index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/couchbasekafka/src/main/java/com/paypal/utils/cb | Create_ds/couchbasekafka/src/main/java/com/paypal/utils/cb/kafka/CBMessageConverter.java | package com.paypal.utils.cb.kafka;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jackson.map.ObjectMapper;
import net.spy.memcached.tapmessage.ResponseMessage;
import com.paypal.cookie.utils.ServerCookieData;
import com.paypal.cookie.utils.CookieHeaders;;
/**
* Converts Couchbase message into flume friendly Event format. *
* @author ssudhakaran
*
*/
public abstract class CBMessageConverter {
public String convert(String key,String message){
return message;
}
}
| 1,600 |
0 | Create_ds/couchbasekafka/src/main/java/com/paypal/utils/cb | Create_ds/couchbasekafka/src/main/java/com/paypal/utils/cb/kafka/CBKafkaProducer.java | package com.paypal.utils.cb.kafka;
import java.io.IOException;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
/**
* CBKafkaProducer uses TAP Client to connect to Couchbase,
* consume message and push to Kafka.
*
* @author ssudhakaran
*
*/
public final class CBKafkaProducer {
/**
* @link http://kafka.apache.org/api-docs/0.6/kafka/producer/ProducerConfig.html
*/
private static ProducerConfig producerConfig;
/**
* @link http://people.apache.org/~joestein/kafka-0.7.1-incubating-docs/kafka/producer/Producer.html
*/
private static Producer<String, String> producer;
private static void init(){
if(producerConfig==null) { producerConfig=new ProducerConfig(ConfigLoader.getKafkaConfigProps());}
if(producer==null) { producer = new Producer<String, String>(producerConfig);}
}
/**
* Check if we have a valid Kafka producer
* @return
*/
public static boolean isValidProducer(){
if(producer !=null) return true;
else {
init();
if(producer !=null) return true;
else return false;
}
}
/**
* Public Message to Kafka Queue
* @param key - Key to Couchbase Document
* @param msg - Body of Couchbase Document.
* @throws IOException
*/
public static void publishMessage(final String key,final String message) throws IOException{
String msg=null;
try {
//If we need to make any Transformation on the message.
if(Boolean.parseBoolean(ConfigLoader.getProp(Constants.ENABLETRANSFORMATION))){
msg = CBMessageTransformerFactory.INSTANCE.createCBMessageConverter().convert(key, message);
}else{
msg=message;
}
} catch (Exception e) {
//If any exception, perform no conversion
}
if(msg!=null && msg.trim().length()>0){
//Wrap KEY/VALUE in JSON -format {\"KEY\":\"<CBKEY>\",\"VALUE\":<CBVALUE>}
String cbmessage=Constants.KAFKA_MESSAGE.replace("[CBKEY]", key);
cbmessage=cbmessage.replace("[CBVALUE]", msg);
KeyedMessage<String, String> data = new KeyedMessage<String, String>(ConfigLoader.getKafkaConfigProps().getProperty(Constants.TOPIC_NAME), key, cbmessage);
//property producer.type indicates async/sync message
if(data!=null) producer.send(data);
}
}
/**
* close producer
*/
public static void closeProducer(){
producer.close();
}
}
| 1,601 |
0 | Create_ds/couchbasekafka/src/main/java/com/paypal/utils/cb | Create_ds/couchbasekafka/src/main/java/com/paypal/utils/cb/kafka/Constants.java | package com.paypal.utils.cb.kafka;
public class Constants {
//------COUCHBASE PROPERTIES------
public static final String BUCKET="cb.bucket";
public static final String CBSERVER="cb.cbserver";
public static final String PASSWORD="cb.password";
public static final String STREAMNAME="cb.streamname";
public static final String STARTDATE = "cb.startdate";
public static final String ISFULLDUMP = "cb.fulldump";
//------KAFKA PROPERTIES--------------
public static final String METADATA_BROKER_LIST="metadata.broker.list";
public static final String SERIALIZER_CLASS="serializer.class";
public static final String PARTITIONER_CLASS="partitioner.class";
public static final String TOPIC_NAME="cookie.topic";
public static final String REQUEST_REQUIRED_ACKS="request.required.acks";
public static final String KAFKA_MESSAGE="{\"KEY\":\"[CBKEY]\",\"VALUE\":[CBVALUE]}\n";
public static final String RESOURCEFILE="./config.properties";
public static final String RESOURCEFILE_KAFKA="./kafkaconfig.properties";
//----KEY FOR FILTERING
public static final String KEYPREFIXFILTER="keyprefixfilter";
//-----Message Converter factory
public static final String CBMESSAGECONVERTER="CBMessageConverter";
public static final String ENABLETRANSFORMATION="enableTransformation";
public static final String ENABLEAVROENCODING="avroEncoding";
public static final int NUM_THREADS=1;
public static final String START_DELAY_SEC="thread.startdelay";
public static final String INTERVAL_SEC="thread.interval";
public static final String INTERVAL_SEC_DEF="120";
}
| 1,602 |
0 | Create_ds/couchbasekafka/src/main/java/com/paypal/cookie | Create_ds/couchbasekafka/src/main/java/com/paypal/cookie/utils/ServerCookieData.java | package com.paypal.cookie.utils;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
public class ServerCookieData {
//Plain header
@JsonProperty("h")
private CookieHeaders headers = new CookieHeaders();
//hash value of email.
@JsonProperty("doctype")
private String doctype="xppp";
//Encrypted body
@JsonProperty("b")
private String body;
public CookieHeaders getHeaders() {
return headers;
}
public void setHeaders(CookieHeaders headers) {
this.headers = headers;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
/**
* @return the doctype
*/
public String getDoctype() {
return doctype;
}
/**
* @param doctype the doctype to set
*/
public void setDoctype(String doctype) {
this.doctype = doctype;
}
}
| 1,603 |
0 | Create_ds/couchbasekafka/src/main/java/com/paypal/cookie | Create_ds/couchbasekafka/src/main/java/com/paypal/cookie/utils/CookieHeaders.java | package com.paypal.cookie.utils;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
/**
* Representation of cookie in the server.
*
*/
@JsonSerialize(include = Inclusion.NON_NULL)
public class CookieHeaders {
//fpti visitor id
@JsonProperty("vid")
private String vid;
//Cookie body length
@JsonProperty("clen")
private long clen;
// Version of the data (incremental number generated and maintained inside x-pp-p cookie)
@JsonProperty("version")
private long version;
// Updated time stamp (UTC)
@JsonProperty("updated")
private long updated;
// Version of the cookie configuration file used to write this document.
@JsonProperty("configVersion")
private String configVersion;
@JsonProperty("docType")
private String docType = "cookie";
@JsonProperty("ua")
private String userAgent;
@JsonProperty("h")
private String host;
//
@JsonProperty("ref")
private String referer;
//from where request came.
@JsonProperty("ru")
private String requestURL;
//content-type
@JsonProperty("a")
private String accept;
//Fetched from request
@JsonProperty("al")
private String acceptLanguage;
//checksum of body
@JsonProperty("cs")
private long checksum;
@JsonProperty("encr")
private int encrypted;
//hash of customer email.
@JsonProperty("eml")
private String email;
//#of cookies we got from browser
@JsonProperty("brcount")
private int brcount;
//#of cookies we got from CB
@JsonProperty("sercount")
private int sercount;
//#of cookies added by app
@JsonProperty("appcount")
private int appcount;
//Size of cookies we got from browser
@JsonProperty("brsize")
private int brsize;
//Size of cookies we got from CB
@JsonProperty("sersize")
private int sersize;
//Size of cookies added by app
@JsonProperty("appsize")
private int appsize;
//ip address of the client
@JsonProperty("ip")
private String ip;
/**
* @return the brcount
*/
public int getBrcount() {
return brcount;
}
/**
* @param brcount the brcount to set
*/
public void setBrcount(int brcount) {
this.brcount = brcount;
}
/**
* @return the sercount
*/
public int getSercount() {
return sercount;
}
/**
* @param sercount the sercount to set
*/
public void setSercount(int sercount) {
this.sercount = sercount;
}
/**
* @return the appcount
*/
public int getAppcount() {
return appcount;
}
/**
* @param appcount the appcount to set
*/
public void setAppcount(int appcount) {
this.appcount = appcount;
}
/**
* @return the brsize
*/
public int getBrsize() {
return brsize;
}
/**
* @param brsize the brsize to set
*/
public void setBrsize(int brsize) {
this.brsize = brsize;
}
/**
* @return the sersize
*/
public int getSersize() {
return sersize;
}
/**
* @param sersize the sersize to set
*/
public void setSersize(int sersize) {
this.sersize = sersize;
}
/**
* @return the appsize
*/
public int getAppsize() {
return appsize;
}
/**
* @param appsize the appsize to set
*/
public void setAppsize(int appsize) {
this.appsize = appsize;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public long getUpdated() {
return updated;
}
public void setUpdated(long updated) {
this.updated = updated;
}
public String getConfigVersion() {
return configVersion;
}
public void setConfigVersion(String configVersion) {
this.configVersion = configVersion;
}
public String getDocType() {
return docType;
}
public void setDocType(String docType) {
this.docType = docType;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public String getHost() {
return host;
}
public String getVid() {
return vid;
}
public void setVid(String vid) {
this.vid = vid;
}
public long getClen() {
return clen;
}
public void setClen(long clen) {
this.clen = clen;
}
public void setHost(String host) {
this.host = host;
}
public String getReferer() {
return referer;
}
public void setReferer(String referer) {
this.referer = referer;
}
public String getRequestURL() {
return requestURL;
}
public void setRequestURL(String requestURL) {
this.requestURL = requestURL;
}
public String getAccept() {
return accept;
}
public void setAccept(String accept) {
this.accept = accept;
}
public String getAcceptLanguage() {
return acceptLanguage;
}
public void setAcceptLanguage(String acceptLanguage) {
this.acceptLanguage = acceptLanguage;
}
public long getChecksum() {
return checksum;
}
public void setChecksum(long checksum) {
this.checksum = checksum;
}
public int getEncrypted() {
return encrypted;
}
public void setEncrypted(int encrypted) {
this.encrypted = encrypted;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@Override
public String toString() {
return "version=" + version +
",updated=" + updated +
",clen=" + clen +
",vid=" + vid +
",configVersion=" + configVersion +
",docType=" + docType +
",userAgent=" + userAgent
+ ", host=" + host
+ ", referer=" + referer
+ ", requestURL=" + requestURL
+ ", accept=" + accept
+ ", acceptLanguage=" + acceptLanguage
+ ", ip=" + ip
;
}
}
| 1,604 |
0 | Create_ds/couchbasekafka/src/main/java/com/paypal/cookie | Create_ds/couchbasekafka/src/main/java/com/paypal/cookie/utils/MetricData.java | package com.paypal.cookie.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
/**
* Metics collected for a Cookie.
* @author ssudhakaran
*
*/
@JsonSerialize(include = Inclusion.NON_NULL)
@JsonIgnoreProperties({"cookieMetrics"})
public class MetricData{
/*
public MetricData(String cookieName){
//keyCookieName is a combination of cookiename with date/time/upto hour.
String keyCookieName=CookieServConstants.COOKIE_ANALYTICS_HEADER+"_"+cookieName+"_"+getCurrentHourUTC();
this.cookieName=keyCookieName;
}*/
public MetricData(){
//dummy constuctor for json deserialization
}
//CookieName
@JsonProperty("cookieName")
private String cookieName;
//Total Count - Total number of Get operations.
@JsonProperty("totalGet")
private AtomicInteger totalGetCount = new AtomicInteger(0);
//Total Count - Total number of Put operations.
@JsonProperty("totalPut")
private AtomicInteger totalPutCount = new AtomicInteger(0);
//Total Count - Total number of Put operations.
@JsonProperty("totalKilled")
private AtomicInteger totalKilledCookieCount = new AtomicInteger(0);
//Count by Flow getmap - Indicates how many times a particular cookie is fetched by a flow.
@JsonProperty("flowGetMap")
private ConcurrentHashMap<String, AtomicInteger> flowgetmap = new ConcurrentHashMap<String, AtomicInteger>();
//private Map<String, AtomicInteger> flowgetmap = new HashMap<String, AtomicInteger>();
//Count by Flow putmap- Indicates how many times a particular cookie is updated by a flow.
@JsonProperty("flowPutMap")
private ConcurrentHashMap<String, AtomicInteger> flowputmap = new ConcurrentHashMap<String, AtomicInteger>();
//private Map<String, AtomicInteger> flowputmap = new HashMap<String, AtomicInteger>();
//Count by Flow putmap- Indicates how many times a particular cookie is updated by a flow.
@JsonProperty("flowKillMap")
private ConcurrentHashMap<String, AtomicInteger> flowkilledcookiemap = new ConcurrentHashMap<String, AtomicInteger>();
//private Map<String, AtomicInteger> flowkilledcookiemap = new HashMap<String, AtomicInteger>();
@JsonIgnore
public Set<String> fetchflowGetMapKeys(){
return flowgetmap.keySet();
}
public Map<String, AtomicInteger> getflowGetMap(){
return flowgetmap;
}
public Map<String, AtomicInteger> getflowPutMap(){
return flowputmap;
}
@JsonIgnore
public Set<String> fetchflowPutMapKeys(){
return flowputmap.keySet();
}
public AtomicInteger getTotalKilledCookieCount() {
return totalKilledCookieCount;
}
public void setTotalKilledCookieCount(AtomicInteger totalKilledCookieCount) {
this.totalKilledCookieCount = totalKilledCookieCount;
}
public String getCookieName() {
return cookieName;
}
public void setCookieName(String cookieName) {
this.cookieName=cookieName;
}
public void assignCookieName(String cookieName) {
String keyCookieName="ca_"+cookieName+"_"+getCurrentHourUTC();
this.cookieName=keyCookieName;
}
/**
* current hour in yyMMddHH format (UTC)
* @return
*/
private String getCurrentHourUTC(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.format(new Date());
}
public void flush(){
totalGetCount.set(0);
totalPutCount.set(0);
flowgetmap.clear();
flowputmap.clear();
}
/**
* Increment flow/get count by 1.
* @param flowName
*/
public void incrementflowGetCount(String flowName){
if(flowName !=null){
if(flowgetmap.containsKey(flowName)){
AtomicInteger flowCounter=flowgetmap.get(flowName);
if(flowCounter!=null)
flowCounter.incrementAndGet();
}else{
//Initialize with number 1
flowgetmap.put(flowName, new AtomicInteger(1));
}
}
}
/**
* get current flow/get count
* @param flowName
*/
public int getflowGetCount(String flowName){
return flowgetmap.get(flowName)!=null?flowgetmap.get(flowName).get():0;
}
/**
* Increment flow/get count by 1.
* @param flowName
*/
public void incrementKilledCookieCount(String flowName){
if(flowName !=null){
if(flowkilledcookiemap.containsKey(flowName)){
AtomicInteger flowCounter=flowkilledcookiemap.get(flowName);
if(flowCounter!=null)
flowCounter.incrementAndGet();
}else{
//Initialize with number 1
flowkilledcookiemap.put(flowName, new AtomicInteger(1));
}
}
}
/**
* get current flow/get count
* @param flowName
*/
public int getflowKilledCookieCount(String flowName){
return flowkilledcookiemap.get(flowName)!=null?flowkilledcookiemap.get(flowName).get():0;
}
/**
* Increment flow/put count
* @param flowName
*/
public void incrementflowPutCount(String flowName){
if(flowName !=null){
if(flowputmap.containsKey(flowName)){
AtomicInteger flowCounter=flowputmap.get(flowName);
if(flowCounter!=null)
flowCounter.incrementAndGet();
}else{
//Initialize with number 1
flowputmap.put(flowName, new AtomicInteger(1));
}
}
}
/**
* Get flow/put count
* @param flowName
* @return
*/
public int getflowPutCount(String flowName){
return flowputmap.get(flowName)!=null?flowputmap.get(flowName).get():0;
}
/**
* Increment Total Get Count
*/
public int incrementTotalGetCount() {
return totalGetCount.incrementAndGet();
}
/**
* Get Total Get Count
* @return
*/
public int valueTotalGetCount() {
return totalGetCount.get();
}
public int incrementTotalKilledCount(){
return totalKilledCookieCount.incrementAndGet();
}
/**
* Increment total number of times this cookie is updated.
* @return
*/
public int incrementTotalPutCount(){
return totalPutCount.incrementAndGet();
}
/**
*
* @return The number of times this cookie is updated.
*/
public int valueTotalPutCount(){
return totalPutCount.get();
}
public ConcurrentMap<String, AtomicInteger> valueFlowGetMap(){
//public Map<String, AtomicInteger> valueFlowGetMap(){
return flowgetmap;
}
public ConcurrentMap<String, AtomicInteger> valueFlowPutMap(){
//public Map<String, AtomicInteger> valueFlowPutMap(){
return flowputmap;
}
public MetricData merge(MetricData metricData) {
// TODO Auto-generated method stub
this.totalGetCount.addAndGet(metricData.totalGetCount.intValue());
this.totalPutCount.addAndGet(metricData.totalPutCount.intValue());
Set<String> keys = new HashSet<String>();
keys.addAll(flowgetmap.keySet());
keys.addAll(metricData.fetchflowGetMapKeys());
for(String flowName:keys){
//flowgetmap.replace(flowName,new AtomicInteger(this.getflowGetCount(flowName)+ metricData.getflowGetCount(flowName)));
flowgetmap.put(flowName,new AtomicInteger(this.getflowGetCount(flowName)+ metricData.getflowGetCount(flowName)));
}
Set<String> keys2 = new HashSet<String>();
keys2.addAll(flowputmap.keySet());
keys2.addAll(metricData.fetchflowPutMapKeys());
for(String flowName:keys2){
//flowputmap.replace(flowName,new AtomicInteger(this.getflowPutCount(flowName)+ metricData.getflowPutCount(flowName)));
flowputmap.put(flowName,new AtomicInteger(this.getflowPutCount(flowName)+ metricData.getflowPutCount(flowName)));
}
return this;
}
}
| 1,605 |
0 | Create_ds/couchbasekafka/src/main/java/com/paypal/cookie | Create_ds/couchbasekafka/src/main/java/com/paypal/cookie/utils/CBCookieMessageConverterImpl.java | package com.paypal.cookie.utils;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import org.apache.commons.codec.binary.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import com.paypal.cookie.utils.ServerCookieData;
import com.paypal.utils.cb.kafka.CBMessageConverter;
import com.paypal.utils.cb.kafka.ConfigLoader;
import com.paypal.utils.cb.kafka.Constants;
/**
* Converts Couchbase message into flume friendly Event format. *
* @author ssudhakaran
*
*/
public class CBCookieMessageConverterImpl extends CBMessageConverter {
private static ObjectMapper objectMapper=null;
public static Charset charset = Charset.forName("UTF-8");
public static CharsetDecoder decoder = charset.newDecoder();
@Override
public String convert(String key,String message) {
try{
if(objectMapper==null) objectMapper=new org.codehaus.jackson.map.ObjectMapper();
//Specific case to extract header from Cookie
if (key.startsWith(ConfigLoader.getProp(Constants.KEYPREFIXFILTER))){
//System.out.println("config :"+ConfigLoader.getProp(Constants.KEYPREFIXFILTER));
ServerCookieData cookiedata=(ServerCookieData) objectMapper.readValue(message, ServerCookieData.class);
byte[] header=objectMapper.writeValueAsBytes(cookiedata.getHeaders());
String cookieMsg= StringUtils.newStringUtf8(header);
return cookieMsg;
}else {
//return the String we received. This is applicable for cases like
//cs_map, analytics document.
return message;
//return null;
}
}catch(org.codehaus.jackson.JsonParseException e){
e.printStackTrace();
return null;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
| 1,606 |
0 | Create_ds/camel-examples/csimple-joor/src/test/java/org/apache/camel | Create_ds/camel-examples/csimple-joor/src/test/java/org/apache/camel/example/CSimpleJOORTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static org.apache.camel.util.PropertiesHelper.asProperties;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that the compiled simple expressions using jooR compiler are evaluated as expected.
*/
class CSimpleJOORTest extends CamelMainTestSupport {
@Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
return asProperties("myPeriod", Integer.toString(500));
}
@Test
void should_be_evaluated() {
NotifyBuilder notify = new NotifyBuilder(context).from("timer:*").whenCompleted(5).create();
assertTrue(
notify.matches(5, TimeUnit.SECONDS), "5 messages should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
}
}
| 1,607 |
0 | Create_ds/camel-examples/csimple-joor/src/main/java/org/apache/camel | Create_ds/camel-examples/csimple-joor/src/main/java/org/apache/camel/example/MyApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.main.Main;
/**
* Main class that boot the Camel application
*/
public final class MyApplication {
private MyApplication() {
}
public static void main(String[] args) throws Exception {
// use Camels Main class
Main main = new Main(MyApplication.class);
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,608 |
0 | Create_ds/camel-examples/csimple-joor/src/main/java/org/apache/camel | Create_ds/camel-examples/csimple-joor/src/main/java/org/apache/camel/example/MyRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.builder.RouteBuilder;
public class MyRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer:foo?period={{myPeriod}}")
.transform(csimple("${random(20)}"))
.choice()
.when(csimple("${bodyAs(int)} > 10"))
.log("high ${body}")
.when(csimple("${bodyAs(int)} > 5"))
.log("med ${body}")
.otherwise()
.log("low ${body}");
}
}
| 1,609 |
0 | Create_ds/camel-examples/java8/src/test/java/org/apache/camel/example | Create_ds/camel-examples/java8/src/test/java/org/apache/camel/example/java8/Java8Test.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.java8;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel supports properly lambda expressions and method references.
*/
class Java8Test extends CamelMainTestSupport {
@Test
void should_be_evaluated() {
NotifyBuilder notify = new NotifyBuilder(context).from("timer:*").whenCompleted(5).create();
assertTrue(
notify.matches(5, TimeUnit.SECONDS), "5 messages should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(new MyApplication.MyRouteBuilder());
}
}
| 1,610 |
0 | Create_ds/camel-examples/java8/src/main/java/org/apache/camel/example | Create_ds/camel-examples/java8/src/main/java/org/apache/camel/example/java8/MyApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.java8;
import java.util.Date;
import java.util.Objects;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class MyApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(MyApplication.class);
private MyApplication() {
}
public static void main(String[] args) throws Exception {
Main main = new Main(MyApplication.class);
main.run(args);
}
static class MyRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer:simple?includeMetadata=true&period=503")
.id("simple-route")
.transform()
.exchange(this::dateToTime)
.process()
.message(this::log)
.process()
.body(this::log)
.choice()
.when()
.body(Integer.class, b -> (b & 1) == 0)
.log("Received even number")
.when()
.body(Integer.class, b -> (b & 1) != 0)
.log("Received odd number")
.when()
.body(Objects::isNull)
.log("Received null body")
.endChoice();
}
private Long dateToTime(Exchange e) {
return e.getProperty(Exchange.TIMER_FIRED_TIME, Date.class).getTime();
}
private void log(Object b) {
LOGGER.info("body is: {}", b);
}
private void log(Message m) {
LOGGER.info("message is: {}", m);
}
}
}
| 1,611 |
0 | Create_ds/camel-examples/kamelet-chucknorris/src/test/java/org/apache/camel | Create_ds/camel-examples/kamelet-chucknorris/src/test/java/org/apache/camel/example/KameletChuckNorrisTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import java.util.concurrent.TimeUnit;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can use a simple Kamelet.
*/
class KameletChuckNorrisTest extends CamelMainTestSupport {
@Test
void should_use_a_simple_kamelet() {
NotifyBuilder notify = new NotifyBuilder(context).whenCompleted(1).create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.withRoutesIncludePattern("camel/*");
}
}
| 1,612 |
0 | Create_ds/camel-examples/ftp/src/test/java/org/apache/camel/example | Create_ds/camel-examples/ftp/src/test/java/org/apache/camel/example/ftp/FtpTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.ftp;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.filesystem.nativefs.NativeFileSystemFactory;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor;
import org.apache.ftpserver.usermanager.impl.PropertiesUserManager;
import org.apache.mina.util.AvailablePortFinder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.camel.test.junit5.TestSupport.createDirectory;
import static org.apache.camel.test.junit5.TestSupport.deleteDirectory;
import static org.apache.camel.util.PropertiesHelper.asProperties;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can read/write from/to a ftp server.
*/
class FtpTest extends CamelMainTestSupport {
private static FtpServer SERVER;
private static int PORT;
@BeforeAll
static void init() throws Exception {
ListenerFactory factory = new ListenerFactory();
PORT = AvailablePortFinder.getNextAvailable();
// set the port of the listener
factory.setPort(PORT);
FtpServerFactory serverFactory = new FtpServerFactory();
// replace the default listener
serverFactory.addListener("default", factory.createListener());
// setup user management to read our users.properties and use clear text passwords
File file = new File("src/test/resources/users.properties");
UserManager userManager = new PropertiesUserManager(new ClearTextPasswordEncryptor(), file, "admin");
serverFactory.setUserManager(userManager);
NativeFileSystemFactory fsf = new NativeFileSystemFactory();
serverFactory.setFileSystem(fsf);
// Create the admin home
createDirectory("./target/ftp-server");
SERVER = serverFactory.createServer();
// start the server
SERVER.start();
}
@AfterAll
static void destroy() {
// Delete directories
deleteDirectory("./target/ftp-server");
deleteDirectory("./target/upload");
if (SERVER != null) {
SERVER.stop();
}
}
@Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
return asProperties(
"ftp.port", Integer.toString(PORT),
"ftp.username", "admin",
"ftp.password", "admin"
);
}
@Test
void should_download_uploaded_file() throws IOException {
String fileName = UUID.randomUUID().toString();
assertTrue(
new File(String.format("target/upload/%s", fileName)).createNewFile(),
"The test file should be created"
);
NotifyBuilder notify = new NotifyBuilder(context)
.whenCompleted(1).wereSentTo("ftp:*")
.and().whenCompleted(1).wereSentTo("file:*").create();
assertTrue(
notify.matches(30, TimeUnit.SECONDS), "1 file should be transferred with success"
);
assertTrue(
new File(String.format("target/download/%s", fileName)).exists(),
"The test file should be uploaded"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyFtpClientRouteBuilder.class, MyFtpServerRouteBuilder.class);
}
}
| 1,613 |
0 | Create_ds/camel-examples/ftp/src/main/java/org/apache/camel/example | Create_ds/camel-examples/ftp/src/main/java/org/apache/camel/example/ftp/MyFtpClientRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.ftp;
import org.apache.camel.builder.RouteBuilder;
/**
* Client route
*/
public class MyFtpClientRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
// configure properties component
getContext().getPropertiesComponent().setLocation("classpath:ftp.properties");
// lets shutdown faster in case of in-flight messages stack up
getContext().getShutdownStrategy().setTimeout(10);
from("file:target/upload?moveFailed=../error")
.log("Uploading file ${file:name}")
.to("{{ftp.client}}")
.log("Uploaded file ${file:name} complete.");
// use system out so it stand out
System.out.println("*********************************************************************************");
System.out.println("Camel will route files from target/upload directory to the FTP server: "
+ getContext().resolvePropertyPlaceholders("{{ftp.server}}"));
System.out.println("You can configure the location of the ftp server in the src/main/resources/ftp.properties file.");
System.out.println("If the file upload fails, then the file is moved to the target/error directory.");
System.out.println("Use ctrl + c to stop this application.");
System.out.println("*********************************************************************************");
}
}
| 1,614 |
0 | Create_ds/camel-examples/ftp/src/main/java/org/apache/camel/example | Create_ds/camel-examples/ftp/src/main/java/org/apache/camel/example/ftp/MyFtpServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.ftp;
import org.apache.camel.main.Main;
/**
* Main class that can download files from an existing FTP server.
*/
public final class MyFtpServer {
private MyFtpServer() {
}
public static void main(String[] args) throws Exception {
Main main = new Main(MyFtpServer.class);
main.run();
}
}
| 1,615 |
0 | Create_ds/camel-examples/ftp/src/main/java/org/apache/camel/example | Create_ds/camel-examples/ftp/src/main/java/org/apache/camel/example/ftp/MyFtpServerRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.ftp;
import org.apache.camel.builder.RouteBuilder;
/**
* Server route
*/
public class MyFtpServerRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
// configure properties component
getContext().getPropertiesComponent().setLocation("classpath:ftp.properties");
// lets shutdown faster in case of in-flight messages stack up
getContext().getShutdownStrategy().setTimeout(10);
from("{{ftp.server}}")
.to("file:target/download")
.log("Downloaded file ${file:name} complete.");
// use system out so it stand out
System.out.println("*********************************************************************************");
System.out.println("Camel will route files from the FTP server: "
+ getContext().resolvePropertyPlaceholders("{{ftp.server}}") + " to the target/download directory.");
System.out.println("You can configure the location of the ftp server in the src/main/resources/ftp.properties file.");
System.out.println("Use ctrl + c to stop this application.");
System.out.println("*********************************************************************************");
}
}
| 1,616 |
0 | Create_ds/camel-examples/ftp/src/main/java/org/apache/camel/example | Create_ds/camel-examples/ftp/src/main/java/org/apache/camel/example/ftp/MyFtpClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.ftp;
import org.apache.camel.main.Main;
/**
* Main class that can upload files to an existing FTP server.
*/
public final class MyFtpClient {
private MyFtpClient() {
}
public static void main(String[] args) throws Exception {
Main main = new Main(MyFtpClient.class);
main.run();
}
}
| 1,617 |
0 | Create_ds/camel-examples/routes-configuration/src/test/java/org/apache/camel | Create_ds/camel-examples/routes-configuration/src/test/java/org/apache/camel/example/RoutesConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import java.util.concurrent.TimeUnit;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can load routes dynamically.
*/
class RoutesConfigurationTest extends CamelMainTestSupport {
@Test
void should_load_routes_dynamically() {
NotifyBuilder notify = new NotifyBuilder(context)
.from("timer:xml*").whenCompleted(1)
.and().from("timer:java*").whenCompleted(1)
.and().from("timer:yaml*").whenCompleted(1).create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "3 messages should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyJavaRouteBuilder.class, MyJavaErrorHandler.class);
}
}
| 1,618 |
0 | Create_ds/camel-examples/routes-configuration/src/main/java/org/apache/camel | Create_ds/camel-examples/routes-configuration/src/main/java/org/apache/camel/example/MyApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.main.Main;
/**
* Main class that boot the Camel application.
*/
public final class MyApplication {
private MyApplication() {
}
public static void main(String[] args) throws Exception {
// use Camels Main class
Main main = new Main();
// add Java route classes
main.configure().addRoutesBuilder(MyJavaRouteBuilder.class, MyJavaErrorHandler.class);
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,619 |
0 | Create_ds/camel-examples/routes-configuration/src/main/java/org/apache/camel | Create_ds/camel-examples/routes-configuration/src/main/java/org/apache/camel/example/MyJavaErrorHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.builder.RouteConfigurationBuilder;
/**
* Route configuration for error handling.
*/
public class MyJavaErrorHandler extends RouteConfigurationBuilder {
@Override
public void configuration() throws Exception {
routeConfiguration("javaError")
.onException(Exception.class).handled(true)
.log("Java WARN: ${exception.message}");
}
}
| 1,620 |
0 | Create_ds/camel-examples/routes-configuration/src/main/java/org/apache/camel | Create_ds/camel-examples/routes-configuration/src/main/java/org/apache/camel/example/MyJavaRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import java.util.Random;
import org.apache.camel.builder.RouteBuilder;
public class MyJavaRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer:java?period=2s")
// refer to the route configuration by the id to use for this route
.routeConfigurationId("javaError")
.setBody(method(MyJavaRouteBuilder.class, "randomNumber"))
.log("Random number ${body}")
.filter(simple("${body} < 30"))
.throwException(new IllegalArgumentException("The number is too low"));
}
public static int randomNumber() {
return new Random().nextInt(100);
}
}
| 1,621 |
0 | Create_ds/camel-examples/debezium-eventhubs-blob/src/main/java/org/apache/camel/example/debezium/eventhubs/blob | Create_ds/camel-examples/debezium-eventhubs-blob/src/main/java/org/apache/camel/example/debezium/eventhubs/blob/producer/AzureEventHubsProducerToAzureBlob.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.debezium.eventhubs.blob.producer;
import org.apache.camel.main.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple example to sink data from Azure Event Hubs that produced by Debezium into Azure Storage Blob
*/
public final class AzureEventHubsProducerToAzureBlob {
private static final Logger LOG = LoggerFactory.getLogger(AzureEventHubsProducerToAzureBlob.class);
private AzureEventHubsProducerToAzureBlob() {
}
public static void main(String[] args) throws Exception {
LOG.debug("About to run Event Hubs to Storage Blob integration..");
// use Camels Main class
Main main = new Main(AzureEventHubsProducerToAzureBlob.class);
// start and run Camel (block)
main.run();
}
}
| 1,622 |
0 | Create_ds/camel-examples/debezium-eventhubs-blob/src/main/java/org/apache/camel/example/debezium/eventhubs/blob | Create_ds/camel-examples/debezium-eventhubs-blob/src/main/java/org/apache/camel/example/debezium/eventhubs/blob/producer/AzureEventHubsProducerToAzureBlobRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.camel.example.debezium.eventhubs.blob.producer;
import org.apache.camel.builder.RouteBuilder;
public class AzureEventHubsProducerToAzureBlobRouteBuilder extends RouteBuilder {
@Override
public void configure() {
from("azure-eventhubs:?connectionString=RAW({{eventhubs.connectionString}})"
+ "&blobContainerName={{blob.containerName}}"
+ "&blobAccountName={{blob.accountName}}"
+ "&blobAccessKey=RAW({{blob.accessKey}})")
// write our data to Azure Blob Storage but committing to an existing append blob
.to("azure-storage-blob://{{blob.accountName}}/{{blob.containerName}}?operation=commitAppendBlob"
+ "&accessKey=RAW({{blob.accessKey}})"
+ "&blobName={{blob.blobName}}")
.end();
}
}
| 1,623 |
0 | Create_ds/camel-examples/debezium-eventhubs-blob/src/main/java/org/apache/camel/example/debezium/eventhubs/blob | Create_ds/camel-examples/debezium-eventhubs-blob/src/main/java/org/apache/camel/example/debezium/eventhubs/blob/consumer/DebeziumMySqlConsumerToAzureEventHubs.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.debezium.eventhubs.blob.consumer;
import org.apache.camel.main.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple example to consume data from Debezium and send it to Azure EventHubs
*/
public final class DebeziumMySqlConsumerToAzureEventHubs {
private static final Logger LOG = LoggerFactory.getLogger(DebeziumMySqlConsumerToAzureEventHubs.class);
private DebeziumMySqlConsumerToAzureEventHubs() {
}
public static void main(String[] args) throws Exception {
LOG.debug("About to run Debezium integration...");
// use Camels Main class
Main main = new Main(DebeziumMySqlConsumerToAzureEventHubs.class);
// start and run Camel (block)
main.run();
}
}
| 1,624 |
0 | Create_ds/camel-examples/debezium-eventhubs-blob/src/main/java/org/apache/camel/example/debezium/eventhubs/blob | Create_ds/camel-examples/debezium-eventhubs-blob/src/main/java/org/apache/camel/example/debezium/eventhubs/blob/consumer/DebeziumMySqlConsumerToAzureEventHubsRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.camel.example.debezium.eventhubs.blob.consumer;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.azure.eventhubs.EventHubsConstants;
import org.apache.camel.component.debezium.DebeziumConstants;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.kafka.connect.data.Struct;
import java.util.HashMap;
import java.util.Map;
public class DebeziumMySqlConsumerToAzureEventHubsRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
// Initial Debezium route that will run and listens to the changes,
// first it will perform an initial snapshot using (select * from) in case there are no offsets
// exists for the connector, and then it will listen to MySQL binlogs for any DB events such as (UPDATE, INSERT and DELETE)
from("debezium-mysql:{{debezium.mysql.name}}?"
+ "databaseServerId={{debezium.mysql.databaseServerId}}"
+ "&databaseHostname={{debezium.mysql.databaseHostName}}"
+ "&databasePort={{debezium.mysql.databasePort}}"
+ "&databaseUser={{debezium.mysql.databaseUser}}"
+ "&databasePassword={{debezium.mysql.databasePassword}}"
+ "&databaseServerName={{debezium.mysql.databaseServerName}}"
+ "&databaseHistoryFileFilename={{debezium.mysql.databaseHistoryFileName}}"
+ "&databaseIncludeList={{debezium.mysql.databaseIncludeList}}"
+ "&tableIncludeList={{debezium.mysql.tableIncludeList}}"
+ "&offsetStorageFileName={{debezium.mysql.offsetStorageFileName}}")
.routeId("FromDebeziumMySql")
// We will need to prepare the data for Azure EventHubs Therefore, we will hash the key to make sure our record land on the same partition
// and convert it to string, but that means we need to preserve the key information into the message body in order not to lose this information downstream.
// Note: If you'd use Kafka, most probably you will not need these transformations as you can send the key as an object and Kafka will do
// the rest to hash it in the broker in order to place it in the correct topic's partition.
.setBody(exchange -> {
// Using Camel Data Format, we can retrieve our data in Map since Debezium component has a Type Converter from Struct to Map, you need to specify the Map.class
// in order to convert the data from Struct to Map
final Map key = exchange.getMessage().getHeader(DebeziumConstants.HEADER_KEY, Map.class);
final Map value = exchange.getMessage().getBody(Map.class);
// Also, we need the operation in order to determine when an INSERT, UPDATE or DELETE happens
final String operation = (String) exchange.getMessage().getHeader(DebeziumConstants.HEADER_OPERATION);
// We we will put everything as nested Map in order to utilize Camel's Type Format
final Map<String, Object> eventHubBody = new HashMap<>();
eventHubBody.put("key", key);
eventHubBody.put("value", value);
eventHubBody.put("operation", operation);
return eventHubBody;
})
// As we mentioned above, we will need to hash the key partition and set it into the headers
.process(exchange -> {
final Struct key = (Struct) exchange.getMessage().getHeader(DebeziumConstants.HEADER_KEY);
final String hash = String.valueOf(key.hashCode());
exchange.getMessage().setHeader(EventHubsConstants.PARTITION_KEY, hash);
})
// Marshal everything to JSON, you can use any other data format such as Avro, Protobuf..etc, but in this example we will keep it to JSON for simplicity
.marshal().json(JsonLibrary.Jackson)
// Send our data to Azure Event Hubs
.to("azure-eventhubs:?connectionString=RAW({{eventhubs.connectionString}})")
.end();
}
}
| 1,625 |
0 | Create_ds/camel-examples/jooq/src/test/java/org/apache/camel/examples | Create_ds/camel-examples/jooq/src/test/java/org/apache/camel/examples/jooq/JOOQTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.examples.jooq;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.test.spring.junit5.CamelSpringTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test allowing to check that Camel can rely on jOOQ to execute CRUD operations.
*/
@CamelSpringTest
@ContextConfiguration("/META-INF/spring/camel-context.xml")
class JOOQTest {
@Autowired
ModelCamelContext context;
@Test
void should_execute_crud_operations() {
NotifyBuilder notify = new NotifyBuilder(context).fromRoute("produce-route").whenCompleted(3)
.and().fromRoute("consume-route").whenCompleted(3).create();
assertTrue(
notify.matches(10, TimeUnit.SECONDS), "3 messages should be completed"
);
}
}
| 1,626 |
0 | Create_ds/camel-examples/jooq/src/main/java/org/apache/camel/examples | Create_ds/camel-examples/jooq/src/main/java/org/apache/camel/examples/jooq/BookStoreRecordBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.examples.jooq;
import org.apache.camel.examples.jooq.db.tables.records.BookStoreRecord;
import org.jooq.ResultQuery;
import org.jooq.impl.DSL;
import org.springframework.stereotype.Component;
import static org.apache.camel.examples.jooq.db.tables.BookStore.BOOK_STORE;
@Component
public class BookStoreRecordBean {
private String name;
public BookStoreRecord generate() {
this.name = "test_" + System.currentTimeMillis();
return new BookStoreRecord(name);
}
public ResultQuery select() {
return DSL.selectFrom(BOOK_STORE).where(BOOK_STORE.NAME.eq(name));
}
}
| 1,627 |
0 | Create_ds/camel-examples/salesforce-consumer/src/main/java/org/apache/camel/example | Create_ds/camel-examples/salesforce-consumer/src/main/java/org/apache/camel/example/salesforce/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.salesforce;
import org.apache.camel.main.Main;
public final class Application {
private Application() {
// noop
}
public static void main(String[] args) throws Exception {
Main camelMain = new Main();
camelMain.configure().addRoutesBuilder(new SalesforceRouteBuilder());
camelMain.run(args);
}
}
| 1,628 |
0 | Create_ds/camel-examples/salesforce-consumer/src/main/java/org/apache/camel/example | Create_ds/camel-examples/salesforce-consumer/src/main/java/org/apache/camel/example/salesforce/SalesforceRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.salesforce;
import org.apache.camel.builder.RouteBuilder;
public class SalesforceRouteBuilder extends RouteBuilder {
@Override
public void configure() {
from("salesforce:{{salesforce.topic}}")
.unmarshal().json()
.choice()
.when(header("CamelSalesforceEventType").isEqualTo("created"))
.log("New Salesforce contact was created: [ID:${body[Id]}, Name:${body[Name]}, Email:${body[Email]}, Phone: ${body[Phone]}]")
.when(header("CamelSalesforceEventType").isEqualTo("updated"))
.log("A Salesforce contact was updated: [ID:${body[Id]}, Name:${body[Name]}, Email:${body[Email]}, Phone: ${body[Phone]}]")
.when(header("CamelSalesforceEventType").isEqualTo("undeleted"))
.log("A Salesforce contact was undeleted: [ID:${body[Id]}, Name:${body[Name]}, Email:${body[Email]}, Phone: ${body[Phone]}]")
.when(header("CamelSalesforceEventType").isEqualTo("deleted"))
.log("A Salesforce contact was deleted: [ID:${body[Id]}]");
}
}
| 1,629 |
0 | Create_ds/camel-examples/mapstruct/src/main/java/org/apache/camel | Create_ds/camel-examples/mapstruct/src/main/java/org/apache/camel/example/MyBeanEnricher.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.example.model.Beverage;
public class MyBeanEnricher {
public void enrich(Beverage bev) {
// we can also use regular Java to modify the pojo
bev.setCategory("beer");
}
}
| 1,630 |
0 | Create_ds/camel-examples/mapstruct/src/main/java/org/apache/camel | Create_ds/camel-examples/mapstruct/src/main/java/org/apache/camel/example/MyRoute.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.example.model.Beer;
import org.apache.camel.example.model.Beverage;
import org.apache.camel.model.rest.RestBindingMode;
public class MyRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
// use json binding in rest service
restConfiguration()
.host("localhost")
.port(8080)
.bindingMode(RestBindingMode.json);
rest("/beer")
.post()
.type(Beer.class)
.outType(Beverage.class)
.to("direct:beer");
from("direct:beer")
// use type converter which triggers mapstruct to map from Beer to Beverage
.convertBodyTo(Beverage.class)
.bean(MyBeanEnricher.class);
}
}
| 1,631 |
0 | Create_ds/camel-examples/mapstruct/src/main/java/org/apache/camel | Create_ds/camel-examples/mapstruct/src/main/java/org/apache/camel/example/MyApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.main.Main;
/**
* Main class that boot the Camel application
*/
public final class MyApplication {
private MyApplication() {
}
public static void main(String[] args) throws Exception {
// use Camels Main class
Main main = new Main(MyApplication.class);
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,632 |
0 | Create_ds/camel-examples/mapstruct/src/main/java/org/apache/camel/example | Create_ds/camel-examples/mapstruct/src/main/java/org/apache/camel/example/mapper/BeerMapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.mapper;
import org.apache.camel.example.model.Beer;
import org.apache.camel.example.model.Beverage;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@Mapper
public interface BeerMapper {
@Mapping(source = "style", target = "category")
@Mapping(source = "alcohol", target = "strength")
Beverage toBeverage(Beer beer);
}
| 1,633 |
0 | Create_ds/camel-examples/flight-recorder/src/test/java/org/apache/camel | Create_ds/camel-examples/flight-recorder/src/test/java/org/apache/camel/example/FlightRecorderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.main.Main;
import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* A unit test allowing to check that the flight recorder is launched as expected.
*/
class FlightRecorderTest {
@Test
void should_launch_flight_recorder() throws Exception {
long before = Files.list(Paths.get(".")).filter(p -> p.toString().endsWith(".jfr")).count();
// use Camels Main class
Main main = new Main(FlightRecorderTest.class);
try {
main.start();
} finally {
main.stop();
}
long after = Files.list(Paths.get(".")).filter(p -> p.toString().endsWith(".jfr")).count();
assertEquals(1L, after - before, "A flight recorder file should have been created");
}
}
| 1,634 |
0 | Create_ds/camel-examples/flight-recorder/src/main/java/org/apache/camel | Create_ds/camel-examples/flight-recorder/src/main/java/org/apache/camel/example/MyApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.main.Main;
/**
* Main class that boot the Camel application
*/
public final class MyApplication {
private MyApplication() {
}
public static void main(String[] args) throws Exception {
// use Camels Main class
Main main = new Main(MyApplication.class);
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,635 |
0 | Create_ds/camel-examples/flight-recorder/src/main/java/org/apache/camel | Create_ds/camel-examples/flight-recorder/src/main/java/org/apache/camel/example/MyRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.builder.RouteBuilder;
public class MyRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer:foo?period={{myPeriod}}")
.to("log:fast?level=OFF")
.to("direct:slow")
.log("${body}");
from("direct:slow")
.to("log:slow?level=OFF")
.bean(MyBean.class, "hello");
}
}
| 1,636 |
0 | Create_ds/camel-examples/flight-recorder/src/main/java/org/apache/camel | Create_ds/camel-examples/flight-recorder/src/main/java/org/apache/camel/example/MyBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyBean {
private static final Logger LOG = LoggerFactory.getLogger(MyBean.class);
public MyBean() {
// force slow startup
try {
LOG.warn("Forcing 2 sec delay to have slow startup");
Thread.sleep(2000);
} catch (Exception e) {
// ignore
}
}
public String hello() {
return "Hello how are you?";
}
}
| 1,637 |
0 | Create_ds/camel-examples/cassandra-kubernetes/src/main/java/org/apache/camel/example/kubernetes | Create_ds/camel-examples/cassandra-kubernetes/src/main/java/org/apache/camel/example/kubernetes/jkube/CqlPopulateBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.kubernetes.jkube;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CqlPopulateBean {
private static final Logger log = LoggerFactory.getLogger(CqlPopulateBean.class);
public void populate() {
try (Cluster cluster = Cluster.builder().addContactPoint("cassandra").build();
Session session = cluster.connect()) {
session.execute("CREATE KEYSPACE IF NOT EXISTS test WITH REPLICATION = {'class':'SimpleStrategy', 'replication_factor':1};");
session.execute("CREATE TABLE IF NOT EXISTS test.users ( id int primary key, name text );");
session.execute("INSERT INTO test.users (id,name) VALUES (1, 'oscerd') IF NOT EXISTS;");
session.execute("INSERT INTO test.users (id,name) VALUES (2, 'not-a-bot') IF NOT EXISTS;");
}
log.info("Cassandra was populated with sample values for test.users table");
}
}
| 1,638 |
0 | Create_ds/camel-examples/cassandra-kubernetes/src/main/java/org/apache/camel/example/kubernetes | Create_ds/camel-examples/cassandra-kubernetes/src/main/java/org/apache/camel/example/kubernetes/jkube/RowProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.kubernetes.jkube;
import com.datastax.oss.driver.api.core.cql.Row;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import java.util.List;
import java.util.stream.Collectors;
public class RowProcessor implements Processor {
@SuppressWarnings("unchecked")
@Override
public void process(Exchange exchange) {
final List<Row> rows = exchange.getIn().getBody(List.class);
exchange.getIn().setBody(rows.stream()
.map(row -> String.format("%s-%s", row.getInt("id"), row.getString("name")))
.collect(Collectors.joining(","))
);
}
}
| 1,639 |
0 | Create_ds/camel-examples/aggregate-dist/src/test/java/org/apache/camel | Create_ds/camel-examples/aggregate-dist/src/test/java/org/apache/camel/example/AggregateDistributedTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test allowing to check that the aggregation distributed works as expected.
*/
class AggregateDistributedTest {
@Test
void should_aggregate() throws Exception {
assertTrue(new Application().asyncLaunch().get(30, TimeUnit.SECONDS));
}
}
| 1,640 |
0 | Create_ds/camel-examples/aggregate-dist/src/main/java/org/apache/camel | Create_ds/camel-examples/aggregate-dist/src/main/java/org/apache/camel/example/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.LoggingLevel;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.processor.aggregate.jdbc.JdbcAggregationRepository;
import org.apache.camel.spi.AggregationRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public final class Application {
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
private static final int THREADS = 20;
private static final int END = 100;
private static final String CID_HEADER = "corrId";
private static final String DB_URL = "jdbc:derby:target/testdb;create=true";
private static final String DB_USER = "admin";
private static final String DB_PASS = "admin";
private final String correlationId;
private final String expectedResult;
private final Queue<Integer> inputQueue;
private final CountDownLatch latch;
private final ExecutorService executor;
public Application() {
this.correlationId = UUID.randomUUID().toString();
this.expectedResult = IntStream.rangeClosed(1, END)
.mapToObj(Integer::toString).collect(Collectors.joining("."));
this.inputQueue = new ConcurrentLinkedQueue<>();
this.latch = new CountDownLatch(THREADS);
this.executor = Executors.newFixedThreadPool(THREADS);
}
public boolean launch() {
try {
// init
IntStream.rangeClosed(1, END).forEach(inputQueue::add);
// test
for (int i = 0; i < THREADS; i++) {
executor.execute(this::startCamel);
}
// wait
latch.await();
stop();
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.error("The test has been interrupted", e);
}
return false;
}
public Future<Boolean> asyncLaunch() {
return CompletableFuture.supplyAsync(this::launch);
}
public static void main(String[] args) {
new Application().launch();
}
private void startCamel() {
try {
Main camel = new Main();
camel.configure().addRoutesBuilder(new RouteBuilder() {
@Override
public void configure() {
from("timer:foo?repeatCount=1&period=1")
.setExchangePattern(ExchangePattern.InOnly)
.bean(new MyProducerBean());
from("direct:aggregator")
.filter(body().isNotNull())
.aggregate().header(CID_HEADER)
.aggregationStrategy(Application.this::aggregationStrategy)
.completionPredicate(Application.this::completionPredicate)
.aggregationRepository(getAggregationRepository())
.optimisticLocking()
.log(LoggingLevel.INFO, "Result: ${body}");
}
});
camel.start();
LOG.debug("Camel started");
latch.await();
camel.stop();
LOG.debug("Camel stopped");
} catch (Exception e) {
LOG.error("Failed to start Camel: {}", e.getMessage());
}
}
private static AggregationRepository getAggregationRepository() {
SingleConnectionDataSource ds = new SingleConnectionDataSource(DB_URL, DB_USER, DB_PASS, true);
ds.setAutoCommit(false);
try (Connection conn = ds.getConnection();
Statement statement = conn.createStatement()){
statement.execute(
"create table aggregation("
+ "id varchar(255) not null primary key,"
+ "exchange blob not null,"
+ "version bigint not null"
+ ")");
statement.execute(
"create table aggregation_completed("
+ "id varchar(255) not null primary key,"
+ "exchange blob not null,"
+ "version bigint not null"
+ ")");
} catch (SQLException e) {
if (!e.getMessage().contains("already exists")) {
LOG.error("Database initialization failure", e);
}
}
DataSourceTransactionManager txManager = new DataSourceTransactionManager(ds);
// repositoryName (aggregation) must match tableName (aggregation, aggregation_completed)
JdbcAggregationRepository repo = new JdbcAggregationRepository(txManager, "aggregation", ds);
repo.setUseRecovery(false);
repo.setStoreBodyAsText(false);
return repo;
}
private Exchange aggregationStrategy(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
String body = oldExchange.getIn().getBody(String.class) + "."
+ newExchange.getIn().getBody(String.class);
oldExchange.getIn().setBody(body);
LOG.trace("Queue: {}", inputQueue);
LOG.trace("Aggregation: {}", oldExchange.getIn().getBody());
return oldExchange;
}
private boolean completionPredicate(Exchange exchange) {
boolean isComplete = false;
final String body = exchange.getIn().getBody(String.class);
if (body != null && !body.isEmpty()) {
String[] a1 = body.split("\\.");
String[] a2 = expectedResult.split("\\.");
if (a1.length == a2.length) {
Arrays.sort(a1);
Arrays.sort(a2);
isComplete = Arrays.equals(a1, a2);
}
}
LOG.debug("Complete? {}", isComplete);
return isComplete;
}
private void stop() {
try {
executor.shutdown();
executor.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.error("Termination interrupted");
} finally {
if (executor.isTerminated()) {
LOG.debug("All tasks completed");
} else {
LOG.error("Forcing shutdown of tasks");
executor.shutdownNow();
}
}
}
class MyProducerBean {
public void run(Exchange exchange) {
CamelContext context = exchange.getContext();
try (ProducerTemplate template = context.createProducerTemplate()) {
template.setThreadedAsyncMode(false);
Endpoint endpoint = context.getEndpoint("direct:aggregator");
Integer item;
while ((item = inputQueue.poll()) != null) {
template.sendBodyAndHeader(endpoint, item, CID_HEADER, correlationId);
}
template.stop();
} catch (IOException e) {
LOG.error("Error during execution");
}
latch.countDown();
}
}
}
| 1,641 |
0 | Create_ds/camel-examples/as2/src/test/java/org/apache/camel/example | Create_ds/camel-examples/as2/src/test/java/org/apache/camel/example/as2/As2Test.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.as2;
import java.util.concurrent.TimeUnit;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.test.spring.junit5.CamelSpringTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that the Camel works as expected with AS2.
*/
@CamelSpringTest
@ContextConfiguration("/META-INF/spring/camel-context.xml")
class As2Test {
@Autowired
ModelCamelContext context;
@Test
void should_consume_and_produce_as2_messages() {
NotifyBuilder notify = new NotifyBuilder(context).fromRoute("server-route")
.whenCompleted(8).create();
assertTrue(
notify.matches(30, TimeUnit.SECONDS), "8 messages should be received by the AS2 server"
);
}
}
| 1,642 |
0 | Create_ds/camel-examples/as2/src/main/java/org/apache/camel/example | Create_ds/camel-examples/as2/src/main/java/org/apache/camel/example/as2/ProvisionAS2ComponentCrypto.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.as2;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.as2.AS2Component;
import org.apache.camel.component.as2.AS2Configuration;
import org.apache.camel.component.as2.api.AS2CompressionAlgorithm;
import org.apache.camel.component.as2.api.AS2EncryptionAlgorithm;
import org.apache.camel.component.as2.api.AS2SignatureAlgorithm;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class ProvisionAS2ComponentCrypto implements CamelContextAware {
private KeyPair issueKP;
private X509Certificate issueCert;
private KeyPair signingKP;
private KeyPair decryptingKP;
private X509Certificate clientCert;
private List<X509Certificate> certList;
@Override
public void setCamelContext(CamelContext camelContext) {
try {
setupKeysAndCertificates();
} catch (Exception e) {
throw new RuntimeCamelException("failed to initialized Camel context for AS component", e);
}
AS2Component as2Component = camelContext.getComponent("as2", AS2Component.class);
AS2Configuration configuration = new AS2Configuration();
configuration.setSigningAlgorithm(AS2SignatureAlgorithm.SHA512WITHRSA);
configuration.setSigningCertificateChain(certList.toArray(new Certificate[0]));
configuration.setSigningPrivateKey(signingKP.getPrivate());
configuration.setSignedReceiptMicAlgorithms(new String[] {"sha1", "md5"});
configuration.setEncryptingAlgorithm(AS2EncryptionAlgorithm.AES128_CBC);
configuration.setEncryptingCertificateChain(certList.toArray(new Certificate[0]));
configuration.setDecryptingPrivateKey(decryptingKP.getPrivate());
configuration.setCompressionAlgorithm(AS2CompressionAlgorithm.ZLIB);
as2Component.setConfiguration(configuration);
}
@Override
public CamelContext getCamelContext() {
return null;
}
private void setupKeysAndCertificates() throws Exception {
Security.addProvider(new BouncyCastleProvider());
//
// set up our certificates
//
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
kpg.initialize(1024, new SecureRandom());
String issueDN = "O=Punkhorn Software, C=US";
issueKP = kpg.generateKeyPair();
issueCert = Utils.makeCertificate(issueKP, issueDN, issueKP, issueDN);
//
// certificate we sign against
//
String signingDN = "CN=William J. Collins, E=punkhornsw@gmail.com, O=Punkhorn Software, C=US";
signingKP = kpg.generateKeyPair();
clientCert = Utils.makeCertificate(signingKP, signingDN, issueKP, issueDN);
certList = new ArrayList<>();
certList.add(clientCert);
certList.add(issueCert);
// keys used to encrypt/decrypt
decryptingKP = signingKP;
}
}
| 1,643 |
0 | Create_ds/camel-examples/as2/src/main/java/org/apache/camel/example | Create_ds/camel-examples/as2/src/main/java/org/apache/camel/example/as2/Utils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.as2;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.Date;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.bc.BcX509ExtensionUtils;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
public final class Utils {
//
// certificate serial number seed.
//
static int serialNo = 1;
private Utils() {
}
public static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey pub) {
SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(pub.getEncoded());
BcX509ExtensionUtils utils = new BcX509ExtensionUtils();
return utils.createAuthorityKeyIdentifier(info);
}
public static SubjectKeyIdentifier createSubjectKeyId(PublicKey pub) {
SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(pub.getEncoded());
return new BcX509ExtensionUtils().createSubjectKeyIdentifier(info);
}
/**
* create a basic X509 certificate from the given keys
*/
public static X509Certificate makeCertificate(KeyPair subKP, String subDN, KeyPair issKP, String issDN)
throws GeneralSecurityException, IOException, OperatorCreationException {
PublicKey subPub = subKP.getPublic();
PrivateKey issPriv = issKP.getPrivate();
PublicKey issPub = issKP.getPublic();
X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name(issDN),
BigInteger.valueOf(serialNo++), new Date(System.currentTimeMillis()),
new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), new X500Name(subDN), subPub);
v3CertGen.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(subPub));
v3CertGen.addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(issPub));
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(
v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(issPriv)));
}
}
| 1,644 |
0 | Create_ds/camel-examples/as2/src/main/java/org/apache/camel/example | Create_ds/camel-examples/as2/src/main/java/org/apache/camel/example/as2/ProvisionExchangeMessageCrypto.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.as2;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.component.as2.AS2Component;
import org.apache.camel.component.as2.AS2Configuration;
public class ProvisionExchangeMessageCrypto implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
AS2Component component = exchange.getContext().getComponent("as2", AS2Component.class);
AS2Configuration configuration = component.getConfiguration();
exchange.getIn().setHeader("CamelAS2.signingAlgorithm", configuration.getSigningAlgorithm());
exchange.getIn().setHeader("CamelAS2.signingCertificateChain", configuration.getSigningCertificateChain());
exchange.getIn().setHeader("CamelAS2.signingPrivateKey", configuration.getSigningPrivateKey());
exchange.getIn().setHeader("CamelAS2.signedReceiptMicAlgorithms", configuration.getSignedReceiptMicAlgorithms());
exchange.getIn().setHeader("CamelAS2.encryptingAlgorithm", configuration.getEncryptingAlgorithm());
exchange.getIn().setHeader("CamelAS2.encryptingCertificateChain", configuration.getEncryptingCertificateChain());
exchange.getIn().setHeader("CamelAS2.decryptingPrivateKey", configuration.getDecryptingPrivateKey());
exchange.getIn().setHeader("CamelAS2.compressionAlgorithm", configuration.getCompressionAlgorithm());
}
}
| 1,645 |
0 | Create_ds/camel-examples/as2/src/main/java/org/apache/camel/example | Create_ds/camel-examples/as2/src/main/java/org/apache/camel/example/as2/ExamineAS2ServerEndpointExchange.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.as2;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.component.as2.api.util.AS2Utils;
import org.apache.camel.component.as2.internal.AS2Constants;
import org.apache.http.HttpRequest;
import org.apache.http.protocol.HttpCoreContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExamineAS2ServerEndpointExchange implements Processor {
private final transient Logger log = LoggerFactory.getLogger(getClass());
@Override
public void process(Exchange exchange) throws Exception {
HttpCoreContext context = exchange.getProperty(AS2Constants.AS2_INTERCHANGE, HttpCoreContext.class);
String ediMessage = exchange.getIn().getBody(String.class);
if (context != null) {
HttpRequest request = context.getRequest();
log.info("\n*******************************************************************************"
+ "\n*******************************************************************************"
+ "\n\n******************* AS2 Server Endpoint Received Request **********************"
+ "\n\n" + AS2Utils.printMessage(request) + "\n"
+ "\n************************** Containing EDI message *****************************"
+ "\n\n" + ediMessage + "\n"
+ "\n*******************************************************************************"
+ "\n*******************************************************************************");
} else {
log.info("AS2 Interchange missing from context");
}
}
}
| 1,646 |
0 | Create_ds/camel-examples/transformer-demo/src/test/java/org/apache/camel/example/transformer | Create_ds/camel-examples/transformer-demo/src/test/java/org/apache/camel/example/transformer/demo/TransformerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.transformer.demo;
import java.util.concurrent.TimeUnit;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.spi.DataType;
import org.apache.camel.spi.DataTypeAware;
import org.apache.camel.test.spring.junit5.CamelSpringTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can transform and validate data.
*/
@CamelSpringTest
@ContextConfiguration("/META-INF/spring/camel-context.xml")
class TransformerTest {
@Autowired
ProducerTemplate template;
@Autowired
ModelCamelContext context;
@Test
void should_transform_and_validate_pojo() {
NotifyBuilder notify = new NotifyBuilder(context).fromRoute("java")
.whenCompleted(1).and()
.whenCompleted(1).wereSentTo("file:target/output*").create();
// Given
Order order = new Order()
.setOrderId("Order-Java-0001")
.setItemId("MILK")
.setQuantity(3);
// When
OrderResponse response = template.requestBody("direct:java", order, OrderResponse.class);
// Then
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
assertNotNull(response);
assertTrue(response.isAccepted());
assertEquals("Order-Java-0001", response.getOrderId());
assertEquals(String.format("Order accepted:[item='%s' quantity='%s']", order.getItemId(), order.getQuantity()), response.getDescription());
}
@Test
void should_transform_and_validate_json() {
NotifyBuilder notify = new NotifyBuilder(context).fromRoute("json")
.whenCompleted(1).and()
.whenCompleted(1).wereSentTo("file:target/output*").create();
// Given
String orderJson = "{\"orderId\":\"Order-JSON-0001\", \"itemId\":\"MIZUYO-KAN\", \"quantity\":\"16350\"}";
// When
Exchange answerJson = template.send("direct:json", ex -> ((DataTypeAware) ex.getIn()).setBody(orderJson, new DataType("json")));
// Then
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
assertNotNull(answerJson);
String response = answerJson.getIn().getBody(String.class);
assertNotNull(response);
assertTrue(response.contains("\"accepted\":true"));
assertTrue(response.contains("\"orderId\":\"Order-JSON-0001\""));
assertTrue(response.contains("Order accepted:[item='MIZUYO-KAN' quantity='16350']"));
}
@Test
void should_transform_and_validate_xml() {
NotifyBuilder notify = new NotifyBuilder(context).fromRoute("xml")
.whenCompleted(1).and()
.whenCompleted(1).wereSentTo("file:target/output*").create();
// Given
String orderXml = "<order orderId=\"Order-XML-0001\" itemId=\"MIKAN\" quantity=\"365\"/>";
// When
Exchange answerXml = template.send("direct:xml",
ex -> ((DataTypeAware) ex.getIn()).setBody(orderXml, new DataType("xml:XMLOrder"))
);
// Then
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
assertNotNull(answerXml);
String response = answerXml.getIn().getBody(String.class);
assertNotNull(response);
assertTrue(response.contains("accepted=\"true\""));
assertTrue(response.contains("orderId=\"Order-XML-0001\""));
assertTrue(response.contains("Order accepted:[item='MIKAN' quantity='365']"));
}
}
| 1,647 |
0 | Create_ds/camel-examples/transformer-demo/src/main/java/org/apache/camel/example/transformer | Create_ds/camel-examples/transformer-demo/src/main/java/org/apache/camel/example/transformer/demo/Order.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.transformer.demo;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
/**
* The Order.
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@CsvRecord(separator = ",")
public class Order {
@XmlAttribute
@DataField(pos = 1)
private String orderId;
@XmlAttribute
@DataField(pos = 2)
private String itemId;
@XmlAttribute
@DataField(pos = 3)
private int quantity;
public String getOrderId() {
return orderId;
}
public Order setOrderId(String orderId) {
this.orderId = orderId;
return this;
}
public String getItemId() {
return itemId;
}
public Order setItemId(String itemId) {
this.itemId = itemId;
return this;
}
public int getQuantity() {
return quantity;
}
public Order setQuantity(int quantity) {
this.quantity = quantity;
return this;
}
@Override
public String toString() {
return String.format("Order[orderId='%s', itemId='%s', quantity='%s']", orderId, itemId, quantity);
}
}
| 1,648 |
0 | Create_ds/camel-examples/transformer-demo/src/main/java/org/apache/camel/example/transformer | Create_ds/camel-examples/transformer-demo/src/main/java/org/apache/camel/example/transformer/demo/OrderResponseValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.transformer.demo;
import org.apache.camel.Message;
import org.apache.camel.ValidationException;
import org.apache.camel.spi.DataType;
import org.apache.camel.spi.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OrderResponseValidator extends Validator {
private static final Logger LOG = LoggerFactory.getLogger(OrderResponseValidator.class);
@Override
public void validate(Message message, DataType type) throws ValidationException {
Object body = message.getBody();
LOG.info("Validating message body: {}", body);
if (!(body instanceof OrderResponse)) {
throw new ValidationException(message.getExchange(), "Expected OrderResponse, but was " + body.getClass());
}
OrderResponse r = (OrderResponse)body;
if (!r.isAccepted()) {
throw new ValidationException(message.getExchange(), "Order was not accepted:" + r);
}
}
}
| 1,649 |
0 | Create_ds/camel-examples/transformer-demo/src/main/java/org/apache/camel/example/transformer | Create_ds/camel-examples/transformer-demo/src/main/java/org/apache/camel/example/transformer/demo/OrderResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.transformer.demo;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
/**
* The OrderResponse.
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class OrderResponse {
@XmlAttribute
private String orderId;
@XmlAttribute
private boolean accepted;
@XmlAttribute
private String description;
public String getOrderId() {
return orderId;
}
public OrderResponse setOrderId(String orderId) {
this.orderId = orderId;
return this;
}
public boolean isAccepted() {
return accepted;
}
public OrderResponse setAccepted(boolean accepted) {
this.accepted = accepted;
return this;
}
public String getDescription() {
return description;
}
public OrderResponse setDescription(String description) {
this.description = description;
return this;
}
@Override
public String toString() {
return String.format("OrderResponse[orderId='%s', accepted='%s', description='%s']", orderId, accepted, description);
}
}
| 1,650 |
0 | Create_ds/camel-examples/transformer-demo/src/main/java/org/apache/camel/example/transformer | Create_ds/camel-examples/transformer-demo/src/main/java/org/apache/camel/example/transformer/demo/OrderProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.transformer.demo;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
/**
* A processor which receives a order request and return a response.
* <p/>
*/
public class OrderProcessor implements Processor {
@Override
public void process(Exchange exchange) {
Order order = exchange.getIn().getBody(Order.class);
OrderResponse answer = new OrderResponse()
.setAccepted(true)
.setOrderId(order.getOrderId())
.setDescription(String.format("Order accepted:[item='%s' quantity='%s']", order.getItemId(), order.getQuantity()));
exchange.getIn().setBody(answer);
}
}
| 1,651 |
0 | Create_ds/camel-examples/transformer-demo/src/main/java/org/apache/camel/example/transformer/demo | Create_ds/camel-examples/transformer-demo/src/main/java/org/apache/camel/example/transformer/demo/client/CamelClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.transformer.demo.client;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.example.transformer.demo.Order;
import org.apache.camel.example.transformer.demo.OrderResponse;
import org.apache.camel.spi.DataType;
import org.apache.camel.spi.DataTypeAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Client that sends order data in various format and verify XML output.
* <p/>
*/
public final class CamelClient {
private static final Logger LOG = LoggerFactory.getLogger(CamelClient.class);
private static final String CSV_PATH = "target/output/orders.csv";
private CamelClient() {
// Helper class
}
public static void main(final String[] args) throws Exception {
File csvLogFile = new File(CSV_PATH);
if (csvLogFile.exists()) {
LOG.info("---> Removing log file '{}'...", csvLogFile.getAbsolutePath());
csvLogFile.delete();
}
// START SNIPPET: e1
LOG.info("---> Starting 'order' camel route...");
try (ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/camel-context.xml")) {
context.start();
CamelContext camelContext = context.getBean("order", CamelContext.class);
try (ProducerTemplate producer = camelContext.createProducerTemplate()) {
// END SNIPPET: e1
Thread.sleep(1000);
Order order = new Order()
.setOrderId("Order-Java-0001")
.setItemId("MILK")
.setQuantity(3);
LOG.info("---> Sending '{}' to 'direct:java'", order);
OrderResponse response = producer.requestBody("direct:java", order, OrderResponse.class);
logResponse(response);
String orderXml = "<order orderId=\"Order-XML-0001\" itemId=\"MIKAN\" quantity=\"365\"/>";
LOG.info("---> Sending '{}' to 'direct:xml'", orderXml);
Exchange answerXml = producer.send("direct:xml",
ex -> ((DataTypeAware) ex.getIn()).setBody(orderXml, new DataType("xml:XMLOrder"))
);
logResponse(answerXml.getIn().getBody(String.class));
String orderJson = "{\"orderId\":\"Order-JSON-0001\", \"itemId\":\"MIZUYO-KAN\", \"quantity\":\"16350\"}";
LOG.info("---> Sending '{}' to 'direct:json'", orderJson);
Exchange answerJson = producer.send("direct:json", ex -> ((DataTypeAware) ex.getIn()).setBody(orderJson, new DataType("json")));
logResponse(answerJson.getIn().getBody(String.class));
}
}
}
private static void logResponse(Object response) throws Exception {
Thread.sleep(1000);
LOG.info("---> Received '{}'", response);
LOG.info("---> CSV log now contains:\n{}", getCsvLog());
Thread.sleep(1000);
}
public static String getCsvLog() throws IOException {
return Files.readString(Paths.get(CSV_PATH));
}
}
| 1,652 |
0 | Create_ds/camel-examples/routeloader/src/test/java/org/apache/camel | Create_ds/camel-examples/routeloader/src/test/java/org/apache/camel/example/RouteLoaderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import java.util.concurrent.TimeUnit;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can load routes dynamically.
*/
class RouteLoaderTest extends CamelMainTestSupport {
@Test
void should_load_routes_dynamically() {
NotifyBuilder notify = new NotifyBuilder(context)
.from("timer:xml*").whenCompleted(1)
.and().from("timer:java*").whenCompleted(1)
.and().from("timer:yaml*").whenCompleted(1).create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "3 messages should be completed"
);
}
}
| 1,653 |
0 | Create_ds/camel-examples/routeloader/src/main/resources | Create_ds/camel-examples/routeloader/src/main/resources/myroutes/MyRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Random;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.builder.endpoint.EndpointRouteBuilder;
public class MyRouteBuilder extends EndpointRouteBuilder {
@Override
public void configure() throws Exception {
from(timer("java").period(2000))
.setBody(method(MyRouteBuilder.class, "randomNumber"))
.log("Random number ${body}");
}
public static int randomNumber() {
return new Random().nextInt(100);
}
}
| 1,654 |
0 | Create_ds/camel-examples/routeloader/src/main/java/org/apache/camel | Create_ds/camel-examples/routeloader/src/main/java/org/apache/camel/example/MyApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.main.Main;
/**
* Main class that boot the Camel application.
*
* This class has been added to make it easy to run the application from a Java editor.
* However you can start this application by running org.apache.camel.main.Main directory (see Maven pom.xml)
*/
public final class MyApplication {
private MyApplication() {
}
public static void main(String[] args) throws Exception {
// use Camels Main class
Main main = new Main();
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,655 |
0 | Create_ds/camel-examples/azure/kafka-azure/src/main/java/org/apache/camel | Create_ds/camel-examples/azure/kafka-azure/src/main/java/org/apache/camel/example/MyApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.main.Main;
/**
* Main class that boot the Camel application
*/
public final class MyApplication {
private MyApplication() {
}
public static void main(String[] args) throws Exception {
// use Camels Main class
Main main = new Main(MyApplication.class);
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,656 |
0 | Create_ds/camel-examples/azure/kafka-azure/src/main/java/org/apache/camel | Create_ds/camel-examples/azure/kafka-azure/src/main/java/org/apache/camel/example/MyRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.builder.RouteBuilder;
public class MyRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("kafka:{{topicName}}?brokers={{brokers}}")
.setHeader("CamelAzureStorageBlobBlobName", simple("${exchangeId}"))
.to("azure-storage-blob://{{accountName}}/{{containerName}}/?accessKey=RAW({{accessKey}})&operation=uploadBlockBlob");
}
}
| 1,657 |
0 | Create_ds/camel-examples/azure/azure-eventhubs/src/main/java/org/apache/camel | Create_ds/camel-examples/azure/azure-eventhubs/src/main/java/org/apache/camel/example/MyApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.main.Main;
/**
* Main class that boot the Camel application
*/
public final class MyApplication {
private MyApplication() {
}
public static void main(String[] args) throws Exception {
// use Camels Main class
Main main = new Main(MyApplication.class);
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,658 |
0 | Create_ds/camel-examples/azure/azure-eventhubs/src/main/java/org/apache/camel | Create_ds/camel-examples/azure/azure-eventhubs/src/main/java/org/apache/camel/example/MyRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.builder.endpoint.EndpointRouteBuilder;
/**
* To use the endpoint DSL then we must extend EndpointRouteBuilder instead of RouteBuilder
*/
public class MyRouteBuilder extends EndpointRouteBuilder {
@Override
public void configure() {
from(azureEventhubs("{{namespaceName}}/{{eventhubName}}").sharedAccessKey("{{sharedAccessKey}}").sharedAccessName("{{sharedAccessName}}").blobAccessKey("{{blobAccessKey}}").blobAccountName("{{blobAccountName}}").blobContainerName("{{blobContainerName}}"))
.log("The content is ${body}");
from(timer("tick").period(1000)).setBody(constant("Event Test"))
.to(azureEventhubs("{{namespaceName}}/{{eventhubName}}").sharedAccessName("{{sharedAccessName}}").sharedAccessKey("{{sharedAccessKey}}"));
}
}
| 1,659 |
0 | Create_ds/camel-examples/azure/azure-storage-blob/src/main/java/org/apache/camel/example | Create_ds/camel-examples/azure/azure-storage-blob/src/main/java/org/apache/camel/example/azurestorageblob/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.azurestorageblob;
import com.azure.storage.blob.BlobServiceClientBuilder;
import com.azure.storage.blob.models.ListBlobsOptions;
import com.azure.storage.common.StorageSharedKeyCredential;
import java.util.Iterator;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
/**
* A basic example of list large azure blob storage.
*/
public final class Application {
private static final String ACCOUNT = "ENTER_YOUR_ACCOUNT";
private static final String ACCESS_KEY = "ACCESS_KEY";
private static final String BLOB_CONTAINER_NAME = "CONTAINER";
public static void main(String[] args) throws Exception {
// create a CamelContext
try (CamelContext camel = new DefaultCamelContext()) {
// add routes which can be inlined as anonymous inner class
// (to keep all code in a single java file for this basic example)
camel.addRoutes(createRouteBuilder());
// start is not blocking
camel.start();
// so run for 10 seconds
Thread.sleep(10_000);
}
}
static RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("timer://runOnce?repeatCount=1&delay=0")
.routeId("listBlobs")
.process(exchange -> exchange.getIn()
.setBody(
new BlobServiceClientBuilder()
.endpoint(String.format("https://%s.blob.core.windows.net", ACCOUNT))
.credential(new StorageSharedKeyCredential(ACCOUNT, ACCESS_KEY))
.buildClient()
.getBlobContainerClient(BLOB_CONTAINER_NAME)
.listBlobs(
new ListBlobsOptions().setMaxResultsPerPage(1),
null
)
)
)
.loopDoWhile(exchange ->
exchange.getIn().getBody(Iterator.class).hasNext()
)
.process(exchange ->
exchange.getIn().setBody(exchange.getIn().getBody(Iterator.class).next())
)
.log("${body.name}")
.end();
}
};
}
}
| 1,660 |
0 | Create_ds/camel-examples/aggregate/src/test/java/org/apache/camel | Create_ds/camel-examples/aggregate/src/test/java/org/apache/camel/example/AggregateTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AdviceWith;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.test.spring.junit5.CamelSpringTest;
import org.apache.camel.test.spring.junit5.MockEndpoints;
import org.apache.camel.test.spring.junit5.UseAdviceWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
/**
* A unit test allowing to check that the aggregation works as expected.
*/
@CamelSpringTest
@ContextConfiguration("/META-INF/spring/camel-context.xml")
@MockEndpoints("stream:out")
@UseAdviceWith
class AggregateTest {
@Autowired
ProducerTemplate template;
@Autowired
ModelCamelContext context;
@EndpointInject("mock:stream:out")
MockEndpoint result;
@Test
void should_aggregate_provided_numbers() throws Exception {
// Replace the from endpoint to send messages easily
AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() {
@Override
public void configure() {
replaceFromWith("direct:in");
}
});
// must start Camel after we are done using advice-with
context.start();
result.expectedBodiesReceived("The result is: 6");
result.expectedMessageCount(1);
template.sendBody("direct:in", "1");
template.sendBody("direct:in", "2");
template.sendBody("direct:in", "3");
template.sendBody("direct:in", "STOP");
result.assertIsSatisfied();
}
}
| 1,661 |
0 | Create_ds/camel-examples/aggregate/src/main/java/org/apache/camel | Create_ds/camel-examples/aggregate/src/main/java/org/apache/camel/example/NumberAggregationStrategy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.AggregationStrategy;
import org.apache.camel.Exchange;
/**
* Aggregate two numbers
*/
// START SNIPPET: e1
public class NumberAggregationStrategy implements AggregationStrategy {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
// check for stop command
String input = newExchange.getIn().getBody(String.class);
if ("STOP".equalsIgnoreCase(input)) {
return oldExchange;
}
Integer num1 = oldExchange.getIn().getBody(Integer.class);
Integer num2 = newExchange.getIn().getBody(Integer.class);
// just avoid bad inputs by assuming its a 0 value
Integer num3 = (num1 != null ? num1 : 0) + (num2 != null ? num2 : 0);
oldExchange.getIn().setBody(num3);
return oldExchange;
}
}
// END SNIPPET: e1
| 1,662 |
0 | Create_ds/camel-examples/netty-custom-correlation/src/test/java/org/apache/camel/example | Create_ds/camel-examples/netty-custom-correlation/src/test/java/org/apache/camel/example/netty/NettyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.netty;
import java.util.concurrent.TimeUnit;
import org.apache.camel.Predicate;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.spi.Registry;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import static org.apache.camel.example.netty.MyClient.createCorrelationManager;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can communicate over TCP with Netty using a custom codec.
*/
class NettyTest extends CamelMainTestSupport {
@Override
protected void bindToRegistry(Registry registry) throws Exception {
// Bind the Correlation Manager to use for the test
registry.bind("myManager", createCorrelationManager());
// Bind the custom codec
registry.bind("myEncoder", new MyCodecEncoderFactory());
registry.bind("myDecoder", new MyCodecDecoderFactory());
}
@Test
void should_exchange_messages_over_tcp_using_a_custom_codec() {
Predicate isAGeneratedWord = exchange -> exchange.getIn().getBody(String.class).endsWith("-Echo");
NotifyBuilder notify = new NotifyBuilder(context).fromRoute("client")
.whenCompleted(5).whenAllDoneMatches(isAGeneratedWord)
.and().fromRoute("server").whenCompleted(5).whenAllDoneMatches(isAGeneratedWord).create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "5 messages should be exchanged"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(new MyServer.MyRouteBuilder());
configuration.addRoutesBuilder(new MyClient.MyRouteBuilder());
}
}
| 1,663 |
0 | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example/netty/MyServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.netty;
import org.apache.camel.BindToRegistry;
import org.apache.camel.Configuration;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.netty.DefaultChannelHandlerFactory;
import org.apache.camel.main.Main;
/**
* Netty server which returns back an echo of the incoming request.
*/
public final class MyServer {
private MyServer() {
}
public static void main(String[] args) throws Exception {
Main main = new Main(MyServer.class);
main.run(args);
}
@Configuration
public static class MyServerConfiguration {
@BindToRegistry("myEncoder")
public DefaultChannelHandlerFactory myCodecEncoderFactory() {
return new MyCodecEncoderFactory();
}
@BindToRegistry("myDecoder")
public DefaultChannelHandlerFactory myCodecDecoderFactory() {
return new MyCodecDecoderFactory();
}
}
public static class MyRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("netty:tcp://localhost:4444?sync=true&encoders=#bean:myEncoder&decoders=#bean:myDecoder").id("server")
.log("Request: ${id}:${body}")
.filter(simple("${body} contains 'beer'"))
// use some delay when its beer to make responses interleaved
// and make the delay asynchronous
.delay(simple("${random(1000,2000)}")).asyncDelayed().end()
.end()
.transform(simple("${body}-Echo"))
.log("Response: ${id}:${body}");
}
}
}
| 1,664 |
0 | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example/netty/MyCodecDecoderFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.netty;
import io.netty.channel.ChannelHandler;
import org.apache.camel.component.netty.DefaultChannelHandlerFactory;
public class MyCodecDecoderFactory extends DefaultChannelHandlerFactory {
@Override
public ChannelHandler newChannelHandler() {
return new MyCodecDecoder();
}
}
| 1,665 |
0 | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example/netty/MyCodecEncoderFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.netty;
import io.netty.channel.ChannelHandler;
import org.apache.camel.component.netty.DefaultChannelHandlerFactory;
public class MyCodecEncoderFactory extends DefaultChannelHandlerFactory {
@Override
public ChannelHandler newChannelHandler() {
return new MyCodecEncoder();
}
}
| 1,666 |
0 | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example/netty/MyCodecEncoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* Netty encoder that writes the Camel message to bytes with start and end byte markers.
*/
public class MyCodecEncoder extends MessageToByteEncoder<Object> {
private static char startByte = 0x0b; // 11 decimal
private static char endByte1 = 0x1c; // 28 decimal
private static char endByte2 = 0x0d; // 13 decimal
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, Object message, ByteBuf byteBuf) throws Exception {
byte[] body;
if (message instanceof String) {
body = ((String) message).getBytes();
} else if (message instanceof byte[]) {
body = (byte[]) message;
} else {
throw new IllegalArgumentException("The message to encode is not a supported type: "
+ message.getClass().getCanonicalName());
}
byteBuf.writeByte(startByte);
byteBuf.writeBytes(body);
byteBuf.writeByte(endByte1);
byteBuf.writeByte(endByte2);
}
}
| 1,667 |
0 | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example/netty/MyCorrelationManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.netty;
import org.apache.camel.component.netty.TimeoutCorrelationManagerSupport;
import org.apache.camel.util.StringHelper;
/**
* Implement a timeout aware {@link org.apache.camel.component.netty.NettyCamelStateCorrelationManager}
* that handles all the complexities for us, so we only need to implement how to extract the correlation id.
*/
public class MyCorrelationManager extends TimeoutCorrelationManagerSupport {
@Override
public String getRequestCorrelationId(Object request) {
// correlation id is before the first colon
return StringHelper.before(request.toString(), ":");
}
@Override
public String getResponseCorrelationId(Object response) {
// correlation id is before the first colon
return StringHelper.before(response.toString(), ":");
}
@Override
public String getTimeoutResponse(String correlationId, Object request) {
// here we can build a custom response message on timeout, instead
// of having an exception being thrown, however we only have access
// to the correlation id and the request message that was sent over the wire
return null;
}
}
| 1,668 |
0 | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example/netty/MyCodecDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.netty;
import java.nio.charset.Charset;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
/**
* Netty decoder that assembles a complete messages from the frames received by Netty.
* The decoder uses delimter based on start and end byte markers, to know when all
* data for a complete message has been received.
*/
public class MyCodecDecoder extends DelimiterBasedFrameDecoder {
private static final int MAX_FRAME_LENGTH = 4096;
private static char startByte = 0x0b; // 11 decimal
private static char endByte1 = 0x1c; // 28 decimal
private static char endByte2 = 0x0d; // 13 decimal
public MyCodecDecoder() {
super(MAX_FRAME_LENGTH, true, Unpooled.copiedBuffer(
new char[]{endByte1, endByte2}, Charset.defaultCharset()));
}
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
ByteBuf buf = (ByteBuf) super.decode(ctx, buffer);
if (buf != null) {
try {
int pos = buf.bytesBefore((byte) startByte);
if (pos >= 0) {
ByteBuf msg = buf.readerIndex(pos + 1).slice();
return asString(msg);
} else {
throw new DecoderException("Did not find start byte " + (int) startByte);
}
} finally {
// We need to release the buf here to avoid the memory leak
buf.release();
}
}
// Message not complete yet - return null to be called again
return null;
}
private String asString(ByteBuf msg) {
// convert the message to a String which Camel will then use
String text = msg.toString(Charset.defaultCharset());
return text;
}
}
| 1,669 |
0 | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example | Create_ds/camel-examples/netty-custom-correlation/src/main/java/org/apache/camel/example/netty/MyClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.netty;
import java.util.Random;
import org.apache.camel.BindToRegistry;
import org.apache.camel.Configuration;
import org.apache.camel.ExchangeTimedOutException;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.netty.DefaultChannelHandlerFactory;
import org.apache.camel.main.Main;
/**
* Netty client which calls the server every half-second with a random word.
*/
public final class MyClient {
private MyClient() {
}
public static void main(String[] args) throws Exception {
Main main = new Main(MyClient.class);
main.run(args);
}
@Configuration
public static class MyClientConfiguration {
@BindToRegistry("myEncoder")
public DefaultChannelHandlerFactory myCodecEncoderFactory() {
return new MyCodecEncoderFactory();
}
@BindToRegistry("myDecoder")
public DefaultChannelHandlerFactory myCodecDecoderFactory() {
return new MyCodecDecoderFactory();
}
@BindToRegistry("myManager")
public MyCorrelationManager myCorrelationManager() {
return createCorrelationManager();
}
}
static MyCorrelationManager createCorrelationManager() {
// setup correlation manager and its timeout (when a request has not received a response within the given time millis)
MyCorrelationManager manager = new MyCorrelationManager();
// set timeout for each request message that did not receive a reply message
manager.setTimeout(5000);
// set the logging level when a timeout was hit, ny default its DEBUG
manager.setTimeoutLoggingLevel(LoggingLevel.INFO);
return manager;
}
public static class MyRouteBuilder extends RouteBuilder {
private static final String[] WORDS = new String[]{"foo", "bar", "baz", "beer", "wine", "cheese"};
private int counter;
private final Random random = new Random();
public int increment() {
return ++counter;
}
public String word() {
return WORDS[random.nextInt(WORDS.length)];
}
@Override
public void configure() throws Exception {
// lets build a special custom error message for timeout
onException(ExchangeTimedOutException.class)
// here we tell Camel to continue routing
.continued(true)
// after it has built this special timeout error message body
.setBody(simple("#${header.corId}:${header.word}-Time out error!!!"));
from("timer:trigger").id("client")
// set correlation id as unique incrementing number
.setHeader("corId", method(this, "increment"))
// set random word to use in request
.setHeader("word", method(this, "word"))
// build request message as a string body
.setBody(simple("#${header.corId}:${header.word}"))
// log request before
.log("Request: ${id}:${body}")
// call netty server using a single shared connection and using custom correlation manager
// to ensure we can correctly map the request and response pairs
.to("netty:tcp://localhost:4444?sync=true&encoders=#bean:myEncoder&decoders=#bean:myDecoder"
+ "&producerPoolEnabled=false&correlationManager=#bean:myManager")
// log response after
.log("Response: ${id}:${body}");
}
}
}
| 1,670 |
0 | Create_ds/camel-examples/main-lambda/src/test/java/org/apache/camel | Create_ds/camel-examples/main-lambda/src/test/java/org/apache/camel/example/MainLambdaTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import java.util.concurrent.TimeUnit;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that {@code LambdaRouteBuilder} can be used to define routes
* using lambda style.
*/
class MainLambdaTest extends CamelMainTestSupport {
@Test
void should_support_routes_defined_using_a_lambda() throws Exception {
NotifyBuilder notify = new NotifyBuilder(context)
.whenCompleted(1).whenBodiesDone("Bye World").create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
}
@Override
protected Class<?> getMainClass() {
return MyApplication.class;
}
}
| 1,671 |
0 | Create_ds/camel-examples/main-lambda/src/main/java/org/apache/camel | Create_ds/camel-examples/main-lambda/src/main/java/org/apache/camel/example/MyConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.BindToRegistry;
import org.apache.camel.Configuration;
import org.apache.camel.PropertyInject;
import org.apache.camel.builder.LambdaRouteBuilder;
/**
* Class to configure the Camel application.
*/
@Configuration
public class MyConfiguration {
@BindToRegistry
public MyBean myBean(@PropertyInject("hi") String hi, @PropertyInject("bye") String bye) {
// this will create an instance of this bean with the name of the method (eg myBean)
return new MyBean(hi, bye);
}
/**
* Here we define a route as a method that returns a LambdaRouteBuilder instance.
* This allows us to use lambda style.
*/
@BindToRegistry
public LambdaRouteBuilder myRoute() {
return rb -> rb.from("quartz:foo?cron={{myCron}}")
.bean("myBean", "hello")
.log("${body}")
.bean("myBean", "bye")
.log("${body}");
}
}
| 1,672 |
0 | Create_ds/camel-examples/main-lambda/src/main/java/org/apache/camel | Create_ds/camel-examples/main-lambda/src/main/java/org/apache/camel/example/MyApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.main.Main;
/**
* Main class that boot the Camel application
*/
public final class MyApplication {
private MyApplication() {
}
public static void main(String[] args) throws Exception {
// use Camels Main class
Main main = new Main(MyApplication.class);
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,673 |
0 | Create_ds/camel-examples/main-lambda/src/main/java/org/apache/camel | Create_ds/camel-examples/main-lambda/src/main/java/org/apache/camel/example/MyBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
public class MyBean {
private String hi;
private String bye;
public MyBean(String hi, String bye) {
this.hi = hi;
this.bye = bye;
}
public String hello() {
return hi + " how are you?";
}
public String bye() {
return bye + " World";
}
}
| 1,674 |
0 | Create_ds/camel-examples/jmx/src/test/java/org/apache/camel/example | Create_ds/camel-examples/jmx/src/test/java/org/apache/camel/example/jmx/JMXTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.jmx;
import org.apache.camel.builder.AdviceWith;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.test.spring.junit5.CamelSpringTest;
import org.apache.camel.test.spring.junit5.UseAdviceWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test allowing to check that Camel can subscribe to the notifications of a custom MBean.
*/
@CamelSpringTest
@ContextConfiguration("/META-INF/spring/camel-context.xml")
@UseAdviceWith
class JMXTest {
@Autowired
ModelCamelContext context;
@Test
void should_receive_mbean_notifications() throws Exception {
// Replace the from endpoint to change the value of the option period
AdviceWith.adviceWith(context.getRouteDefinitions().get(1), context, new AdviceWithRouteBuilder() {
@Override
public void configure() {
replaceFromWith("timer:foo?period=1000");
}
});
// must start Camel after we are done using advice-with
context.start();
NotifyBuilder notify = new NotifyBuilder(context).whenCompleted(3).wereSentTo("log:jmxEvent").create();
assertTrue(
notify.matches(10, TimeUnit.SECONDS), "3 messages should be completed"
);
}
}
| 1,675 |
0 | Create_ds/camel-examples/jmx/src/main/java/org/apache/camel/example | Create_ds/camel-examples/jmx/src/main/java/org/apache/camel/example/jmx/ISimpleMXBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.jmx;
import java.io.Serializable;
/**
* Interface defining the POJO
*/
public interface ISimpleMXBean extends Serializable {
void tick() throws Exception;
}
| 1,676 |
0 | Create_ds/camel-examples/jmx/src/main/java/org/apache/camel/example | Create_ds/camel-examples/jmx/src/main/java/org/apache/camel/example/jmx/SimpleBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.jmx;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.management.AttributeChangeNotification;
import javax.management.NotificationBroadcasterSupport;
/**
* Our business logic which also is capable of broadcasting JMX notifications,
* such as an attribute being changed.
*/
public class SimpleBean extends NotificationBroadcasterSupport implements ISimpleMXBean {
private static final long serialVersionUID = 1L;
private int sequence;
private int tick;
@Override
public void tick() throws Exception {
tick++;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-dd-MM'T'HH:mm:ss");
Date date = sdf.parse("2010-07-01T10:30:15");
long timeStamp = date.getTime();
AttributeChangeNotification acn = new AttributeChangeNotification(
this, sequence++, timeStamp, "attribute changed", "stringValue", "string", tick - 1, tick);
sendNotification(acn);
}
}
| 1,677 |
0 | Create_ds/camel-examples/jmx/src/main/java/org/apache/camel/example | Create_ds/camel-examples/jmx/src/main/java/org/apache/camel/example/jmx/MyRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.jmx;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.camel.builder.RouteBuilder;
/**
* A simple example router demonstrating the camel-jmx component.
*/
public class MyRouteBuilder extends RouteBuilder {
private SimpleBean bean;
private MBeanServer server;
public MyRouteBuilder() throws Exception {
server = ManagementFactory.getPlatformMBeanServer();
bean = new SimpleBean();
// START SNIPPET: e2
server.registerMBean(bean, new ObjectName("jmxExample", "name", "simpleBean"));
// END SNIPPET: e2
}
@Override
public void configure() {
// START SNIPPET: e1
from("jmx:platform?objectDomain=jmxExample&key.name=simpleBean").
to("log:jmxEvent");
// END SNIPPET: e1
from("timer:foo?period=6000").bean(bean, "tick");
}
}
| 1,678 |
0 | Create_ds/camel-examples/google/google-pubsub/src/main/java/org/apache/camel | Create_ds/camel-examples/google/google-pubsub/src/main/java/org/apache/camel/example/MyApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.main.Main;
/**
* Main class that boot the Camel application
*/
public final class MyApplication {
private MyApplication() {
}
public static void main(String[] args) throws Exception {
// use Camels Main class
Main main = new Main(MyApplication.class);
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,679 |
0 | Create_ds/camel-examples/google/google-pubsub/src/main/java/org/apache/camel | Create_ds/camel-examples/google/google-pubsub/src/main/java/org/apache/camel/example/MyRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.builder.endpoint.EndpointRouteBuilder;
/**
* To use the endpoint DSL then we must extend EndpointRouteBuilder instead of RouteBuilder
*/
public class MyRouteBuilder extends EndpointRouteBuilder {
@Override
public void configure() {
from(googlePubsub("{{projectId}}:{{subscriptionName}}").serviceAccountKey("{{serviceAccountKey}}")).log("The content is ${body}");
from(timer("tick").period(1000)).setBody(constant("Event Test"))
.to(googlePubsub("{{projectId}}:{{topicName}}").serviceAccountKey("{{serviceAccountKey}}"));
}
}
| 1,680 |
0 | Create_ds/camel-examples/main-tiny/src/generated/java/org/apache/camel | Create_ds/camel-examples/main-tiny/src/generated/java/org/apache/camel/example/MyBeanConfigurer.java | /* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.example;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.example.MyBean;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class MyBeanConfigurer extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.example.MyBean target = (org.apache.camel.example.MyBean) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "hi":
case "Hi": target.setHi(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "hi":
case "Hi": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.example.MyBean target = (org.apache.camel.example.MyBean) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "hi":
case "Hi": return target.getHi();
default: return null;
}
}
}
| 1,681 |
0 | Create_ds/camel-examples/main-tiny/src/test/java/org/apache/camel | Create_ds/camel-examples/main-tiny/src/test/java/org/apache/camel/example/MainTinyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import static org.apache.camel.util.PropertiesHelper.asProperties;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can work in tiny mode.
*/
class MainTinyTest extends CamelMainTestSupport {
@Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
return asProperties("myPeriod", Integer.toString(500));
}
@Test
void should_support_tiny_mode() {
NotifyBuilder notify = new NotifyBuilder(context).whenCompleted(1).whenBodiesDone("Hello how are you?").create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
}
}
| 1,682 |
0 | Create_ds/camel-examples/main-tiny/src/main/java/org/apache/camel | Create_ds/camel-examples/main-tiny/src/main/java/org/apache/camel/example/MyApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.main.Main;
/**
* Main class that boot the Camel application
*/
public final class MyApplication {
private MyApplication() {
}
public static void main(String[] args) throws Exception {
// use Camels Main class
Main main = new Main(MyApplication.class);
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,683 |
0 | Create_ds/camel-examples/main-tiny/src/main/java/org/apache/camel | Create_ds/camel-examples/main-tiny/src/main/java/org/apache/camel/example/MyRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.builder.RouteBuilder;
public class MyRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer:foo?period={{myPeriod}}")
.bean("myBean", "hello")
.log("${body}");
}
}
| 1,684 |
0 | Create_ds/camel-examples/main-tiny/src/main/java/org/apache/camel | Create_ds/camel-examples/main-tiny/src/main/java/org/apache/camel/example/MyBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import org.apache.camel.spi.Configurer;
@Configurer
public class MyBean {
private String hi;
public String getHi() {
return hi;
}
public void setHi(String hi) {
this.hi = hi;
}
public String hello() {
return hi + " how are you?";
}
}
| 1,685 |
0 | Create_ds/camel-examples/resume-api/resume-api-file-offset/src/main/java/org/apache/camel/example/resume/file/offset | Create_ds/camel-examples/resume-api/resume-api-file-offset/src/main/java/org/apache/camel/example/resume/file/offset/main/MainApp.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.file.offset.main;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.caffeine.resume.CaffeineCache;
import org.apache.camel.example.resume.strategies.kafka.KafkaUtil;
import org.apache.camel.example.resume.strategies.kafka.file.LargeFileRouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.processor.resume.kafka.SingleNodeKafkaResumeStrategy;
/**
* A Camel Application
*/
public class MainApp {
/**
* A main() so we can easily run these routing rules in our IDE
*/
public static void main(String... args) {
Main main = new Main();
String tmp = System.getProperty("resume.batch.size", "30");
int batchSize = Integer.valueOf(tmp);
CountDownLatch latch = new CountDownLatch(batchSize);
RouteBuilder routeBuilder = new LargeFileRouteBuilder(new CaffeineCache<>(1), latch);
main.configure().addRoutesBuilder(routeBuilder);
Executors.newSingleThreadExecutor().submit(() -> waitForStop(main, latch));
main.start();
}
private static void waitForStop(Main main, CountDownLatch latch) {
try {
latch.await();
main.stop();
int shutdownWait = 10;
while (!main.isStopped() && shutdownWait > 0) {
Thread.sleep(1000);
shutdownWait--;
}
System.exit(0);
} catch (InterruptedException e) {
System.exit(1);
}
}
}
| 1,686 |
0 | Create_ds/camel-examples/resume-api/resume-api-fileset-clusterized/src/main/java/org/apache/camel/example/resume/fileset/clusterized | Create_ds/camel-examples/resume-api/resume-api-fileset-clusterized/src/main/java/org/apache/camel/example/resume/fileset/clusterized/strategies/ClusterizedLargeDirectoryRouteBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.fileset.clusterized.strategies;
import java.io.File;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.caffeine.resume.CaffeineCache;
import org.apache.camel.example.resume.strategies.kafka.KafkaUtil;
import org.apache.camel.processor.resume.kafka.KafkaResumeStrategyConfigurationBuilder;
import org.apache.camel.resume.cache.ResumeCache;
import org.apache.camel.support.resume.Resumables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClusterizedLargeDirectoryRouteBuilder extends RouteBuilder {
private static final Logger LOG = LoggerFactory.getLogger(ClusterizedLargeDirectoryRouteBuilder.class);
private void process(Exchange exchange) {
File path = exchange.getMessage().getHeader("CamelFilePath", File.class);
LOG.debug("Processing {}", path.getPath());
exchange.getMessage().setHeader(Exchange.OFFSET, Resumables.of(path.getParentFile(), path));
// Put a delay to simulate slow processing
try {
Thread.sleep(100);
} catch (InterruptedException e) {
LOG.trace("Interrupted while sleeping", e);
}
}
/**
* Let's configure the Camel routing rules using Java code...
*/
public void configure() {
final KafkaResumeStrategyConfigurationBuilder defaultKafkaResumeStrategyConfigurationBuilder = KafkaUtil
.getDefaultKafkaResumeStrategyConfigurationBuilder()
.withResumeCache(new CaffeineCache<>(10000));
from("timer:heartbeat?period=10000")
.routeId("heartbeat")
.log("HeartBeat route (timer) ...");
from("master:resume-ns:file:{{input.dir}}?noop=true&recursive=true&repeatCount=1")
.resumable()
.configuration(defaultKafkaResumeStrategyConfigurationBuilder)
.routeId("clustered")
.process(this::process)
.to("file:{{output.dir}}");
}
}
| 1,687 |
0 | Create_ds/camel-examples/resume-api/resume-api-fileset-clusterized/src/main/java/org/apache/camel/example/resume/fileset/clusterized | Create_ds/camel-examples/resume-api/resume-api-fileset-clusterized/src/main/java/org/apache/camel/example/resume/fileset/clusterized/main/ClusterizedListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.fileset.clusterized.main;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.zookeeper.cluster.ZooKeeperClusterService;
import org.apache.camel.example.resume.fileset.clusterized.strategies.ClusterizedLargeDirectoryRouteBuilder;
import org.apache.camel.main.BaseMainSupport;
import org.apache.camel.main.MainListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Acts upon events on the main class
*/
class ClusterizedListener implements MainListener {
private static final Logger LOG = LoggerFactory.getLogger(ClusterizedListener.class);
private final ZooKeeperClusterService clusterService;
public ClusterizedListener(ZooKeeperClusterService clusterService) {
this.clusterService = clusterService;
}
@Override
public void beforeInitialize(BaseMainSupport main) {
// NO-OP
}
// This is called after the CamelContext is created, so we use it to access the context and configure the services
@Override
public void beforeConfigure(BaseMainSupport main) {
try {
LOG.trace("Adding the cluster service");
main.getCamelContext().addService(clusterService);
LOG.trace("Creating the strategy");
LOG.trace("Creating the route");
RouteBuilder routeBuilder = new ClusterizedLargeDirectoryRouteBuilder();
main.getCamelContext().addRoutes(routeBuilder);
} catch (Exception e) {
LOG.error("Unable to add the cluster service: {}", e.getMessage(), e);
System.exit(1);
}
}
@Override
public void afterConfigure(BaseMainSupport main) {
}
@Override
public void beforeStart(BaseMainSupport main) {
}
@Override
public void afterStart(BaseMainSupport main) {
}
@Override
public void beforeStop(BaseMainSupport main) {
}
@Override
public void afterStop(BaseMainSupport main) {
// main.shutdown();
// System.exit(0);
}
}
| 1,688 |
0 | Create_ds/camel-examples/resume-api/resume-api-fileset-clusterized/src/main/java/org/apache/camel/example/resume/fileset/clusterized | Create_ds/camel-examples/resume-api/resume-api-fileset-clusterized/src/main/java/org/apache/camel/example/resume/fileset/clusterized/main/MainApp.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.fileset.clusterized.main;
import org.apache.camel.component.zookeeper.cluster.ZooKeeperClusterService;
import org.apache.camel.main.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Camel Application
*/
public class MainApp {
private static final Logger LOG = LoggerFactory.getLogger(MainApp.class);
/**
* A main() so we can easily run these routing rules in our IDE
*/
public static void main(String... args) throws Exception {
Main main = new Main();
ZooKeeperClusterService clusterService = new ZooKeeperClusterService();
// This identifies the camel instance in the cluster
String nodeId = System.getProperty("resume.example.node.id");
// This property points to our zookeeper host
String nodeHost = System.getProperty("resume.example.zk.host");
clusterService.setId(nodeId);
clusterService.setNodes(nodeHost);
clusterService.setBasePath("/camel/cluster");
/* In this example we use an implementation of MainListener to configure the services and listen for
events on Camel's main
*/
final ClusterizedListener listener = new ClusterizedListener(clusterService);
main.addMainListener(listener);
main.run(args);
}
}
| 1,689 |
0 | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra/main/ExampleDao.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.cassandra.main;
import java.time.Duration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import com.datastax.oss.driver.api.core.type.DataTypes;
import com.datastax.oss.driver.api.querybuilder.SchemaBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class ExampleDao {
public static final String KEY_SPACE = "camel_ks";
public static final String TABLE_NAME = "example";
private static final Logger LOG = LoggerFactory.getLogger(ExampleDao.class);
private final CqlSession session;
public ExampleDao(CqlSession session) {
this.session = session;
}
public void createKeySpace() {
Map<String, Object> replication = new HashMap<>();
replication.put("class", "SimpleStrategy");
replication.put("replication_factor", 3);
String statement = SchemaBuilder.createKeyspace(KEY_SPACE)
.ifNotExists()
.withReplicationOptions(replication)
.asCql();
LOG.info("Executing {}", statement);
ResultSet rs = session.execute(statement);
if (!rs.wasApplied()) {
LOG.warn("The create key space statement did not execute");
}
}
public void useKeySpace() {
// Use String.format because "Bind variables cannot be used for keyspace names"
String statement = String.format("USE %s", KEY_SPACE);
session.execute(statement);
}
public void createTable() {
SimpleStatement statement = SchemaBuilder.createTable(TABLE_NAME)
.ifNotExists()
.withPartitionKey("id", DataTypes.TIMEUUID)
.withClusteringColumn("number", DataTypes.BIGINT)
.withColumn("text", DataTypes.TEXT)
.builder()
.setTimeout(Duration.ofSeconds(10)).build();
LOG.info("Executing create table {}", statement);
ResultSet rs = session.execute(statement);
if (!rs.wasApplied()) {
LOG.warn("The create table statement did not execute");
}
}
public static String getInsertStatement() {
return "insert into example(id, number, text) values (now(), ?, ?)";
}
public static String getSelectStatement(int limitSize) {
return String.format("select id, dateOf(id) as insertion_date,number,text from example limit %d", limitSize);
}
public void delete(UUID id) {
session.execute("delete from camel_ks.example where id=?", id);
}
public void getData(Consumer<String> consumer) {
ResultSet rs = session.execute("select * from example");
if (rs != null) {
Iterator<Row> iterator = rs.iterator();
while (iterator.hasNext()) {
Row row = iterator.next();
String data = row.getString("text");
LOG.trace("Retrieved data: {}", data);
consumer.accept(data);
}
} else {
LOG.warn("No records were returned");
}
}
public void insert(long number, String text) {
session.execute(getInsertStatement(), number, text);
}
}
| 1,690 |
0 | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra/main/CassandraRoute.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.cassandra.main;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.cassandra.CassandraConstants;
import org.apache.camel.processor.resume.kafka.KafkaResumeStrategyConfigurationBuilder;
import org.apache.camel.resume.ResumeAction;
import org.apache.camel.support.resume.Resumables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CassandraRoute extends RouteBuilder {
private static final Logger LOG = LoggerFactory.getLogger(CassandraRoute.class);
private final CountDownLatch latch;
private final int batchSize;
private final CassandraClient client;
private final KafkaResumeStrategyConfigurationBuilder configurationBuilder;
public CassandraRoute(CountDownLatch latch, int batchSize, KafkaResumeStrategyConfigurationBuilder configurationBuilder, CassandraClient client) {
this.latch = latch;
this.batchSize = batchSize;
this.configurationBuilder = configurationBuilder;
this.client = client;
}
private class CustomResumeAction implements ResumeAction {
private final ExampleDao dao;
public CustomResumeAction(ExampleDao dao) {
this.dao = dao;
dao.useKeySpace();
}
@Override
public boolean evalEntry(Object key, Object value) {
LOG.trace("Evaluating entry {} with value {}", key, value);
dao.delete(UUID.fromString((String) value));
return false;
}
}
private void addResumeInfo(Exchange exchange) {
ExampleEntry bodyEntry = exchange.getMessage().getBody(ExampleEntry.class);
LOG.info("Received record number: {}", bodyEntry.getNumber());
exchange.getMessage().setHeader(Exchange.OFFSET, Resumables.of(bodyEntry.getId().toString(), bodyEntry.getId().toString()));
if (latch.getCount() == 1) {
exchange.setRouteStop(true);
}
latch.countDown();
}
@Override
public void configure() {
bindToRegistry(CassandraConstants.CASSANDRA_RESUME_ACTION, new CustomResumeAction(client.newExampleDao()));
fromF("cql:{{cassandra.host}}:{{cassandra.cql3.port}}/camel_ks?cql=%s&resultSetConversionStrategy=#class:%s",
ExampleDao.getSelectStatement(batchSize), ExampleResultSetConversionStrategy.class.getName())
.split(body()) // We receive a list of records so, for each
.resumable()
.configuration(configurationBuilder)
.intermittent(true) // Set to ignore empty data sets that will generate exchanges w/ no offset information
.process(this::addResumeInfo);
}
}
| 1,691 |
0 | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra/main/MainApp.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.cassandra.main;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import org.apache.camel.component.caffeine.resume.CaffeineCache;
import org.apache.camel.example.resume.strategies.kafka.KafkaUtil;
import org.apache.camel.main.Main;
import org.apache.camel.processor.resume.kafka.KafkaResumeStrategyConfigurationBuilder;
import org.apache.camel.processor.resume.kafka.SingleNodeKafkaResumeStrategy;
public class MainApp {
public static void main(String[] args) {
String host = System.getProperty("cassandra.host", "localhost");
String txtPort = System.getProperty("cassandra.cql3.port", "9042");
int port = Integer.valueOf(txtPort);
// Runs the load action
String action = System.getProperty("resume.action");
if ("load".equalsIgnoreCase(action)) {
try {
loadData(host, port);
System.exit(0);
} catch (Exception e) {
System.err.println("Unable to load data: " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
}
// Normal code path for consuming from Cassandra
final KafkaResumeStrategyConfigurationBuilder configurationBuilder = KafkaUtil.getDefaultKafkaResumeStrategyConfigurationBuilder();
Main main = new Main();
Integer batchSize = Integer.parseInt(System.getProperty("batch.size", "50"));
CountDownLatch latch = new CountDownLatch(batchSize);
Executors.newSingleThreadExecutor().submit(() -> waitForStop(main, latch));
try (CassandraClient client = new CassandraClient(host, port)) {
configurationBuilder.withResumeCache(new CaffeineCache<>(10240));
main.configure().addRoutesBuilder(new CassandraRoute(latch, batchSize, configurationBuilder, client));
main.start();
}
}
public static void loadData(String host, int port) {
try (CassandraClient cassandraClient = new CassandraClient(host, port)) {
ExampleDao exampleDao = cassandraClient.newExampleDao();
exampleDao.createKeySpace();
exampleDao.useKeySpace();
exampleDao.createTable();
int dataSize = Integer.parseInt(System.getProperty("data.size", "500"));
for (long i = 0; i < dataSize; i++) {
exampleDao.insert(i, UUID.randomUUID().toString());
}
}
}
private static void waitForStop(Main main, CountDownLatch latch) {
try {
latch.await();
main.stop();
while (!main.isStopped()) {
Thread.sleep(1000);
}
System.exit(0);
} catch (InterruptedException e) {
System.exit(1);
}
}
}
| 1,692 |
0 | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra/main/ExampleEntry.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.cassandra.main;
import java.time.Instant;
import java.util.UUID;
public class ExampleEntry {
private UUID id;
private Instant insertionDate;
private long number;
private String text;
public ExampleEntry() {
}
public ExampleEntry(UUID id, Instant insertionDate, long number, String text) {
this.id = id;
this.insertionDate = insertionDate;
this.number = number;
this.text = text;
}
public Instant getInsertionDate() {
return insertionDate;
}
public void setInsertionDate(Instant insertionDate) {
this.insertionDate = insertionDate;
}
public long getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public UUID getId() {
return id;
}
@Override
public String toString() {
return "ExampleEntry{" +
"id=" + id +
", insertionDate=" + insertionDate +
", number=" + number +
", text='" + text + '\'' +
'}';
}
}
| 1,693 |
0 | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra/main/ExampleResultSetConversionStrategy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.cassandra.main;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import org.apache.camel.component.cassandra.ResultSetConversionStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExampleResultSetConversionStrategy implements ResultSetConversionStrategy {
private static final Logger LOG = LoggerFactory.getLogger(ExampleResultSetConversionStrategy.class);
@Override
public Object getBody(ResultSet resultSet) {
List<ExampleEntry> ret = new ArrayList<>();
Iterator<Row> iterator = resultSet.iterator();
while (iterator.hasNext()) {
Row row = iterator.next();
UUID id = row.getUuid("id");
final Instant insertion_date = row.getInstant("insertion_date");
long number = row.getLong("number");
String text = row.getString("text");
ret.add(new ExampleEntry(id, insertion_date, number, text));
LOG.trace("Retrieved number {}, insertion date: {}. text: {}", number, insertion_date, text);
}
return ret;
}
}
| 1,694 |
0 | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra | Create_ds/camel-examples/resume-api/resume-api-cassandraql/src/main/java/org/apache/camel/example/resume/cassandra/main/CassandraClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.cassandra.main;
import java.net.InetSocketAddress;
import com.datastax.oss.driver.api.core.CqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple client for Cassandra for testing purposes
*/
class CassandraClient implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(CassandraClient.class);
private CqlSession session;
public CassandraClient(String host, int port) {
tryConnect(host, port);
}
private void tryConnect(String host, int port) {
InetSocketAddress socketAddress = new InetSocketAddress(host, port);
int i = 12;
do {
try {
LOG.info("Trying to connect to: {}:{}", host, port);
session = CqlSession.builder()
.addContactPoint(socketAddress)
.withLocalDatacenter("datacenter1")
.build();
return;
} catch (Exception e) {
LOG.error("Failed to connect: {}", e.getMessage());
i--;
if (i == 0) {
throw e;
}
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
return;
}
}
} while (i > 0);
}
public ExampleDao newExampleDao() {
return new ExampleDao(this.session);
}
@Override
public void close() {
session.close();
}
}
| 1,695 |
0 | Create_ds/camel-examples/resume-api/resume-api-aws2-kinesis/src/main/java/org/apache/camel/example/resume/aws/kinesis | Create_ds/camel-examples/resume-api/resume-api-aws2-kinesis/src/main/java/org/apache/camel/example/resume/aws/kinesis/main/KinesisRoute.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.aws.kinesis.main;
import java.util.concurrent.CountDownLatch;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.kinesis.Kinesis2Constants;
import org.apache.camel.example.resume.strategies.kafka.KafkaUtil;
import org.apache.camel.resume.cache.ResumeCache;
import org.apache.camel.support.resume.Resumables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.kinesis.KinesisClient;
public class KinesisRoute extends RouteBuilder {
private static final Logger LOG = LoggerFactory.getLogger(KinesisRoute.class);
private final String streamName;
private final ResumeCache<String> resumeCache;
private final KinesisClient client;
private final CountDownLatch latch;
public KinesisRoute(String streamName, ResumeCache<String> resumeCache, KinesisClient client, CountDownLatch latch) {
this.streamName = streamName;
this.resumeCache = resumeCache;
this.client = client;
this.latch = latch;
}
private void addResumeOffset(Exchange exchange) {
String sequenceNumber = exchange.getMessage().getHeader(Kinesis2Constants.SEQUENCE_NUMBER, String.class);
exchange.getMessage().setHeader(Exchange.OFFSET, Resumables.of(streamName, sequenceNumber));
String body = exchange.getMessage().getBody(String.class);
LOG.warn("Processing: {} with sequence number {}", body, sequenceNumber);
latch.countDown();
}
@Override
public void configure() {
bindToRegistry("amazonKinesisClient", client);
String kinesisEndpointUri = "aws2-kinesis://%s?amazonKinesisClient=#amazonKinesisClient";
fromF(kinesisEndpointUri, streamName)
.resumable().configuration(KafkaUtil.getDefaultKafkaResumeStrategyConfigurationBuilder().withResumeCache(resumeCache))
.process(this::addResumeOffset);
}
}
| 1,696 |
0 | Create_ds/camel-examples/resume-api/resume-api-aws2-kinesis/src/main/java/org/apache/camel/example/resume/aws/kinesis | Create_ds/camel-examples/resume-api/resume-api-aws2-kinesis/src/main/java/org/apache/camel/example/resume/aws/kinesis/main/MainApp.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.aws.kinesis.main;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.caffeine.resume.CaffeineCache;
import org.apache.camel.main.Main;
import org.apache.camel.test.infra.aws2.clients.AWSSDKClientUtils;
import org.apache.camel.test.infra.aws2.clients.KinesisUtils;
import software.amazon.awssdk.services.kinesis.KinesisClient;
/**
* A Camel Application
*/
public class MainApp {
/**
* A main() so we can easily run these routing rules in our IDE
*/
public static void main(String... args) {
Main main = new Main();
String streamName = System.getProperty("aws.kinesis.streamName", "aws-kinesis-test");
String action = System.getProperty("resume.action");
KinesisClient client = AWSSDKClientUtils.newKinesisClient();
if ("load".equalsIgnoreCase(action)) {
// do load
loadData(client, streamName, 500);
return;
}
Integer batchSize = Integer.parseInt(System.getProperty("batch.size", "50"));
CountDownLatch latch = new CountDownLatch(batchSize);
Executors.newSingleThreadExecutor().submit(() -> waitForStop(main, latch));
RouteBuilder routeBuilder = new KinesisRoute(streamName, new CaffeineCache<>(100), client, latch);
main.configure().addRoutesBuilder(routeBuilder);
main.start();
}
private static void loadData(KinesisClient client, String streamName, int recordCount) {
KinesisUtils.createStream(client, streamName);
KinesisUtils.putRecords(client, streamName, recordCount);
}
private static void waitForStop(Main main, CountDownLatch latch) {
try {
main.stop();
while (!main.isStopped()) {
Thread.sleep(1000);
}
latch.await();
System.exit(0);
} catch (InterruptedException e) {
System.exit(1);
}
}
}
| 1,697 |
0 | Create_ds/camel-examples/resume-api/resume-api-fileset/src/main/java/org/apache/camel/example/resume/fileset | Create_ds/camel-examples/resume-api/resume-api-fileset/src/main/java/org/apache/camel/example/resume/fileset/main/MainApp.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.fileset.main;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.caffeine.resume.CaffeineCache;
import org.apache.camel.example.resume.strategies.kafka.check.CheckRoute;
import org.apache.camel.example.resume.strategies.kafka.fileset.LargeDirectoryRouteBuilder;
import org.apache.camel.main.Main;
/**
* A Camel Application
*/
public class MainApp {
/**
* A main() so we can easily run these routing rules in our IDE
*/
public static void main(String... args) throws Exception {
Main main = new Main();
RouteBuilder routeBuilder = new LargeDirectoryRouteBuilder(new CaffeineCache<>(10000));
main.configure().addRoutesBuilder(new CheckRoute());
main.configure().addRoutesBuilder(routeBuilder);
main.run(args);
}
}
| 1,698 |
0 | Create_ds/camel-examples/resume-api/resume-api-fileset-wal/src/main/java/org/apache/camel/example/resume/fileset/wal | Create_ds/camel-examples/resume-api/resume-api-fileset-wal/src/main/java/org/apache/camel/example/resume/fileset/wal/main/MainApp.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.resume.fileset.wal.main;
import java.io.File;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.caffeine.resume.CaffeineCache;
import org.apache.camel.component.wal.WriteAheadResumeStrategyConfigurationBuilder;
import org.apache.camel.example.resume.strategies.kafka.KafkaUtil;
import org.apache.camel.example.resume.strategies.kafka.check.CheckRoute;
import org.apache.camel.example.resume.strategies.kafka.fileset.LargeDirectoryRouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.processor.resume.kafka.SingleNodeKafkaResumeStrategy;
/**
* A Camel Application
*/
public class MainApp {
/**
* A main() so we can easily run these routing rules in our IDE
*/
public static void main(String... args) throws Exception {
Main main = new Main();
SingleNodeKafkaResumeStrategy resumeStrategy = KafkaUtil.getDefaultStrategy();
final String logFile = System.getProperty("wal.log.file");
final long delay = Long.parseLong(System.getProperty("processing.delay", "0"));
final WriteAheadResumeStrategyConfigurationBuilder configurationBuilder = WriteAheadResumeStrategyConfigurationBuilder
.newBuilder()
.withDelegateResumeStrategy(resumeStrategy)
.withLogFile(new File(logFile));
RouteBuilder routeBuilder = new LargeDirectoryRouteBuilder(configurationBuilder, new CaffeineCache<>(10000), delay);
main.configure().addRoutesBuilder(new CheckRoute());
main.configure().addRoutesBuilder(routeBuilder);
main.run(args);
}
}
| 1,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.