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/camel-examples/telegram/src/main/java/org/apache/camel/example | Create_ds/camel-examples/telegram/src/main/java/org/apache/camel/example/telegram/TelegramRouteBuilder.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.telegram;
import org.apache.camel.builder.RouteBuilder;
public class TelegramRouteBuilder extends RouteBuilder {
@Override
public void configure() {
from("direct:start")
.toF("telegram:bots/?authorizationToken=%s&chatId=%s", Application.AUTHORIZATION_TOKEN, Application.CHAT_ID);
}
}
| 1,800 |
0 | Create_ds/camel-examples/telegram/src/main/java/org/apache/camel/example/telegram | Create_ds/camel-examples/telegram/src/main/java/org/apache/camel/example/telegram/usage/TelegramMethodUsage.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.telegram.usage;
import org.apache.camel.CamelContext;
public interface TelegramMethodUsage {
void run(CamelContext context) throws InterruptedException;
}
| 1,801 |
0 | Create_ds/camel-examples/telegram/src/main/java/org/apache/camel/example/telegram | Create_ds/camel-examples/telegram/src/main/java/org/apache/camel/example/telegram/usage/GetUpdatesUsage.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.telegram.usage;
import org.apache.camel.CamelContext;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.component.telegram.model.Update;
import org.apache.camel.example.telegram.Application;
public class GetUpdatesUsage implements TelegramMethodUsage {
@Override
public void run(CamelContext context) {
ConsumerTemplate template = context.createConsumerTemplate();
Update message = template.receiveBodyNoWait(String.format("telegram:bots/?authorizationToken=%s&chatId=%s", Application.AUTHORIZATION_TOKEN, Application.CHAT_ID), Update.class);
System.out.println(message);
}
}
| 1,802 |
0 | Create_ds/camel-examples/telegram/src/main/java/org/apache/camel/example/telegram | Create_ds/camel-examples/telegram/src/main/java/org/apache/camel/example/telegram/usage/SendMessageUsage.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.telegram.usage;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.telegram.model.MessageResult;
import org.apache.camel.component.telegram.model.OutgoingTextMessage;
public class SendMessageUsage implements TelegramMethodUsage {
@Override
public void run(CamelContext context) {
ProducerTemplate template = context.createProducerTemplate();
OutgoingTextMessage msg = new OutgoingTextMessage();
msg.setText("Hello world!");
MessageResult msgResult = template.requestBody("direct:start", msg, MessageResult.class);
System.out.println(msgResult);
}
}
| 1,803 |
0 | Create_ds/camel-examples/telegram/src/main/java/org/apache/camel/example/telegram | Create_ds/camel-examples/telegram/src/main/java/org/apache/camel/example/telegram/usage/SendVenueUsage.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.telegram.usage;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.telegram.model.MessageResult;
import org.apache.camel.component.telegram.model.SendVenueMessage;
public class SendVenueUsage implements TelegramMethodUsage {
private double latitude = 59.9386292;
private double longitude = 30.3141308;
@Override
public void run(CamelContext context) throws InterruptedException {
ProducerTemplate template = context.createProducerTemplate();
SendVenueMessage msg = new SendVenueMessage(latitude, longitude, "MyTitle", "MyAddress");
MessageResult result = template.requestBody("direct:start", msg, MessageResult.class);
System.out.println(result);
}
}
| 1,804 |
0 | Create_ds/camel-examples/telegram/src/main/java/org/apache/camel/example/telegram | Create_ds/camel-examples/telegram/src/main/java/org/apache/camel/example/telegram/usage/LiveLocationUsage.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.telegram.usage;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.telegram.model.EditMessageLiveLocationMessage;
import org.apache.camel.component.telegram.model.MessageResult;
import org.apache.camel.component.telegram.model.SendLocationMessage;
import org.apache.camel.component.telegram.model.StopMessageLiveLocationMessage;
public class LiveLocationUsage implements TelegramMethodUsage {
private double latitude = 59.9386292;
private double longitude = 30.3141308;
@Override
public void run(CamelContext context) throws InterruptedException {
ProducerTemplate template = context.createProducerTemplate();
SendLocationMessage msg = new SendLocationMessage(latitude, longitude);
msg.setLivePeriod(new Integer(60));
MessageResult firstLocationMessage = template.requestBody("direct:start", msg, MessageResult.class);
System.out.println(firstLocationMessage);
long messageId = firstLocationMessage.getMessage().getMessageId();
double delta = 0.001;
for (int i = 0; i < 3; i++) {
double positionDelta = delta * (i + 1);
EditMessageLiveLocationMessage liveLocationMessage = new EditMessageLiveLocationMessage(latitude + positionDelta, longitude + positionDelta);
liveLocationMessage.setMessageId(messageId);
MessageResult editedMessage = template.requestBody("direct:start", liveLocationMessage, MessageResult.class);
System.out.println(editedMessage);
Thread.sleep(3000);
}
StopMessageLiveLocationMessage stopLiveLocationMessage = new StopMessageLiveLocationMessage();
stopLiveLocationMessage.setMessageId(messageId);
MessageResult stopMessage = template.requestBody("direct:start", stopLiveLocationMessage, MessageResult.class);
System.out.println(stopMessage);
}
}
| 1,805 |
0 | Create_ds/camel-examples/main-health/src/test/java/org/apache/camel | Create_ds/camel-examples/main-health/src/test/java/org/apache/camel/example/MainHealthTest.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.AdviceWith;
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.BeforeEach;
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 supports custom health-checks.
*/
class MainHealthTest extends CamelMainTestSupport {
@Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
return asProperties("myPeriod", Integer.toString(500));
}
@Override
@BeforeEach
public void setUp() throws Exception {
// Prevent failure by replacing the failing endpoint
replaceRouteFromWith("netty", "direct:foo");
super.setUp();
}
@Test
void should_support_custom_health_checks() throws Exception {
NotifyBuilder notify = new NotifyBuilder(context)
.whenCompleted(2).whenBodiesDone("Chaos monkey was here", "All is okay").create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "2 messages should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
}
}
| 1,806 |
0 | Create_ds/camel-examples/main-health/src/main/java/org/apache/camel | Create_ds/camel-examples/main-health/src/main/java/org/apache/camel/example/MonkeyHealthCheck.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.Map;
import org.apache.camel.health.HealthCheckResultBuilder;
import org.apache.camel.impl.health.AbstractHealthCheck;
import org.apache.camel.spi.annotations.HealthCheck;
/**
* A chaos monkey health check that reports UP or DOWN in a chaotic way.
*
* This is a custom implementation of a Camel {@link org.apache.camel.health.HealthCheck}
* which is automatic discovered if bound in the {@link org.apache.camel.spi.Registry} and
* used as part of Camel's health-check system.
*/
@HealthCheck("monkey-check")
public class MonkeyHealthCheck extends AbstractHealthCheck {
private static boolean up = true;
public MonkeyHealthCheck() {
super("custom", "monkey");
}
@Override
protected void doCall(HealthCheckResultBuilder builder, Map<String, Object> options) {
builder.detail("monkey", "The chaos monkey was here");
if (up) {
builder.up();
} else {
builder.down();
}
}
public static String chaos() {
up = !up;
return up ? "All is okay" : "Chaos monkey was here";
}
}
| 1,807 |
0 | Create_ds/camel-examples/main-health/src/main/java/org/apache/camel | Create_ds/camel-examples/main-health/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,808 |
0 | Create_ds/camel-examples/main-health/src/main/java/org/apache/camel | Create_ds/camel-examples/main-health/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 {
// to trigger the health check to flip between UP and DOWN then lets call it as a Java bean from
// a route
from("timer:foo?period={{myPeriod}}").routeId("timer")
.bean(MonkeyHealthCheck.class, "chaos")
.log("${body}");
// this route is invalid and fails during startup
// the supervising route controller will take over and attempt
// to restart this route
from("netty:tcp:unknownhost").to("log:dummy").routeId("netty");
}
}
| 1,809 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-sqs-consumer/src/test/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-sqs-consumer/src/test/java/org/apache/camel/example/AwsSQSTest.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.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.sqs.Sqs2Component;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.infra.aws.common.services.AWSService;
import org.apache.camel.test.infra.aws2.clients.AWSSDKClientUtils;
import org.apache.camel.test.infra.aws2.services.AWSServiceFactory;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can consume messages from Amazon SQS.
*/
class AwsSQSTest extends CamelMainTestSupport {
@RegisterExtension
private static final AWSService AWS_SERVICE = AWSServiceFactory.createSQSService();
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
Sqs2Component sqs = camelContext.getComponent("aws2-sqs", Sqs2Component.class);
sqs.getConfiguration().setAmazonSQSClient(AWSSDKClientUtils.newSQSClient());
return camelContext;
}
@Test
void should_poll_sqs_queue() {
// Add a message first
template.send("direct:publishMessage", exchange -> exchange.getIn().setBody("Camel rocks!"));
NotifyBuilder notify = new NotifyBuilder(context).from("aws2-sqs:*").whenCompleted(1).create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
configuration.addRoutesBuilder(new PublishMessageRouteBuilder());
}
private static class PublishMessageRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:publishMessage").to("aws2-sqs://{{sqs-queue-name}}?autoCreateQueue=true");
}
}
}
| 1,810 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-sqs-consumer/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-sqs-consumer/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,811 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-sqs-consumer/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-sqs-consumer/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() throws Exception {
from(aws2Sqs("{{sqs-queue-name}}").deleteAfterRead(true).autoCreateQueue(true))
.log("${body}");
}
}
| 1,812 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-s3-events-inject/src/test/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-s3-events-inject/src/test/java/org/apache/camel/example/AwsS3Test.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.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.component.aws2.s3.AWS2S3Component;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.infra.aws.common.services.AWSService;
import org.apache.camel.test.infra.aws2.clients.AWSSDKClientUtils;
import org.apache.camel.test.infra.aws2.services.AWSServiceFactory;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can store content into an Amazon S3 bucket.
*/
class AwsS3Test extends CamelMainTestSupport {
@RegisterExtension
private static final AWSService AWS_SERVICE = AWSServiceFactory.createS3Service();
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
AWS2S3Component s3 = camelContext.getComponent("aws2-s3", AWS2S3Component.class);
s3.getConfiguration().setAmazonS3Client(AWSSDKClientUtils.newS3Client());
return camelContext;
}
@Test
void should_store_content_into_a_s3_bucket() throws Exception {
NotifyBuilder notify = new NotifyBuilder(context).wereSentTo("aws2-s3:*").whenCompleted(1).create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
}
}
| 1,813 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-s3-events-inject/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-s3-events-inject/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,814 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-s3-events-inject/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-s3-events-inject/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() throws Exception {
from(timer("fire").repeatCount("1"))
.setBody(constant("Camel rocks"))
.to(aws2S3("{{bucketName}}").keyName("firstfile").autoCreateBucket(true))
.stop();
}
}
| 1,815 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-eventbridge-creator/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-eventbridge-creator/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,816 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-eventbridge-creator/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2/aws2-eventbridge-creator/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 java.util.ArrayList;
import java.util.List;
import org.apache.camel.builder.endpoint.EndpointRouteBuilder;
import org.apache.camel.component.aws2.eventbridge.EventbridgeConstants;
import org.apache.camel.component.aws2.eventbridge.EventbridgeOperations;
import software.amazon.awssdk.services.eventbridge.model.Target;
/**
* To use the endpoint DSL then we must extend EndpointRouteBuilder instead of RouteBuilder
*/
public class MyRouteBuilder extends EndpointRouteBuilder {
@Override
public void configure() throws Exception {
from(timer("fire").repeatCount("1"))
.setHeader(EventbridgeConstants.RULE_NAME, constant("s3-events-rule"))
.to(aws2Eventbridge("default")
.operation(EventbridgeOperations.putRule)
.eventPatternFile("file:src/main/resources/eventpattern.json"))
.process(exchange -> {
exchange.getMessage().setHeader(EventbridgeConstants.RULE_NAME, "s3-events-rule");
Target target = Target.builder().id("sqs-queue").arn("arn:aws:sqs:eu-west-1:780410022472:camel-connector-test").build();
List<Target> targets = new ArrayList<>();
targets.add(target);
exchange.getMessage().setHeader(EventbridgeConstants.TARGETS, targets);
})
.to(aws2Eventbridge("default")
.operation(EventbridgeOperations.putTargets))
.log("All set, enjoy!");
}
}
| 1,817 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3/src/test/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3/src/test/java/org/apache/camel/example/AwsS3Test.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.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.s3.AWS2S3Component;
import org.apache.camel.component.aws2.s3.AWS2S3Constants;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.infra.aws.common.services.AWSService;
import org.apache.camel.test.infra.aws2.clients.AWSSDKClientUtils;
import org.apache.camel.test.infra.aws2.services.AWSServiceFactory;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can poll an Amazon S3 bucket.
*/
class AwsS3Test extends CamelMainTestSupport {
@RegisterExtension
private static final AWSService AWS_SERVICE = AWSServiceFactory.createS3Service();
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
AWS2S3Component s3 = camelContext.getComponent("aws2-s3", AWS2S3Component.class);
s3.getConfiguration().setAmazonS3Client(AWSSDKClientUtils.newS3Client());
return camelContext;
}
@Test
void should_poll_s3_bucket() {
// Add a bucket first
template.send("direct:putObject", exchange -> {
exchange.getIn().setHeader(AWS2S3Constants.KEY, "camel-content-type.txt");
exchange.getIn().setHeader(AWS2S3Constants.CONTENT_TYPE, "application/text");
exchange.getIn().setBody("Camel rocks!");
});
NotifyBuilder notify = new NotifyBuilder(context).from("aws2-s3:*").whenCompleted(1).create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
configuration.addRoutesBuilder(new AddBucketRouteBuilder());
}
private static class AddBucketRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:putObject").to("aws2-s3://{{bucketName}}?autoCreateBucket=true");
}
}
}
| 1,818 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3/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,819 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3/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() throws Exception {
from(aws2S3("{{bucketName}}").delay(1000L).useDefaultCredentialsProvider(true).deleteAfterRead(false))
.log("The content is ${body}");
}
}
| 1,820 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3/src/test/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3/src/test/java/org/apache/camel/example/KafkaAwsS3Test.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.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.s3.AWS2S3Component;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.infra.aws.common.services.AWSService;
import org.apache.camel.test.infra.aws2.clients.AWSSDKClientUtils;
import org.apache.camel.test.infra.aws2.services.AWSServiceFactory;
import org.apache.camel.test.infra.kafka.services.KafkaService;
import org.apache.camel.test.infra.kafka.services.KafkaServiceFactory;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static org.apache.camel.util.PropertiesHelper.asProperties;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can poll data from a Kafka topic and put it into an Amazon S3 bucket.
*/
class KafkaAwsS3Test extends CamelMainTestSupport {
@RegisterExtension
private static final AWSService AWS_SERVICE = AWSServiceFactory.createS3Service();
@RegisterExtension
private static final KafkaService KAFKA_SERVICE = KafkaServiceFactory.createService();
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
AWS2S3Component s3 = camelContext.getComponent("aws2-s3", AWS2S3Component.class);
s3.getConfiguration().setAmazonS3Client(AWSSDKClientUtils.newS3Client());
return camelContext;
}
@Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
return asProperties(
"kafkaBrokers", KAFKA_SERVICE.getBootstrapServers()
);
}
@Test
void should_poll_kafka_and_push_to_s3_bucket() {
NotifyBuilder notify = new NotifyBuilder(context).from("kafka:*").whenCompleted(2).create();
// Load data into Kafka
template.sendBody("direct:kafkaT1", "Camel rocks in topic 1!");
template.sendBody("direct:kafkaT2", "Camel rocks in topic 2!");
assertTrue(
notify.matches(10, TimeUnit.SECONDS), "2 messages should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
configuration.addRoutesBuilder(new LoadKafkaRouteBuilder());
}
private static class LoadKafkaRouteBuilder extends RouteBuilder {
@Override
public void configure() {
from("direct:kafkaT1").to("kafka:{{kafkaTopic1}}?brokers={{kafkaBrokers}}");
from("direct:kafkaT2").to("kafka:{{kafkaTopic2}}?brokers={{kafkaBrokers}}");
}
}
}
| 1,821 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3/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,822 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3/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;
import org.apache.camel.component.aws2.s3.stream.AWSS3NamingStrategyEnum;
public class MyRouteBuilder extends EndpointRouteBuilder {
@Override
public void configure() throws Exception {
from(kafka("{{kafkaTopic1}}").brokers("{{kafkaBrokers}}")
.seekTo("{{consumer.seekTo}}"))
.log("Kafka Message is: ${body}")
.to(aws2S3("{{bucketName}}").useDefaultCredentialsProvider(true).autoCreateBucket(true).streamingUploadMode(true).batchMessageNumber(25).namingStrategy(AWSS3NamingStrategyEnum.progressive).keyName("{{kafkaTopic1}}/{{kafkaTopic1}}.txt"));
from(kafka("{{kafkaTopic2}}").brokers("{{kafkaBrokers}}")
.seekTo("{{consumer.seekTo}}"))
.log("Kafka Message is: ${body}")
.to(aws2S3("{{bucketName}}").useDefaultCredentialsProvider(true).autoCreateBucket(true).streamingUploadMode(true).batchMessageNumber(25).namingStrategy(AWSS3NamingStrategyEnum.progressive).keyName("{{kafkaTopic2}}/{{kafkaTopic2}}.txt"));
}
}
| 1,823 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3-restarting-policy/src/test/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3-restarting-policy/src/test/java/org/apache/camel/example/KafkaAwsS3Test.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.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.s3.AWS2S3Component;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.infra.aws.common.services.AWSService;
import org.apache.camel.test.infra.aws2.clients.AWSSDKClientUtils;
import org.apache.camel.test.infra.aws2.services.AWSServiceFactory;
import org.apache.camel.test.infra.kafka.services.KafkaService;
import org.apache.camel.test.infra.kafka.services.KafkaServiceFactory;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static org.apache.camel.util.PropertiesHelper.asProperties;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can poll data from a Kafka topic and put it into an Amazon S3 bucket.
*/
class KafkaAwsS3Test extends CamelMainTestSupport {
@RegisterExtension
private static final AWSService AWS_SERVICE = AWSServiceFactory.createS3Service();
@RegisterExtension
private static final KafkaService KAFKA_SERVICE = KafkaServiceFactory.createService();
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
AWS2S3Component s3 = camelContext.getComponent("aws2-s3", AWS2S3Component.class);
s3.getConfiguration().setAmazonS3Client(AWSSDKClientUtils.newS3Client());
return camelContext;
}
@Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
return asProperties(
"kafkaBrokers", KAFKA_SERVICE.getBootstrapServers()
);
}
@Test
void should_poll_kafka_and_push_to_s3_bucket() {
NotifyBuilder notify = new NotifyBuilder(context).from("kafka:*").whenCompleted(1).create();
// Load data into Kafka
template.sendBody("direct:kafka", "Camel rocks in topic 1!");
assertTrue(
notify.matches(10, TimeUnit.SECONDS), "2 messages should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
configuration.addRoutesBuilder(new LoadKafkaRouteBuilder());
}
private static class LoadKafkaRouteBuilder extends RouteBuilder {
@Override
public void configure() {
from("direct:kafka").to("kafka:{{kafkaTopic1}}?brokers={{kafkaBrokers}}");
}
}
}
| 1,824 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3-restarting-policy/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3-restarting-policy/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,825 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3-restarting-policy/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-kafka-aws2-s3-restarting-policy/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;
import org.apache.camel.component.aws2.s3.stream.AWSS3NamingStrategyEnum;
import org.apache.camel.component.aws2.s3.stream.AWSS3RestartingPolicyEnum;
public class MyRouteBuilder extends EndpointRouteBuilder {
@Override
public void configure() throws Exception {
from(kafka("{{kafkaTopic1}}").brokers("{{kafkaBrokers}}").seekTo("{{consumer.seekTo}}"))
.log("Kafka Message is: ${body}")
.toD(aws2S3("{{bucketName}}")
.streamingUploadMode(true)
.useDefaultCredentialsProvider(true)
.autoCreateBucket(true)
.restartingPolicy(AWSS3RestartingPolicyEnum.lastPart)
.batchMessageNumber(25).namingStrategy(AWSS3NamingStrategyEnum.progressive)
.keyName("{{kafkaTopic1}}/partition_${headers.kafka.PARTITION}/{{kafkaTopic1}}.txt"));
}
}
| 1,826 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3-kafka/src/test/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3-kafka/src/test/java/org/apache/camel/example/AwsS3KafkaTest.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.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.s3.AWS2S3Component;
import org.apache.camel.component.aws2.s3.AWS2S3Constants;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.infra.aws.common.services.AWSService;
import org.apache.camel.test.infra.aws2.clients.AWSSDKClientUtils;
import org.apache.camel.test.infra.aws2.services.AWSServiceFactory;
import org.apache.camel.test.infra.kafka.services.KafkaService;
import org.apache.camel.test.infra.kafka.services.KafkaServiceFactory;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static org.apache.camel.util.PropertiesHelper.asProperties;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can poll an Amazon S3 bucket and put the data into a Kafka topic.
*/
class AwsS3KafkaTest extends CamelMainTestSupport {
@RegisterExtension
private static final AWSService AWS_SERVICE = AWSServiceFactory.createS3Service();
@RegisterExtension
private static final KafkaService KAFKA_SERVICE = KafkaServiceFactory.createService();
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
AWS2S3Component s3 = camelContext.getComponent("aws2-s3", AWS2S3Component.class);
s3.getConfiguration().setAmazonS3Client(AWSSDKClientUtils.newS3Client());
return camelContext;
}
@Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
return asProperties(
"kafkaBrokers", KAFKA_SERVICE.getBootstrapServers()
);
}
@Test
void should_poll_s3_bucket_and_push_to_kafka() {
// Add a bucket first
template.send("direct:putObject", exchange -> {
exchange.getIn().setHeader(AWS2S3Constants.KEY, "camel-content-type.txt");
exchange.getIn().setHeader(AWS2S3Constants.CONTENT_TYPE, "application/text");
exchange.getIn().setBody("Camel rocks!");
});
NotifyBuilder notify = new NotifyBuilder(context).from("kafka:*").whenCompleted(1).create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
configuration.addRoutesBuilder(new AddBucketRouteBuilder());
}
private static class AddBucketRouteBuilder extends RouteBuilder {
@Override
public void configure() {
from("direct:putObject").to("aws2-s3://{{bucketName}}?autoCreateBucket=true");
}
}
}
| 1,827 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3-kafka/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3-kafka/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,828 |
0 | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3-kafka/src/main/java/org/apache/camel | Create_ds/camel-examples/aws/main-endpointdsl-aws2-s3-kafka/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;
public class MyRouteBuilder extends EndpointRouteBuilder {
@Override
public void configure() throws Exception {
from(aws2S3("{{bucketName}}").delay(1000L).useDefaultCredentialsProvider(true).deleteAfterRead(true)).startupOrder(2)
.to(kafka("{{kafkaTopic}}").brokers("{{kafkaBrokers}}"));
from(kafka("{{kafkaTopic}}").brokers("{{kafkaBrokers}}")).startupOrder(1)
.log("Kafka Message is: ${body}");
}
}
| 1,829 |
0 | Create_ds/camel-examples/hazelcast-kubernetes/src/main/java/org/apache/camel/example/kubernetes | Create_ds/camel-examples/hazelcast-kubernetes/src/main/java/org/apache/camel/example/kubernetes/fmp/HazelcastRoute.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.fmp;
import java.util.UUID;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.config.SSLConfig;
import com.hazelcast.core.HazelcastInstance;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.hazelcast.HazelcastConstants;
import org.apache.camel.component.hazelcast.HazelcastOperation;
import org.apache.camel.component.hazelcast.topic.HazelcastTopicComponent;
public class HazelcastRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
// setup hazelcast
ClientConfig config = new ClientConfig();
config.getNetworkConfig().addAddress("hazelcast");
config.getNetworkConfig().setSSLConfig(new SSLConfig().setEnabled(false));
HazelcastInstance instance = HazelcastClient.newHazelcastClient(config);
// setup camel hazelcast
HazelcastTopicComponent hazelcast = new HazelcastTopicComponent();
hazelcast.setHazelcastInstance(instance);
getContext().addComponent("hazelcast-topic", hazelcast);
from("timer:foo?period=5000")
.log("Producer side: Sending data to Hazelcast topic..")
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(HazelcastConstants.OPERATION, HazelcastOperation.PUBLISH);
String payload = "Test " + UUID.randomUUID();
exchange.getIn().setBody(payload);
}
})
.to("hazelcast-topic:foo");
from("hazelcast-topic:foo")
.log("Consumer side: Detected following action: $simple{in.header.CamelHazelcastListenerAction}");
}
}
| 1,830 |
0 | Create_ds/camel-examples/reactive-executor-vertx/src/test/java/org/apache/camel | Create_ds/camel-examples/reactive-executor-vertx/src/test/java/org/apache/camel/example/VertxTest.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 io.vertx.core.Vertx;
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.AfterEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can use VertX as reactive executor.
*/
class VertxTest extends CamelMainTestSupport {
@AfterEach
void destroy() {
Vertx vertx = context.getRegistry().lookupByNameAndType("vertx", Vertx.class);
if (vertx != null) {
vertx.close();
}
}
@Override
protected void bindToRegistry(Registry registry) throws Exception {
registry.bind("vertx", Vertx.vertx());
}
@Test
void should_use_vertx_as_reactive_executor() {
NotifyBuilder notify = new NotifyBuilder(context).from("timer:*").whenCompleted(15).create();
assertTrue(
notify.matches(30, TimeUnit.SECONDS), "15 messages should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
}
}
| 1,831 |
0 | Create_ds/camel-examples/reactive-executor-vertx/src/main/java/org/apache/camel | Create_ds/camel-examples/reactive-executor-vertx/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 io.vertx.core.Vertx;
import org.apache.camel.BindToRegistry;
import org.apache.camel.CamelContext;
import org.apache.camel.Configuration;
import org.apache.camel.main.Main;
import org.apache.camel.support.LifecycleStrategySupport;
/**
* 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);
}
@Configuration
static class MyConfiguration {
@BindToRegistry(value = "vertx", beanPostProcess = true)
public Vertx vertx(CamelContext camelContext) {
// register existing vertx which should be used by Camel
final Vertx vertx = Vertx.vertx();
// register 'vertx' bean stop lifecycle hook
camelContext.addLifecycleStrategy(new LifecycleStrategySupport() {
@Override
public void onContextStopped(CamelContext context) {
super.onContextStopped(context);
// stop vertx
vertx.close();
}
});
return vertx;
}
}
}
| 1,832 |
0 | Create_ds/camel-examples/reactive-executor-vertx/src/main/java/org/apache/camel | Create_ds/camel-examples/reactive-executor-vertx/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=5s")
.setBody().constant("H,e,l,l,o, ,W,o,r,l,d,!,!,!, , ")
.split(body().tokenize(",")).parallelProcessing()
.log("${body}")
.end();
}
}
| 1,833 |
0 | Create_ds/camel-examples/main-xml/src/test/java/org/apache/camel | Create_ds/camel-examples/main-xml/src/test/java/org/apache/camel/example/MainXMLTest.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 supports XML routes.
*/
class MainXMLTest extends CamelMainTestSupport {
@Test
void should_support_xml_routes() {
NotifyBuilder notify = new NotifyBuilder(context).whenCompleted(1).whenBodiesDone("Bye World").create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addConfiguration(MyConfiguration.class);
configuration.withRoutesIncludePattern("routes/*.xml");
}
}
| 1,834 |
0 | Create_ds/camel-examples/main-xml/src/main/java/org/apache/camel | Create_ds/camel-examples/main-xml/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.CamelContext;
import org.apache.camel.Configuration;
import org.apache.camel.PropertyInject;
import org.apache.camel.CamelConfiguration;
/**
* Class to configure the Camel application.
*/
@Configuration
public class MyConfiguration implements CamelConfiguration {
@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);
}
@Override
public void configure(CamelContext camelContext) {
// this method is optional and can be removed if no additional configuration is needed.
}
}
| 1,835 |
0 | Create_ds/camel-examples/main-xml/src/main/java/org/apache/camel | Create_ds/camel-examples/main-xml/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);
// and add all the XML routes
main.configure().withRoutesIncludePattern("routes/*.xml");
// turn on reloading routes on code-changes
main.configure().withRoutesReloadEnabled(true);
main.configure().withRoutesReloadDirectory("src/main/resources");
main.configure().withRoutesReloadPattern("routes/*.xml");
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,836 |
0 | Create_ds/camel-examples/main-xml/src/main/java/org/apache/camel | Create_ds/camel-examples/main-xml/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,837 |
0 | Create_ds/camel-examples/main/src/test/java/org/apache/camel | Create_ds/camel-examples/main/src/test/java/org/apache/camel/example/MainWithAnnotationTest.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.BeanInject;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.test.main.junit5.CamelMainTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test using the annotation based approach checking that Camel supports binding via annotations.
*/
@CamelMainTest(mainClass = MyApplication.class)
class MainWithAnnotationTest {
@BeanInject
CamelContext context;
@Test
void should_support_binding_via_annotations() {
NotifyBuilder notify = new NotifyBuilder(context)
.whenCompleted(1).whenBodiesDone("Hello how are you?").create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
}
}
| 1,838 |
0 | Create_ds/camel-examples/main/src/test/java/org/apache/camel | Create_ds/camel-examples/main/src/test/java/org/apache/camel/example/MainTest.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 using the legacy approach checking that Camel supports binding via annotations.
*/
class MainTest extends CamelMainTestSupport {
@Test
void should_support_binding_via_annotations() {
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 Class<?> getMainClass() {
return MyApplication.class;
}
}
| 1,839 |
0 | Create_ds/camel-examples/main/src/main/java/org/apache/camel | Create_ds/camel-examples/main/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;
/**
* Class to configure the Camel application.
*/
@Configuration
public class MyConfiguration {
@BindToRegistry
public MyBean myBean(@PropertyInject("hi") String hi) {
// this will create an instance of this bean with the name of the method (eg myBean)
return new MyBean(hi);
}
}
| 1,840 |
0 | Create_ds/camel-examples/main/src/main/java/org/apache/camel | Create_ds/camel-examples/main/src/main/java/org/apache/camel/example/StandaloneCamel.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.impl.DefaultCamelContext;
/**
* This is an alternative example to show how you can use a public static void main method
* to run Camel standalone (without help from its Main class). This is to demonstrate
* what code you need to write to start up Camel without any help (or magic).
* <p/>
* Compare this example with {@link MyApplication} which uses Camel's main class to
* run Camel standalone in an easier way.
*/
public final class StandaloneCamel {
private StandaloneCamel() {
}
public static void main(String[] args) throws Exception {
// create a new CamelContext
try (CamelContext camelContext = new DefaultCamelContext()) {
// configure where to load properties file in the properties component
camelContext.getPropertiesComponent().setLocation("classpath:application.properties");
// resolve property placeholder
String hello = camelContext.resolvePropertyPlaceholders("{{hi}}");
// and create bean with the placeholder
MyBean myBean = new MyBean(hello);
// register bean to Camel
camelContext.getRegistry().bind("myBean", myBean);
// add routes to Camel
camelContext.addRoutes(new MyRouteBuilder());
// start Camel
camelContext.start();
// just run for 10 seconds and stop
System.out.println("Running for 10 seconds and then stopping");
Thread.sleep(10000);
}
}
}
| 1,841 |
0 | Create_ds/camel-examples/main/src/main/java/org/apache/camel | Create_ds/camel-examples/main/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,842 |
0 | Create_ds/camel-examples/main/src/main/java/org/apache/camel | Create_ds/camel-examples/main/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").routeId("foo")
.bean("myBean", "hello")
.log("${body}");
}
}
| 1,843 |
0 | Create_ds/camel-examples/main/src/main/java/org/apache/camel | Create_ds/camel-examples/main/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;
public MyBean(String hi) {
this.hi = hi;
}
public String hello() {
return hi + " how are you?";
}
}
| 1,844 |
0 | Create_ds/camel-examples/csimple/src/generated/java/org/apache/camel | Create_ds/camel-examples/csimple/src/generated/java/org/apache/camel/example/CSimpleScript3.java | package org.apache.camel.example;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
import org.apache.camel.*;
import org.apache.camel.util.*;
import org.apache.camel.spi.*;
import static org.apache.camel.language.csimple.CSimpleHelper.*;
public class CSimpleScript3 extends org.apache.camel.language.csimple.CSimpleSupport {
Language bean;
public CSimpleScript3() {
}
@Override
public boolean isPredicate() {
return true;
}
@Override
public String getText() {
return "${body} > 5";
}
@Override
public Object evaluate(CamelContext context, Exchange exchange, Message message, Object body) throws Exception {
return isGreaterThan(exchange, body, 5);
}
}
| 1,845 |
0 | Create_ds/camel-examples/csimple/src/generated/java/org/apache/camel | Create_ds/camel-examples/csimple/src/generated/java/org/apache/camel/example/CSimpleScript2.java | package org.apache.camel.example;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
import org.apache.camel.*;
import org.apache.camel.util.*;
import org.apache.camel.spi.*;
import static org.apache.camel.language.csimple.CSimpleHelper.*;
public class CSimpleScript2 extends org.apache.camel.language.csimple.CSimpleSupport {
Language bean;
public CSimpleScript2() {
}
@Override
public boolean isPredicate() {
return true;
}
@Override
public String getText() {
return "${body} > 10";
}
@Override
public Object evaluate(CamelContext context, Exchange exchange, Message message, Object body) throws Exception {
return isGreaterThan(exchange, body, 10);
}
}
| 1,846 |
0 | Create_ds/camel-examples/csimple/src/generated/java/org/apache/camel | Create_ds/camel-examples/csimple/src/generated/java/org/apache/camel/example/CSimpleScript1.java | package org.apache.camel.example;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
import org.apache.camel.*;
import org.apache.camel.util.*;
import org.apache.camel.spi.*;
import static org.apache.camel.language.csimple.CSimpleHelper.*;
public class CSimpleScript1 extends org.apache.camel.language.csimple.CSimpleSupport {
Language bean;
public CSimpleScript1() {
}
@Override
public boolean isPredicate() {
return false;
}
@Override
public String getText() {
return "${random(20)}";
}
@Override
public Object evaluate(CamelContext context, Exchange exchange, Message message, Object body) throws Exception {
return random(exchange, 0, 20);
}
}
| 1,847 |
0 | Create_ds/camel-examples/csimple/src/test/java/org/apache/camel | Create_ds/camel-examples/csimple/src/test/java/org/apache/camel/example/CSimpleTest.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 are evaluated as expected.
*/
class CSimpleTest 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,848 |
0 | Create_ds/camel-examples/csimple/src/main/java/org/apache/camel | Create_ds/camel-examples/csimple/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,849 |
0 | Create_ds/camel-examples/csimple/src/main/java/org/apache/camel | Create_ds/camel-examples/csimple/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("${body} > 10")
.log("high ${body}")
.when().csimple("${body} > 5")
.log("med ${body}")
.otherwise()
.log("low ${body}");
}
}
| 1,850 |
0 | Create_ds/camel-examples/couchbase-log/src/test/java/org/apache/camel | Create_ds/camel-examples/couchbase-log/src/test/java/org/apache/camel/example/CouchbaseTest.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.time.Duration;
import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.json.JsonObject;
import com.couchbase.client.java.manager.bucket.BucketSettings;
import com.couchbase.client.java.manager.bucket.BucketType;
import com.couchbase.client.java.manager.view.DesignDocument;
import com.couchbase.client.java.manager.view.View;
import com.couchbase.client.java.view.DesignDocumentNamespace;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.component.couchbase.CouchbaseConstants;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.infra.couchbase.services.CouchbaseService;
import org.apache.camel.test.infra.couchbase.services.CouchbaseServiceFactory;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static org.apache.camel.util.PropertiesHelper.asProperties;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel consume data from Couchbase.
*/
class CouchbaseTest extends CamelMainTestSupport {
private static final String BUCKET = "test-bucket-" + System.currentTimeMillis();
@RegisterExtension
private static final CouchbaseService SERVICE = CouchbaseServiceFactory.createService();
private static Cluster CLUSTER;
@BeforeAll
static void init() {
CLUSTER = Cluster.connect(
SERVICE.getConnectionString(), SERVICE.getUsername(), SERVICE.getPassword()
);
DesignDocument designDoc = new DesignDocument(
CouchbaseConstants.DEFAULT_DESIGN_DOCUMENT_NAME,
Collections.singletonMap(
CouchbaseConstants.DEFAULT_VIEWNAME,
new View("function (doc, meta) { emit(meta.id, doc);}")
)
);
CLUSTER.buckets().createBucket(
BucketSettings.create(BUCKET).bucketType(BucketType.COUCHBASE).flushEnabled(true));
CLUSTER.bucket(BUCKET).viewIndexes().upsertDesignDocument(designDoc, DesignDocumentNamespace.PRODUCTION);
}
@AfterAll
static void destroy() {
if (CLUSTER != null) {
CLUSTER.buckets().dropBucket(BUCKET);
CLUSTER.disconnect();
}
}
@Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
return asProperties(
"couchbase.host", SERVICE.getHostname(),
"couchbase.port", Integer.toString(SERVICE.getPort()),
"couchbase.username", SERVICE.getUsername(),
"couchbase.password", SERVICE.getPassword(),
"couchbase.bucket", BUCKET
);
}
@Test
void should_consume_bucket() {
Bucket bucket = CLUSTER.bucket(BUCKET);
bucket.waitUntilReady(Duration.ofSeconds(10L));
for (int i = 0; i < 10; i++) {
bucket.defaultCollection().upsert("my-doc-" + i, JsonObject.create().put("name", "My Name " + i));
}
NotifyBuilder notify = new NotifyBuilder(context).whenCompleted(10).wereSentTo("log:info").create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "10 messages should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
}
}
| 1,851 |
0 | Create_ds/camel-examples/couchbase-log/src/main/java/org/apache/camel | Create_ds/camel-examples/couchbase-log/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,852 |
0 | Create_ds/camel-examples/couchbase-log/src/main/java/org/apache/camel | Create_ds/camel-examples/couchbase-log/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("couchbase:http://{{couchbase.host}}:{{couchbase.port}}?bucket={{couchbase.bucket}}&username={{couchbase.username}}&password={{couchbase.password}}&consumerProcessedStrategy={{couchbase.consumerProcessedStrategy}}")
.to("log:info");
}
}
| 1,853 |
0 | Create_ds/camel-examples/routetemplate-xml/src/test/java/org/apache/camel | Create_ds/camel-examples/routetemplate-xml/src/test/java/org/apache/camel/example/RouteTemplateXMLTest.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 supports parameterized routes in XML.
*/
class RouteTemplateXMLTest extends CamelMainTestSupport {
@Test
void should_support_parameterized_routes() {
NotifyBuilder notify = new NotifyBuilder(context).from("timer:*").whenCompleted(2).create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "2 messages should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.withRoutesIncludePattern("templates/*.xml,builders/*.xml");
}
}
| 1,854 |
0 | Create_ds/camel-examples/routetemplate-xml/src/main/java/org/apache/camel | Create_ds/camel-examples/routetemplate-xml/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 boots up 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();
// and add all the XML templates and builders
// make sure that the templates are listed before the builders to prevent
// route creation error
main.configure().withRoutesIncludePattern("templates/*.xml,builders/*.xml");
// now keep the application running until the JVM is terminated (ctrl + c or sigterm)
main.run(args);
}
}
| 1,855 |
0 | Create_ds/camel-examples/main-endpointdsl/src/test/java/org/apache/camel | Create_ds/camel-examples/main-endpointdsl/src/test/java/org/apache/camel/example/MainEndpointDSLTest.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 supports routes with endpoints built with the endpoint DSL.
*/
class MainEndpointDSLTest extends CamelMainTestSupport {
@Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
return asProperties("myPeriod", Integer.toString(500));
}
@Test
void should_support_routes_built_with_endpoint_dsl() {
NotifyBuilder notify = new NotifyBuilder(context)
.whenCompleted(1).whenBodiesDone("Davs how are you? I am called 1 times").create();
assertTrue(
notify.matches(20, TimeUnit.SECONDS), "1 message should be completed"
);
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(MyRouteBuilder.class);
}
}
| 1,856 |
0 | Create_ds/camel-examples/main-endpointdsl/src/main/java/org/apache/camel | Create_ds/camel-examples/main-endpointdsl/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,857 |
0 | Create_ds/camel-examples/main-endpointdsl/src/main/java/org/apache/camel | Create_ds/camel-examples/main-endpointdsl/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.BeanScope;
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() throws Exception {
// the endpoint-dsl allows to define endpoints in type safe fluent builders
// here we configure the time and bean endpoint
from(timer("foo")
.period("{{myPeriod}}") // here we use {{ }} to refer to properties from application.properties
.includeMetadata(false)
.repeatCount(123))
.to(bean("org.apache.camel.example.MyBean")
.method("hello")
// try change this to Prototype scope
.scope(BeanScope.Singleton)
// we can configure advanced options
.advanced().parameters("hi", "Davs"))
.log("${body}");
}
}
| 1,858 |
0 | Create_ds/camel-examples/main-endpointdsl/src/main/java/org/apache/camel | Create_ds/camel-examples/main-endpointdsl/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 int counter;
public String getHi() {
return hi;
}
public void setHi(String hi) {
this.hi = hi;
}
public String hello() {
return hi + " how are you? I am called " + ++counter + " times";
}
}
| 1,859 |
0 | Create_ds/camel-examples/whatsapp/src/main/java/org/apache/camel/example | Create_ds/camel-examples/whatsapp/src/main/java/org/apache/camel/example/whatsapp/WhatsappExamplesRunner.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.whatsapp;
import org.apache.camel.CamelContext;
import org.apache.camel.StartupListener;
import org.apache.camel.component.whatsapp.model.TextMessage;
import org.apache.camel.component.whatsapp.model.TextMessageRequest;
public class WhatsappExamplesRunner implements StartupListener {
private static final String CAMEL_EMOJI = "\uD83D\uDC2B";
@Override
public void onCamelContextStarted(CamelContext context, boolean alreadyStarted) throws Exception {
// Send message to whatsapp
TextMessageRequest request = new TextMessageRequest();
request.setTo(Application.RECIPIENT_PHONE_NUMBER);
request.setText(new TextMessage());
request.getText().setBody("This is an auto-generated message from Camel " + CAMEL_EMOJI);
context.createProducerTemplate().requestBody("direct:start", request);
}
}
| 1,860 |
0 | Create_ds/camel-examples/whatsapp/src/main/java/org/apache/camel/example | Create_ds/camel-examples/whatsapp/src/main/java/org/apache/camel/example/whatsapp/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.whatsapp;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
public final class Application {
public static final String AUTHORIZATION_TOKEN;
public static final String PHONE_NUMBER_ID;
public static final String RECIPIENT_PHONE_NUMBER;
public static final String WEBHOOK_VERIFY_TOKEN;
static {
Properties properties = new Properties();
ClassLoader loader = Application.class.getClassLoader();
try (InputStream resourceStream = loader.getResourceAsStream("application.properties")) {
properties.load(resourceStream);
} catch (IOException e) {
e.printStackTrace();
}
AUTHORIZATION_TOKEN = properties.getProperty("authorizationToken");
PHONE_NUMBER_ID = properties.getProperty("phoneNumberId");
RECIPIENT_PHONE_NUMBER = properties.getProperty("recipientPhoneNumber");
WEBHOOK_VERIFY_TOKEN = properties.getProperty("webhookVerifyToken");
}
private Application() {
// noop
}
public static void main(String[] args) throws Exception {
try (CamelContext context = new DefaultCamelContext()) {
context.start();
context.addRoutes(new WhatsappRouteBuilder());
context.addStartupListener(new WhatsappExamplesRunner());
Thread.sleep(6000000);
}
}
}
| 1,861 |
0 | Create_ds/camel-examples/whatsapp/src/main/java/org/apache/camel/example | Create_ds/camel-examples/whatsapp/src/main/java/org/apache/camel/example/whatsapp/WhatsappRouteBuilder.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.whatsapp;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.whatsapp.model.TextMessage;
import org.apache.camel.component.whatsapp.model.TextMessageRequest;
public class WhatsappRouteBuilder extends RouteBuilder {
@Override
public void configure() {
restConfiguration().port(8080);
// Send custom message
from("direct:start")
.toF("whatsapp:%s/?authorizationToken=%s", Application.PHONE_NUMBER_ID, Application.AUTHORIZATION_TOKEN);
// Echo to a message sent from the number
fromF("webhook:whatsapp:%s?authorizationToken=%s&webhookVerifyToken=%s", Application.PHONE_NUMBER_ID, Application.AUTHORIZATION_TOKEN, Application.WEBHOOK_VERIFY_TOKEN)
.log("${body}")
.choice().when().jsonpath("$.entry[0].changes[0].value.messages", true)
.setHeader("CamelWhatsappBody").jsonpath("$.entry[0].changes[0].value.messages[0].text.body")
.setHeader("CamelWhatsappSentMessage").jsonpath("$.entry[0].changes[0].value.contacts[0].profile.name")
.setHeader("CamelWhatsappPhoneNumber").jsonpath("$.entry[0].changes[0].value.contacts[0].wa_id")
.process(exchange -> {
TextMessageRequest request = new TextMessageRequest();
request.setTo(exchange.getIn().getHeader("CamelWhatsappPhoneNumber").toString());
request.setText(new TextMessage());
request.getText().setBody(String.format("Hello %s message sent was %s",
exchange.getIn().getHeader("CamelWhatsappSentMessage"),
exchange.getIn().getHeader("CamelWhatsappBody")));
exchange.getIn().setBody(request);
})
.toF("whatsapp:%s/?authorizationToken=%s", Application.PHONE_NUMBER_ID, Application.AUTHORIZATION_TOKEN)
.end();
}
}
| 1,862 |
0 | Create_ds/camel-examples/vault/google-secret-manager-reloading/src/main/java/org/apache/camel | Create_ds/camel-examples/vault/google-secret-manager-reloading/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 java.time.Instant;
import org.apache.camel.main.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main class that boot the Camel application
*/
public final class MyApplication {
private static final Logger LOG = LoggerFactory.getLogger(MyApplication.class);
public static Instant lastTime = null;
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,863 |
0 | Create_ds/camel-examples/vault/google-secret-manager-reloading/src/main/java/org/apache/camel | Create_ds/camel-examples/vault/google-secret-manager-reloading/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://myTimer?fixedRate=true&period=10000")
.log("Secret value is: {{gcp:hello}}");
}
}
| 1,864 |
0 | Create_ds/camel-examples/vault/aws-secrets-manager-reloading/src/main/java/org/apache/camel | Create_ds/camel-examples/vault/aws-secrets-manager-reloading/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.component.aws.secretsmanager.vault.CloudTrailReloadTriggerTask;
import org.apache.camel.main.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.camel.spi.ContextReloadStrategy;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudtrail.CloudTrailClient;
import software.amazon.awssdk.services.cloudtrail.model.*;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Main class that boot the Camel application
*/
public final class MyApplication {
private static final Logger LOG = LoggerFactory.getLogger(MyApplication.class);
public static Instant lastTime = null;
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,865 |
0 | Create_ds/camel-examples/vault/aws-secrets-manager-reloading/src/main/java/org/apache/camel | Create_ds/camel-examples/vault/aws-secrets-manager-reloading/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;
import org.apache.camel.component.aws.secretsmanager.SecretsManagerConstants;
public class MyRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer://myTimer?fixedRate=true&period=10000")
.log("Secret value is: {{aws:SecretTest}}");
}
}
| 1,866 |
0 | Create_ds/camel-examples/vault/aws-secrets-manager/src/main/java/org/apache/camel | Create_ds/camel-examples/vault/aws-secrets-manager/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,867 |
0 | Create_ds/camel-examples/vault/aws-secrets-manager/src/main/java/org/apache/camel | Create_ds/camel-examples/vault/aws-secrets-manager/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;
import org.apache.camel.component.aws.secretsmanager.SecretsManagerConstants;
public class MyRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer://myTimer?fixedRate=true&period=10000")
.toD("https://finnhub.io/api/v1/quote?symbol={{stock}}&token={{aws:finnhub_token}}")
.setBody().jsonpath("$.c", true)
.log("Current {{stockName}} price: ${body} $");
}
}
| 1,868 |
0 | Create_ds/camel-examples/vault/azure-key-vault-reloading/src/main/java/org/apache/camel | Create_ds/camel-examples/vault/azure-key-vault-reloading/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 java.time.Instant;
import org.apache.camel.main.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main class that boot the Camel application
*/
public final class MyApplication {
private static final Logger LOG = LoggerFactory.getLogger(MyApplication.class);
public static Instant lastTime = null;
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,869 |
0 | Create_ds/camel-examples/vault/azure-key-vault-reloading/src/main/java/org/apache/camel | Create_ds/camel-examples/vault/azure-key-vault-reloading/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://myTimer?fixedRate=true&period=10000")
.log("Secret value is: {{azure:hello}}");
}
}
| 1,870 |
0 | Create_ds/camel-examples/debezium/src/test/java/org/apache/camel/example | Create_ds/camel-examples/debezium/src/test/java/org/apache/camel/example/debezium/DebeziumTest.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;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.kinesis.Kinesis2Component;
import org.apache.camel.component.sql.SqlComponent;
import org.apache.camel.main.MainConfigurationProperties;
import org.apache.camel.test.infra.aws.common.services.AWSService;
import org.apache.camel.test.infra.aws2.clients.AWSSDKClientUtils;
import org.apache.camel.test.infra.aws2.services.AWSServiceFactory;
import org.apache.camel.test.infra.cassandra.services.CassandraLocalContainerService;
import org.apache.camel.test.infra.cassandra.services.CassandraService;
import org.apache.camel.test.infra.postgres.services.PostgresLocalContainerService;
import org.apache.camel.test.infra.postgres.services.PostgresService;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.postgresql.ds.PGSimpleDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.CassandraContainer;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.utility.DockerImageName;
import software.amazon.awssdk.services.kinesis.KinesisClient;
import software.amazon.awssdk.services.kinesis.model.CreateStreamRequest;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.camel.util.PropertiesHelper.asProperties;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A unit test checking that Camel can propagate changes from one Database to another thanks to Debezium.
*/
class DebeziumTest extends CamelMainTestSupport {
private static final String PGSQL_IMAGE = "debezium/example-postgres:2.3.2.Final";
private static final String CASSANDRA_IMAGE = "cassandra:4.0.1";
private static final String SOURCE_DB_NAME = "debezium-db";
private static final String SOURCE_DB_SCHEMA = "inventory";
private static final String SOURCE_DB_USERNAME = "pgsql-user";
private static final String SOURCE_DB_PASSWORD = "pgsql-pw";
private static final Logger LOGGER = LoggerFactory.getLogger(DebeziumTest.class);
@RegisterExtension
private static final AWSService AWS_SERVICE = AWSServiceFactory.createKinesisService();
@RegisterExtension
private static final PostgresService POSTGRES_SERVICE = new PostgresLocalContainerService(
new PostgreSQLContainer<>(DockerImageName.parse(PGSQL_IMAGE).asCompatibleSubstituteFor("postgres"))
.withDatabaseName(SOURCE_DB_NAME)
.withUsername(SOURCE_DB_USERNAME)
.withPassword(SOURCE_DB_PASSWORD)
);
@RegisterExtension
private static final CassandraService CASSANDRA_SERVICE = new CassandraLocalContainerService(
new CassandraContainer<>(CASSANDRA_IMAGE)
.withInitScript("org/apache/camel/example/debezium/db-init.cql")
);
@BeforeEach
void init() throws IOException {
Files.deleteIfExists(Path.of("target/offset-01.data"));
}
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
Kinesis2Component component = camelContext.getComponent("aws2-kinesis", Kinesis2Component.class);
KinesisClient kinesisClient = AWSSDKClientUtils.newKinesisClient();
// Create the stream
kinesisClient.createStream(CreateStreamRequest.builder().streamName("camel-debezium-example").shardCount(1).build());
component.getConfiguration().setAmazonKinesisClient(kinesisClient);
// required for the sql component
PGSimpleDataSource db = new PGSimpleDataSource();
db.setServerNames(new String[]{POSTGRES_SERVICE.host()});
db.setPortNumbers(new int[]{POSTGRES_SERVICE.port()});
db.setUser(SOURCE_DB_USERNAME);
db.setPassword(SOURCE_DB_PASSWORD);
db.setDatabaseName(SOURCE_DB_NAME);
camelContext.getComponent("sql", SqlComponent.class).setDataSource(db);
return camelContext;
}
@Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
// Override the host and port of the broker
return asProperties(
"debezium.postgres.databaseHostName", POSTGRES_SERVICE.host(),
"debezium.postgres.databasePort", Integer.toString(POSTGRES_SERVICE.port()),
"debezium.postgres.databaseUser", SOURCE_DB_USERNAME,
"debezium.postgres.databasePassword", SOURCE_DB_PASSWORD,
"cassandra.node", String.format("%s:%d", CASSANDRA_SERVICE.getCassandraHost(), CASSANDRA_SERVICE.getCQL3Port())
);
}
@Test
void should_propagate_db_event_thanks_to_debezium() {
NotifyBuilder notify = new NotifyBuilder(context).from("aws2-kinesis:*").whenCompleted(3).create();
LOGGER.debug("Doing initial select");
List<?> resultSource = template.requestBody("direct:select", null, List.class);
assertEquals(9, resultSource.size(), "We should not have additional products in source");
await().atMost(20, SECONDS).until(() -> template.requestBody("direct:result", null, List.class).size(), equalTo(0));
// Wait until the notification message is written to the logfile
// If the insert is done before the end of the snapshot, no events are received
await().atMost(2, SECONDS).until(() -> snapshotIsDone());
LOGGER.debug("Doing insert");
template.sendBody("direct:insert", new Object[] { 1, "scooter", "Small 2-wheel yellow scooter", 5.54 });
resultSource = template.requestBody("direct:select", null, List.class);
assertEquals(10, resultSource.size(), "We should have one additional product in source");
await().atMost(20, SECONDS).until(() -> template.requestBody("direct:result", null, List.class).size(), equalTo(1));
LOGGER.debug("Doing update");
template.sendBody("direct:update", new Object[] { "yellow scooter", 1 });
resultSource = template.requestBody("direct:select", null, List.class);
assertEquals(10, resultSource.size(), "We should not have more product in source");
await().atMost(20, SECONDS).until(() -> template.requestBody("direct:result", null, List.class).size(), equalTo(1));
LOGGER.debug("Doing delete");
template.sendBody("direct:delete", new Object[] { 1 });
resultSource = template.requestBody("direct:select", null, List.class);
assertEquals(9, resultSource.size(), "We should have one less product in source");
await().atMost(20, SECONDS).until(() -> template.requestBody("direct:result", null, List.class).size(), equalTo(0));
assertTrue(
notify.matches(60, SECONDS), "3 messages should be completed"
);
}
private boolean snapshotIsDone() {
Path log = Path.of("target/notifications.log");
try {
return(Files.size(log)>0);
} catch (IOException e) {
return false;
}
}
@Override
protected void configure(MainConfigurationProperties configuration) {
configuration.addRoutesBuilder(DebeziumPgSQLConsumerToKinesis.createRouteBuilder());
configuration.addRoutesBuilder(KinesisProducerToCassandra.createRouteBuilder());
configuration.addRoutesBuilder(new ApplyChangesToPgSQLRouteBuilder());
}
private static class ApplyChangesToPgSQLRouteBuilder extends RouteBuilder {
@Override
public void configure() {
from("direct:select").toF("sql:select * from %s.products", SOURCE_DB_SCHEMA).to("mock:query");
from("direct:insert").toF("sql:insert into %s.products (id, name, description, weight) values (#, #, #, #)", SOURCE_DB_SCHEMA).to("mock:insert");
from("direct:update").toF("sql:update %s.products set name=# where id=#", SOURCE_DB_SCHEMA).to("mock:update");
from("direct:delete").toF("sql:delete from %s.products where id=#", SOURCE_DB_SCHEMA).to("mock:delete");
from("direct:result").to("cql:{{cassandra.node}}/{{cassandra.keyspace}}?cql=select * from dbzSink.products").to("mock:result");
}
}
}
| 1,871 |
0 | Create_ds/camel-examples/debezium/src/main/java/org/apache/camel/example | Create_ds/camel-examples/debezium/src/main/java/org/apache/camel/example/debezium/DebeziumPgSQLConsumerToKinesis.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;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.kinesis.Kinesis2Constants;
import org.apache.camel.component.debezium.DebeziumConstants;
import org.apache.camel.main.Main;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.kafka.connect.data.Struct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple example to consume data from Debezium and send it to Kinesis
*/
public final class DebeziumPgSQLConsumerToKinesis {
private static final Logger LOG = LoggerFactory.getLogger(DebeziumPgSQLConsumerToKinesis.class);
// use Camel Main to set up and run Camel
private static final Main MAIN = new Main();
private DebeziumPgSQLConsumerToKinesis() {
}
public static void main(String[] args) throws Exception {
LOG.debug("About to run Debezium integration...");
// add route
MAIN.configure().addRoutesBuilder(createRouteBuilder());
// start and run Camel (block)
MAIN.run();
}
static RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
// Initial Debezium route that will run and listen to the changes,
// first it will perform an initial snapshot using (select * from) in case no offset
// exists for the connector, and then it will listen to postgres for any DB events such as (UPDATE, INSERT and DELETE)
from("debezium-postgres:{{debezium.postgres.name}}?"
+ "databaseHostname={{debezium.postgres.databaseHostName}}"
+ "&databasePort={{debezium.postgres.databasePort}}"
+ "&databaseUser={{debezium.postgres.databaseUser}}"
+ "&databasePassword={{debezium.postgres.databasePassword}}"
+ "&topicPrefix={{debezium.postgres.topicPrefix}}"
+ "&databaseDbname={{debezium.postgres.databaseDbname}}"
+ "&schemaIncludeList={{debezium.postgres.schemaIncludeList}}"
+ "&tableIncludeList={{debezium.postgres.tableIncludeList}}"
+ "&replicaIdentityAutosetValues={{debezium.postgres.replica.identity.autoset.values}}"
+ "&additionalProperties.notification.enabled.channels=log"
+ "&offsetStorageFileName={{debezium.postgres.offsetStorageFileName}}")
.routeId("FromDebeziumPgSql")
// We will need to prepare the data for Kinesis, however we need to mention here is that Kinesis is a bit different from Kafka in terms
// of the key partition which only limited to 256 byte length, depending on the size of your key, that may not be optimal. Therefore, the safer option is to hash the key
// 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 will put everything as nested Map in order to utilize Camel's Type Format
final Map<String, Object> kinesisBody = new HashMap<>();
kinesisBody.put("key", key);
kinesisBody.put("value", value);
kinesisBody.put("operation", operation);
return kinesisBody;
})
// 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(Kinesis2Constants.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 kinesis
.to("aws2-kinesis:{{kinesis.streamName}}?accessKey=RAW({{kinesis.accessKey}})"
+ "&secretKey=RAW({{kinesis.secretKey}})"
+ "®ion={{kinesis.region}}")
.end();
}
};
}
}
| 1,872 |
0 | Create_ds/camel-examples/debezium/src/main/java/org/apache/camel/example | Create_ds/camel-examples/debezium/src/main/java/org/apache/camel/example/debezium/KinesisProducerToCassandra.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;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple example to sink data from Kinesis that produced by Debezium into Cassandra
*/
public final class KinesisProducerToCassandra {
private static final Logger LOG = LoggerFactory.getLogger(KinesisProducerToCassandra.class);
// use Camel Main to set up and run Camel
private static final Main MAIN = new Main();
private KinesisProducerToCassandra() {
}
public static void main(String[] args) throws Exception {
LOG.debug("About to run Kinesis to Cassandra integration...");
// add route
MAIN.configure().addRoutesBuilder(createRouteBuilder());
// start and run Camel (block)
MAIN.run();
}
static RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
// We set the CQL templates we need, note that an UPDATE in Cassandra means an UPSERT which is what we need
final String cqlUpdate = "update products set name = ?, description = ?, weight = ? where id = ?";
final String cqlDelete = "delete from products where id = ?";
from("aws2-kinesis:{{kinesis.streamName}}?accessKey=RAW({{kinesis.accessKey}})"
+ "&secretKey=RAW({{kinesis.secretKey}})"
+ "®ion={{kinesis.region}}")
// Since we expect the data of the body to be ByteArr, we convert it to String using Kinesis
// Type Converter, in order to unmarshal later from JSON to Map
.convertBodyTo(String.class)
// Unmarshal our body, it will convert it from JSON to Map
.unmarshal().json(JsonLibrary.Jackson)
// In order not to lose the operation that we set in Debezium, we set it as a property or as
// a header
.setProperty("DBOperation", simple("${body[operation]}"))
.choice()
// If we have a INSERT or UPDATE, we will need to set the body with the CQL query parameters since we are using
// camel-cassandraql component
.when(exchangeProperty("DBOperation").in("c", "u"))
.setBody(exchange -> {
final Map body = (Map) exchange.getMessage().getBody();
final Map value = (Map) body.get("value");
final Map key = (Map) body.get("key");
// We as well check for nulls
final String name = value.get("name") != null ? value.get("name").toString() : "";
final String description = value.get("description") != null ? value.get("description").toString() : "";
final float weight = value.get("weight") != null ? Float.parseFloat(value.get("weight").toString()) : 0;
return Arrays.asList(name, description, weight, key.get("id"));
})
// We set the appropriate query in the header so we don't run the same route twice
.setHeader("CQLQuery", constant(cqlUpdate))
// If we have a DELETE, then we just set the id as a query parameter in the body
.when(exchangeProperty("DBOperation").isEqualTo("d"))
.setBody(exchange -> {
final Map body = (Map) exchange.getMessage().getBody();
final Map key = (Map) body.get("key");
return Collections.singletonList(key.get("id"));
})
// We set the appropriate query in the header so we don't run the same route twice
.setHeader("CQLQuery", constant(cqlDelete))
.end()
.choice()
// We just make sure we ONLY handle INSERT, UPDATE and DELETE and nothing else
.when(exchangeProperty("DBOperation").in("c", "u", "d"))
// Send query to Cassandra
.recipientList(simple("cql:{{cassandra.node}}/{{cassandra.keyspace}}?cql=RAW(${header.CQLQuery})"))
.end();
}
};
}
}
| 1,873 |
0 | Create_ds/camel-examples/spring/src/test/java/org/apache/camel/example | Create_ds/camel-examples/spring/src/test/java/org/apache/camel/example/spring/IntegrationTest.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.spring;
import org.apache.camel.spring.Main;
import org.junit.jupiter.api.Test;
class IntegrationTest {
@Test
void testCamelRulesDeployCorrectlyInSpring() throws Exception {
// let's boot up the Spring application context for 2 seconds to check that it works OK
Main main = new Main();
main.run(new String[]{"-duration", "2s"});
}
}
| 1,874 |
0 | Create_ds/camel-examples/spring/src/main/java/org/apache/camel/example | Create_ds/camel-examples/spring/src/main/java/org/apache/camel/example/spring/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.spring;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.spring.Main;
/**
* A simple example router from a file system to an ActiveMQ queue and then to a file system
*/
public class MyRouteBuilder extends RouteBuilder {
/**
* Allow this route to be run as an application
*/
public static void main(String[] args) throws Exception {
new Main().run(args);
}
@Override
public void configure() {
// populate the message queue with some messages
from("file:src/data?noop=true").
to("jms:test.MyQueue");
from("jms:test.MyQueue").
to("file://target/test");
// set up a listener on the file component
from("file://target/test?noop=true").
bean(new SomeBean());
}
public static class SomeBean {
public void someMethod(String body) {
System.out.println("Received: " + body);
}
}
}
| 1,875 |
0 | Create_ds/camel-examples/console/src/test/java/org/apache/camel/example | Create_ds/camel-examples/console/src/test/java/org/apache/camel/example/console/ConsoleTest.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.console;
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 input data can be transformed to upper case as expected.
*/
@CamelSpringTest
@ContextConfiguration("/META-INF/spring/camel-context.xml")
@MockEndpoints("stream:out")
@UseAdviceWith
class ConsoleTest {
@Autowired
ProducerTemplate template;
@Autowired
ModelCamelContext context;
@EndpointInject("mock:stream:out")
MockEndpoint result;
@Test
void should_transform_input_data_to_upper_case() 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("HELLO WORLD");
result.expectedMessageCount(1);
template.sendBody("direct:in", "Hello World");
result.assertIsSatisfied();
}
}
| 1,876 |
0 | Create_ds/camel-examples/console/src/main/java/org/apache/camel/example | Create_ds/camel-examples/console/src/main/java/org/apache/camel/example/console/CamelConsoleMain.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.console;
import org.apache.camel.spring.Main;
/**
* A main class to run the example from your editor.
*/
public final class CamelConsoleMain {
private CamelConsoleMain() {
}
public static void main(String[] args) throws Exception {
// Main makes it easier to run a Spring application (default context 'META-INF/spring/*.xml' will be scanned)
Main main = new Main();
// run and block until Camel is stopped (or JVM terminated)
main.run();
}
}
| 1,877 |
0 | Create_ds/sputnik/src/test/java/com/airbnb/sputnik | Create_ds/sputnik/src/test/java/com/airbnb/sputnik/tools/BeansDataset.java | package com.airbnb.sputnik.tools;
import com.airbnb.sputnik.tools.beans.JsonData;
import com.airbnb.sputnik.tools.beans.ParsedData;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoder;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.SparkSession;
import java.util.Collections;
public class BeansDataset {
public static Dataset<ParsedData> getDataset(SparkSession sparkSession) {
JsonData jsonData = new JsonData();
jsonData.setInnerFieldOne("hi");
ParsedData parsedData = new ParsedData();
parsedData.setJsonFieldOne(jsonData);
parsedData.setFieldOne("someValue1");
Encoder<ParsedData> jsonDataEncoder = Encoders.bean(ParsedData.class);
Dataset<ParsedData> dataset =
sparkSession.createDataset(Collections.singletonList(parsedData), jsonDataEncoder);
return dataset;
}
}
| 1,878 |
0 | Create_ds/sputnik/src/test/java/com/airbnb/sputnik/tools | Create_ds/sputnik/src/test/java/com/airbnb/sputnik/tools/beans/MapData.java | package com.airbnb.sputnik.tools.beans;
public class MapData {
private String innerFieldOne;
private String innerFieldTwo;
public String getInnerFieldOne() {
return innerFieldOne;
}
public void setInnerFieldOne(String innerFieldOne) {
this.innerFieldOne = innerFieldOne;
}
public String getInnerFieldTwo() {
return innerFieldTwo;
}
public void setInnerFieldTwo(String innerFieldTwo) {
this.innerFieldTwo = innerFieldTwo;
}
}
| 1,879 |
0 | Create_ds/sputnik/src/test/java/com/airbnb/sputnik/tools | Create_ds/sputnik/src/test/java/com/airbnb/sputnik/tools/beans/ParsedData.java | package com.airbnb.sputnik.tools.beans;
import com.airbnb.sputnik.annotations.Comment;
import com.airbnb.sputnik.annotations.FieldsFormatting;
import com.airbnb.sputnik.annotations.JsonField;
import com.airbnb.sputnik.annotations.TableName;
import com.google.common.base.CaseFormat;
import java.io.Serializable;
@TableName("default.someTableParsedData")
@FieldsFormatting(CaseFormat.LOWER_UNDERSCORE)
public class ParsedData implements Serializable {
@Comment("Some comment")
private String fieldOne;
@JsonField private JsonData jsonFieldOne;
public String getFieldOne() {
return fieldOne;
}
public void setFieldOne(String fieldOne) {
this.fieldOne = fieldOne;
}
public JsonData getJsonFieldOne() {
return jsonFieldOne;
}
public void setJsonFieldOne(JsonData jsonFieldOne) {
this.jsonFieldOne = jsonFieldOne;
}
}
| 1,880 |
0 | Create_ds/sputnik/src/test/java/com/airbnb/sputnik/tools | Create_ds/sputnik/src/test/java/com/airbnb/sputnik/tools/beans/JsonData.java | package com.airbnb.sputnik.tools.beans;
import java.io.Serializable;
public class JsonData implements Serializable {
private String innerFieldOne;
public String getInnerFieldOne() {
return innerFieldOne;
}
public void setInnerFieldOne(String innerFieldOne) {
this.innerFieldOne = innerFieldOne;
}
}
| 1,881 |
0 | Create_ds/sputnik/src/test/java/com/airbnb/sputnik/tools | Create_ds/sputnik/src/test/java/com/airbnb/sputnik/tools/beans/ParsedDataMap.java | package com.airbnb.sputnik.tools.beans;
import com.airbnb.sputnik.annotations.MapField;
public class ParsedDataMap {
private String fieldOne;
@MapField private MapData mapData;
public String getFieldOne() {
return fieldOne;
}
public void setFieldOne(String fieldOne) {
this.fieldOne = fieldOne;
}
public MapData getMapData() {
return mapData;
}
public void setMapData(MapData mapData) {
this.mapData = mapData;
}
}
| 1,882 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/enums/TableFileFormat.java | package com.airbnb.sputnik.enums;
public enum TableFileFormat { ORC, PARQUET, RCFILE }
| 1,883 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/JsonField.java | package com.airbnb.sputnik.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface JsonField {
}
| 1,884 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/TableParallelism.java | package com.airbnb.sputnik.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TableParallelism {
int value();
}
| 1,885 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/TableName.java | package com.airbnb.sputnik.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TableName {
String value();
}
| 1,886 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/FieldsFormatting.java | package com.airbnb.sputnik.annotations;
import com.google.common.base.CaseFormat;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FieldsFormatting {
CaseFormat value();
}
| 1,887 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/MapField.java | package com.airbnb.sputnik.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MapField {}
| 1,888 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/Comment.java | package com.airbnb.sputnik.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Comment {
String value();
}
| 1,889 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/FieldsSubsetIsAllowed.java | package com.airbnb.sputnik.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FieldsSubsetIsAllowed {
boolean value();
}
| 1,890 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/TableFormat.java | package com.airbnb.sputnik.annotations;
import com.airbnb.sputnik.enums.TableFileFormat;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TableFormat {
TableFileFormat value();
}
| 1,891 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/TableDescription.java | package com.airbnb.sputnik.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TableDescription {
String value();
}
| 1,892 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/PartitioningField.java | package com.airbnb.sputnik.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface PartitioningField {
} | 1,893 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/checks/NotEmptyCheck.java | package com.airbnb.sputnik.annotations.checks;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface NotEmptyCheck {
}
| 1,894 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/checks/RecordMinCount.java | package com.airbnb.sputnik.annotations.checks;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RecordMinCount {
int minCount();
}
| 1,895 |
0 | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations | Create_ds/sputnik/src/main/java/com/airbnb/sputnik/annotations/checks/NotNull.java | package com.airbnb.sputnik.annotations.checks;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NotNull {
}
| 1,896 |
0 | Create_ds/iceberg/pig/src/test/java/com/netflix/iceberg | Create_ds/iceberg/pig/src/test/java/com/netflix/iceberg/pig/SchemaUtilTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed 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 com.netflix.iceberg.pig;
import com.netflix.iceberg.Schema;
import com.netflix.iceberg.types.Types.BinaryType;
import com.netflix.iceberg.types.Types.BooleanType;
import com.netflix.iceberg.types.Types.DecimalType;
import com.netflix.iceberg.types.Types.DoubleType;
import com.netflix.iceberg.types.Types.FloatType;
import com.netflix.iceberg.types.Types.IntegerType;
import com.netflix.iceberg.types.Types.ListType;
import com.netflix.iceberg.types.Types.LongType;
import com.netflix.iceberg.types.Types.MapType;
import com.netflix.iceberg.types.Types.StringType;
import com.netflix.iceberg.types.Types.StructType;
import org.apache.pig.ResourceSchema;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.junit.Test;
import java.io.IOException;
import static com.netflix.iceberg.types.Types.NestedField.optional;
import static com.netflix.iceberg.types.Types.NestedField.required;
import static org.junit.Assert.*;
public class SchemaUtilTest {
@Test
public void testPrimitive() throws IOException {
Schema icebergSchema = new Schema(
optional(1, "b", BooleanType.get()),
optional(1, "i", IntegerType.get()),
optional(2, "l", LongType.get()),
optional(3, "f", FloatType.get()),
optional(4, "d", DoubleType.get()),
optional(5, "dec", DecimalType.of(0,2)),
optional(5, "s", StringType.get()),
optional(6,"bi", BinaryType.get())
);
ResourceSchema pigSchema = SchemaUtil.convert(icebergSchema);
assertEquals("b:boolean,i:int,l:long,f:float,d:double,dec:bigdecimal,s:chararray,bi:bytearray", pigSchema.toString());
}
@Test
public void testComplex() throws IOException {
convertToPigSchema(
new Schema(
optional(1, "bag", ListType.ofOptional(2, BooleanType.get())),
optional(3, "map", MapType.ofOptional(4,5, StringType.get(), DoubleType.get())),
optional(6, "tuple", StructType.of(optional(7, "i", IntegerType.get()), optional(8,"f", FloatType.get())))
),"bag:{(boolean)},map:[double],tuple:(i:int,f:float)", null
);
}
@Test(expected = FrontendException.class)
public void invalidMap() throws IOException {
convertToPigSchema(new Schema(
optional(1, "invalid", MapType.ofOptional(2,3, IntegerType.get(), DoubleType.get()))
), "", "");
}
@Test
public void nestedMaps() throws IOException {
convertToPigSchema(new Schema(
optional(1, "nested",
MapType.ofOptional(2,3, StringType.get(),
MapType.ofOptional(4,5, StringType.get(),
MapType.ofOptional(6,7, StringType.get(), DecimalType.of(10,2)))))
),"nested:[[[bigdecimal]]]", "");
}
@Test
public void nestedBags() throws IOException {
convertToPigSchema(new Schema(
optional(1, "nested",
ListType.ofOptional(2,
ListType.ofOptional(3,
ListType.ofOptional(4, DoubleType.get()))))
), "nested:{({({(double)})})}", "");
}
@Test
public void nestedTuples() throws IOException {
convertToPigSchema(new Schema(
optional(1,"first", StructType.of(
optional(2, "second", StructType.of(
optional(3, "third", StructType.of(
optional(4, "val", StringType.get())
))
))
))
), "first:(second:(third:(val:chararray)))", "");
}
@Test
public void complexNested() throws IOException {
convertToPigSchema(new Schema(
optional(1,"t", StructType.of(
optional(2, "b", ListType.ofOptional(3,StructType.of(
optional(4, "i", IntegerType.get()),
optional(5,"s", StringType.get())
)))
)),
optional(6, "m1", MapType.ofOptional(7,8, StringType.get(), StructType.of(
optional(9, "b", ListType.ofOptional(10, BinaryType.get()) ),
optional(11, "m2", MapType.ofOptional(12,13, StringType.get(), IntegerType.get()))
))),
optional(14, "b1", ListType.ofOptional(15,
MapType.ofOptional(16,17, StringType.get(),
ListType.ofOptional(18, FloatType.get()))))
), "t:(b:{(i:int,s:chararray)}),m1:[(b:{(bytearray)},m2:[int])],b1:{([{(float)}])}", "");
}
@Test
public void mapConversions() throws IOException {
// consistent behavior for maps conversions. The below test case, correctly does not specify map key types
convertToPigSchema(
new Schema(
required(
1, "a",
MapType.ofRequired(
2, 3,
StringType.get(),
ListType.ofRequired(
4, StructType.of(
required(5, "b", LongType.get()),
required(6, "c", StringType.get())))))),
"a:[{(b:long,c:chararray)}]",
"We do not specify the map key type here");
// struct<a:map<string,map<string,double>>> -> (a:[[double]])
// As per https://pig.apache.org/docs/latest/basic.html#map-schema. It seems that
// we only need to specify value type as keys are always of type chararray
convertToPigSchema(
new Schema(
StructType.of(
required(1, "a", MapType.ofRequired(
2, 3,
StringType.get(),
MapType.ofRequired(4, 5, StringType.get(), DoubleType.get())))
).fields()),
"a:[[double]]",
"A map key type does not need to be specified");
}
@Test
public void testTupleInMap() throws IOException {
Schema icebergSchema = new Schema(
optional(
1, "nested_list",
MapType.ofOptional(
2, 3,
StringType.get(),
ListType.ofOptional(
4, StructType.of(
required(5, "id", LongType.get()),
optional(6, "data", StringType.get()))))));
ResourceSchema pigSchema = SchemaUtil.convert(icebergSchema);
assertEquals("nested_list:[{(id:long,data:chararray)}]", pigSchema.toString()); // The output should contain a nested struct within a list within a map, I think.
}
@Test
public void testLongInBag() throws IOException {
Schema icebergSchema = new Schema(
optional(
1, "nested_list",
MapType.ofOptional(
2, 3,
StringType.get(),
ListType.ofRequired(5, LongType.get()))));
SchemaUtil.convert(icebergSchema);
}
@Test
public void doubleWrappingTuples() throws IOException {
// struct<a:array<struct<b:string>>> -> (a:{(b:chararray)})
convertToPigSchema(
new Schema(
StructType.of(
required(1, "a", ListType.ofRequired(2, StructType.of(required(3, "b", StringType.get()))))
).fields()),
"a:{(b:chararray)}",
"A tuple inside a bag should not be double wrapped");
// struct<a:array<boolean>> -> "(a:{(boolean)})
convertToPigSchema(
new Schema(StructType.of(required(1, "a", ListType.ofRequired(2, BooleanType.get()))).fields()),
"a:{(boolean)}",
"boolean (or anything non-tuple) element inside a bag should be wrapped inside a tuple"
);
}
private static void convertToPigSchema(Schema icebergSchema, String expectedPigSchema, String assertMessage) throws IOException {
ResourceSchema pigSchema = SchemaUtil.convert(icebergSchema);
assertEquals(assertMessage, expectedPigSchema, pigSchema.toString());
}
} | 1,897 |
0 | Create_ds/iceberg/pig/src/main/java/com/netflix/iceberg | Create_ds/iceberg/pig/src/main/java/com/netflix/iceberg/pig/PigParquetReader.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed 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 com.netflix.iceberg.pig;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netflix.iceberg.Schema;
import com.netflix.iceberg.parquet.ParquetValueReader;
import com.netflix.iceberg.parquet.ParquetValueReaders;
import com.netflix.iceberg.parquet.ParquetValueReaders.BinaryAsDecimalReader;
import com.netflix.iceberg.parquet.ParquetValueReaders.FloatAsDoubleReader;
import com.netflix.iceberg.parquet.ParquetValueReaders.IntAsLongReader;
import com.netflix.iceberg.parquet.ParquetValueReaders.IntegerAsDecimalReader;
import com.netflix.iceberg.parquet.ParquetValueReaders.LongAsDecimalReader;
import com.netflix.iceberg.parquet.ParquetValueReaders.PrimitiveReader;
import com.netflix.iceberg.parquet.ParquetValueReaders.RepeatedKeyValueReader;
import com.netflix.iceberg.parquet.ParquetValueReaders.RepeatedReader;
import com.netflix.iceberg.parquet.ParquetValueReaders.ReusableEntry;
import com.netflix.iceberg.parquet.ParquetValueReaders.StringReader;
import com.netflix.iceberg.parquet.ParquetValueReaders.StructReader;
import com.netflix.iceberg.parquet.ParquetValueReaders.UnboxedReader;
import com.netflix.iceberg.parquet.TypeWithSchemaVisitor;
import com.netflix.iceberg.types.Type.TypeID;
import com.netflix.iceberg.types.Types;
import org.apache.parquet.column.ColumnDescriptor;
import org.apache.parquet.schema.DecimalMetadata;
import org.apache.parquet.schema.GroupType;
import org.apache.parquet.schema.MessageType;
import org.apache.parquet.schema.PrimitiveType;
import org.apache.parquet.schema.Type;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.BagFactory;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.netflix.iceberg.parquet.ParquetSchemaUtil.convert;
import static com.netflix.iceberg.parquet.ParquetSchemaUtil.hasIds;
import static com.netflix.iceberg.parquet.ParquetValueReaders.option;
import static java.lang.String.format;
public class PigParquetReader {
private final ParquetValueReader reader;
public PigParquetReader(Schema readSchema, MessageType fileSchema, Map<Integer, Object> partitionValues) {
this.reader = buildReader(convert(readSchema, fileSchema.getName()), readSchema, partitionValues);
}
@SuppressWarnings("unchecked")
public static ParquetValueReader<Tuple> buildReader(MessageType fileSchema, Schema expectedSchema, Map<Integer, Object> partitionValues) {
if (hasIds(fileSchema)) {
return (ParquetValueReader<Tuple>)
TypeWithSchemaVisitor.visit(expectedSchema.asStruct(), fileSchema,
new ReadBuilder(fileSchema, partitionValues));
} else {
return (ParquetValueReader<Tuple>)
TypeWithSchemaVisitor.visit(expectedSchema.asStruct(), fileSchema,
new FallbackReadBuilder(fileSchema, partitionValues));
}
}
private static class FallbackReadBuilder extends ReadBuilder {
FallbackReadBuilder(MessageType type, Map<Integer, Object> partitionValues) {
super(type, partitionValues);
}
@Override
public ParquetValueReader<?> message(Types.StructType expected, MessageType message, List<ParquetValueReader<?>> fieldReaders) {
// the top level matches by ID, but the remaining IDs are missing
return super.struct(expected, message, fieldReaders);
}
@Override
public ParquetValueReader<?> struct(Types.StructType ignored, GroupType struct, List<ParquetValueReader<?>> fieldReaders) {
// the expected struct is ignored because nested fields are never found when the
List<ParquetValueReader<?>> newFields = Lists.newArrayListWithExpectedSize(
fieldReaders.size());
List<Type> types = Lists.newArrayListWithExpectedSize(fieldReaders.size());
List<Type> fields = struct.getFields();
for (int i = 0; i < fields.size(); i += 1) {
Type fieldType = fields.get(i);
int fieldD = type.getMaxDefinitionLevel(path(fieldType.getName())) - 1;
newFields.add(option(fieldType, fieldD, fieldReaders.get(i)));
types.add(fieldType);
}
return new TupleReader(types, newFields, partitionValues);
}
}
private static class ReadBuilder extends TypeWithSchemaVisitor<ParquetValueReader<?>> {
final MessageType type;
final Map<Integer, Object> partitionValues;
ReadBuilder(MessageType type, Map<Integer, Object> partitionValues) {
this.type = type;
this.partitionValues = partitionValues;
}
@Override
public ParquetValueReader<?> message(Types.StructType expected, MessageType message, List<ParquetValueReader<?>> fieldReaders) {
return struct(expected, message.asGroupType(), fieldReaders);
}
@Override
public ParquetValueReader<?> struct(Types.StructType expected, GroupType struct, List<ParquetValueReader<?>> fieldReaders) {
// match the expected struct's order
Map<Integer, ParquetValueReader<?>> readersById = Maps.newHashMap();
Map<Integer, Type> typesById = Maps.newHashMap();
List<Type> fields = struct.getFields();
for (int i = 0; i < fields.size(); i += 1) {
Type fieldType = fields.get(i);
int fieldD = type.getMaxDefinitionLevel(path(fieldType.getName())) - 1;
int id = fieldType.getId().intValue();
readersById.put(id, option(fieldType, fieldD, fieldReaders.get(i)));
typesById.put(id, fieldType);
}
List<Types.NestedField> expectedFields = expected != null ?
expected.fields() : ImmutableList.of();
List<ParquetValueReader<?>> reorderedFields = Lists.newArrayListWithExpectedSize(
expectedFields.size());
List<Type> types = Lists.newArrayListWithExpectedSize(expectedFields.size());
for (Types.NestedField field : expectedFields) {
int id = field.fieldId();
ParquetValueReader<?> reader = readersById.get(id);
if (reader != null) {
reorderedFields.add(reader);
types.add(typesById.get(id));
} else {
reorderedFields.add(ParquetValueReaders.nulls());
types.add(null);
}
}
return new TupleReader(types, reorderedFields, partitionValues);
}
@Override
public ParquetValueReader<?> list(Types.ListType expectedList, GroupType array, ParquetValueReader<?> elementReader) {
GroupType repeated = array.getFields().get(0).asGroupType();
String[] repeatedPath = currentPath();
int repeatedD = type.getMaxDefinitionLevel(repeatedPath) - 1;
int repeatedR = type.getMaxRepetitionLevel(repeatedPath) - 1;
Type elementType = repeated.getType(0);
int elementD = type.getMaxDefinitionLevel(path(elementType.getName())) - 1;
return new ArrayReader<>(repeatedD, repeatedR, option(elementType, elementD, elementReader));
}
@Override
public ParquetValueReader<?> map(Types.MapType expectedMap, GroupType map, ParquetValueReader<?> keyReader, ParquetValueReader<?> valueReader) {
GroupType repeatedKeyValue = map.getFields().get(0).asGroupType();
String[] repeatedPath = currentPath();
int repeatedD = type.getMaxDefinitionLevel(repeatedPath) - 1;
int repeatedR = type.getMaxRepetitionLevel(repeatedPath) - 1;
Type keyType = repeatedKeyValue.getType(0);
int keyD = type.getMaxDefinitionLevel(path(keyType.getName())) - 1;
Type valueType = repeatedKeyValue.getType(1);
int valueD = type.getMaxDefinitionLevel(path(valueType.getName())) - 1;
return new MapReader<>(repeatedD, repeatedR,
option(keyType, keyD, keyReader), option(valueType, valueD, valueReader));
}
@Override
public ParquetValueReader<?> primitive(com.netflix.iceberg.types.Type.PrimitiveType expected, PrimitiveType primitive) {
ColumnDescriptor desc = type.getColumnDescription(currentPath());
if (primitive.getOriginalType() != null) {
switch (primitive.getOriginalType()) {
case ENUM:
case JSON:
case UTF8: return new StringReader(desc);
case DATE: return new DateReader(desc);
case INT_8:
case INT_16:
case INT_32:
if (expected != null && expected.typeId() == Types.LongType.get().typeId()) {
return new IntAsLongReader(desc);
} else {
return new UnboxedReader(desc);
}
case INT_64: return new UnboxedReader<>(desc);
case TIMESTAMP_MILLIS: return new TimestampMillisReader(desc);
case TIMESTAMP_MICROS: return new TimestampMicrosReader(desc);
case DECIMAL:
DecimalMetadata decimal = primitive.getDecimalMetadata();
switch (primitive.getPrimitiveTypeName()) {
case BINARY:
case FIXED_LEN_BYTE_ARRAY: return new BinaryAsDecimalReader(desc, decimal.getScale());
case INT32: return new IntegerAsDecimalReader(desc, decimal.getScale());
case INT64: return new LongAsDecimalReader(desc, decimal.getScale());
default:
throw new UnsupportedOperationException(
"Unsupported base type for decimal: " + primitive.getPrimitiveTypeName());
}
default:
throw new UnsupportedOperationException("Unsupported type: " + primitive.getOriginalType());
}
}
switch (primitive.getPrimitiveTypeName()) {
case FIXED_LEN_BYTE_ARRAY:
case BINARY:
return new BytesReader(desc);
case INT32:
if (expected != null && expected.typeId() == TypeID.LONG) {
return new IntAsLongReader(desc);
} else {
return new UnboxedReader<>(desc);
}
case FLOAT:
if (expected != null && expected.typeId() == TypeID.DOUBLE) {
return new FloatAsDoubleReader(desc);
} else {
return new UnboxedReader<>(desc);
}
case BOOLEAN:
case INT64:
case DOUBLE:
return new UnboxedReader<>(desc);
default:
throw new UnsupportedOperationException("Unsupported type: " + primitive);
}
}
private String[] currentPath() {
String[] path = new String[fieldNames.size()];
if (!fieldNames.isEmpty()) {
Iterator<String> iter = fieldNames.descendingIterator();
for (int i = 0; iter.hasNext(); i += 1) {
path[i] = iter.next();
}
}
return path;
}
protected String[] path(String name) {
String[] path = new String[fieldNames.size() + 1];
path[fieldNames.size()] = name;
if (!fieldNames.isEmpty()) {
Iterator<String> iter = fieldNames.descendingIterator();
for (int i = 0; iter.hasNext(); i += 1) {
path[i] = iter.next();
}
}
return path;
}
}
private static class DateReader extends PrimitiveReader<String> {
private static final OffsetDateTime EPOCH = Instant.ofEpochSecond(0).atOffset(ZoneOffset.UTC);
DateReader(ColumnDescriptor desc) {
super(desc);
}
@Override
public String read(String reuse) {
OffsetDateTime day = EPOCH.plusDays(column.nextInteger());
return format("%04d-%02d-%02d", day.getYear(), day.getMonth().getValue(), day.getDayOfMonth());
}
}
private static class BytesReader extends PrimitiveReader<DataByteArray> {
BytesReader(ColumnDescriptor desc) {
super(desc);
}
@Override
public DataByteArray read(DataByteArray reuse) {
byte[] bytes = column.nextBinary().getBytes();
return new DataByteArray(bytes);
}
}
private static class TimestampMicrosReader extends UnboxedReader<String> {
private static final OffsetDateTime EPOCH = Instant.ofEpochSecond(0).atOffset(ZoneOffset.UTC);
TimestampMicrosReader(ColumnDescriptor desc) {
super(desc);
}
@Override
public String read(String ignored) {
return ChronoUnit.MICROS.addTo(EPOCH, column.nextLong()).toString();
}
}
private static class TimestampMillisReader extends UnboxedReader<String> {
private static final OffsetDateTime EPOCH = Instant.ofEpochSecond(0).atOffset(ZoneOffset.UTC);
TimestampMillisReader(ColumnDescriptor desc) {
super(desc);
}
@Override
public String read(String ignored) {
return ChronoUnit.MILLIS.addTo(EPOCH, column.nextLong()).toString();
}
}
private static class MapReader<K, V> extends RepeatedKeyValueReader<Map<K, V>, Map<K, V>, K, V> {
ReusableEntry<K, V> nullEntry = new ReusableEntry<>();
MapReader(int definitionLevel, int repetitionLevel,
ParquetValueReader<K> keyReader, ParquetValueReader<V> valueReader) {
super(definitionLevel, repetitionLevel, keyReader, valueReader);
}
@Override
protected Map<K, V> newMapData(Map<K, V> reuse) {
return new LinkedHashMap<>();
}
@Override
protected Map.Entry<K, V> getPair(Map<K, V> reuse) {
return nullEntry;
}
@Override
protected void addPair(Map<K, V> map, K key, V value) {
map.put(key, value);
}
@Override
protected Map<K, V> buildMap(Map<K, V> map) {
return map;
}
}
private static class ArrayReader<T> extends RepeatedReader<DataBag, DataBag, T> {
private final BagFactory BF = BagFactory.getInstance();
private final TupleFactory TF = TupleFactory.getInstance();
ArrayReader(int definitionLevel, int repetitionLevel, ParquetValueReader<T> reader) {
super(definitionLevel, repetitionLevel, reader);
}
@Override
protected DataBag newListData(DataBag reuse) {
return BF.newDefaultBag();
}
@Override
protected T getElement(DataBag list) {
return null;
}
@Override
protected void addElement(DataBag bag, T element) {
bag.add(TF.newTuple(element));
}
@Override
protected DataBag buildList(DataBag bag) {
return bag;
}
}
private static class TupleReader extends StructReader<Tuple, Tuple> {
private static final TupleFactory TF = TupleFactory.getInstance();
private final Map<Integer, Object> partitionValues;
private final int columns;
protected TupleReader(List<Type> types, List<ParquetValueReader<?>> readers, Map<Integer, Object> partitionValues) {
super(types, readers);
this.partitionValues = partitionValues;
this.columns = types.size() + partitionValues.size();
}
@Override
protected Tuple newStructData(Tuple reuse) {
return TF.newTuple(columns);
}
@Override
protected Object getField(Tuple tuple, int pos) {
return null;
}
@Override
protected Tuple buildStruct(Tuple tuple) {
for (Map.Entry<Integer, Object> e : partitionValues.entrySet()) {
try {
tuple.set(e.getKey(), e.getValue());
} catch (ExecException ex) {
throw new RuntimeException("Error setting value for key" + e.getKey(), ex);
}
}
return tuple;
}
@Override
protected void set(Tuple tuple, int pos, Object value) {
try {
tuple.set(pos, value);
} catch (ExecException e) {
throw new RuntimeException(format("Error setting tuple value for pos: %d, value: %s", pos, value), e);
}
}
}
}
| 1,898 |
0 | Create_ds/iceberg/pig/src/main/java/com/netflix/iceberg | Create_ds/iceberg/pig/src/main/java/com/netflix/iceberg/pig/IcebergStorage.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed 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 com.netflix.iceberg.pig;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netflix.iceberg.Schema;
import com.netflix.iceberg.Table;
import com.netflix.iceberg.expressions.Expressions;
import com.netflix.iceberg.types.Types;
import org.apache.hadoop.fs.Path;
import org.apache.pig.impl.util.ObjectSerializer;
import org.apache.pig.impl.util.UDFContext;
import org.mortbay.log.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.iceberg.Tables;
import com.netflix.iceberg.hadoop.HadoopTables;
import com.netflix.iceberg.pig.IcebergPigInputFormat.IcebergRecordReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.pig.Expression;
import org.apache.pig.Expression.*;
import org.apache.pig.LoadFunc;
import org.apache.pig.LoadMetadata;
import org.apache.pig.LoadPredicatePushdown;
import org.apache.pig.LoadPushDown;
import org.apache.pig.ResourceSchema;
import org.apache.pig.ResourceStatistics;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.FrontendException;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static com.netflix.iceberg.expressions.Expressions.and;
import static com.netflix.iceberg.expressions.Expressions.equal;
import static com.netflix.iceberg.expressions.Expressions.greaterThan;
import static com.netflix.iceberg.expressions.Expressions.greaterThanOrEqual;
import static com.netflix.iceberg.expressions.Expressions.isNull;
import static com.netflix.iceberg.expressions.Expressions.lessThan;
import static com.netflix.iceberg.expressions.Expressions.lessThanOrEqual;
import static com.netflix.iceberg.expressions.Expressions.not;
import static com.netflix.iceberg.expressions.Expressions.notEqual;
import static com.netflix.iceberg.expressions.Expressions.or;
import static com.netflix.iceberg.pig.IcebergPigInputFormat.ICEBERG_FILTER_EXPRESSION;
import static com.netflix.iceberg.pig.IcebergPigInputFormat.ICEBERG_PROJECTED_FIELDS;
import static com.netflix.iceberg.pig.IcebergPigInputFormat.ICEBERG_SCHEMA;
import static org.apache.pig.Expression.OpType.OP_AND;
import static org.apache.pig.Expression.OpType.OP_BETWEEN;
import static org.apache.pig.Expression.OpType.OP_EQ;
import static org.apache.pig.Expression.OpType.OP_GE;
import static org.apache.pig.Expression.OpType.OP_GT;
import static org.apache.pig.Expression.OpType.OP_IN;
import static org.apache.pig.Expression.OpType.OP_LE;
import static org.apache.pig.Expression.OpType.OP_LT;
import static org.apache.pig.Expression.OpType.OP_NE;
import static org.apache.pig.Expression.OpType.OP_NOT;
import static org.apache.pig.Expression.OpType.OP_NULL;
import static org.apache.pig.Expression.OpType.OP_OR;
public class IcebergStorage extends LoadFunc implements LoadMetadata, LoadPredicatePushdown, LoadPushDown {
private static final Logger LOG = LoggerFactory.getLogger(IcebergStorage.class);
public static final String PIG_ICEBERG_TABLES_IMPL = "pig.iceberg.tables.impl";
private static Tables iceberg;
private static Map<String, Table> tables = Maps.newConcurrentMap();
private static Map<String, String> locations = Maps.newConcurrentMap();
private String signature;
private IcebergRecordReader reader;
@Override
public void setLocation(String location, Job job) {
LOG.info(format("[%s]: setLocation() -> %s ", signature, location));
locations.put(signature, location);
Configuration conf = job.getConfiguration();
copyUDFContextToConfiguration(conf, ICEBERG_SCHEMA);
copyUDFContextToConfiguration(conf, ICEBERG_PROJECTED_FIELDS);
copyUDFContextToConfiguration(conf, ICEBERG_FILTER_EXPRESSION);
}
@Override
public InputFormat getInputFormat() {
LOG.info(format("[%s]: getInputFormat()", signature));
String location = locations.get(signature);
return new IcebergPigInputFormat(tables.get(location));
}
@Override
public Tuple getNext() throws IOException {
if (!reader.nextKeyValue()) {
return null;
}
return (Tuple) reader.getCurrentValue();
}
@Override
public void prepareToRead(RecordReader reader, PigSplit split) {
LOG.info(format("[%s]: prepareToRead() -> %s", signature, split));
this.reader = (IcebergRecordReader) reader;
}
@Override
public ResourceSchema getSchema(String location, Job job) throws IOException {
LOG.info(format("[%s]: getSchema() -> %s", signature, location));
Schema schema = load(location, job).schema();
storeInUDFContext(ICEBERG_SCHEMA, schema);
return SchemaUtil.convert(schema);
}
@Override
public ResourceStatistics getStatistics(String location, Job job) {
LOG.info(format("[%s]: getStatistics() -> : %s", signature, location));
return null;
}
@Override
public String[] getPartitionKeys(String location, Job job) {
LOG.info(format("[%s]: getPartitionKeys()", signature));
return new String[0];
}
@Override
public void setPartitionFilter(Expression partitionFilter) {
LOG.info(format("[%s]: setPartitionFilter() -> %s", signature, partitionFilter));
}
@Override
public List<String> getPredicateFields(String location, Job job) throws IOException {
LOG.info(format("[%s]: getPredicateFields() -> %s", signature, location));
Schema schema = load(location, job).schema();
List<String> result = Lists.newArrayList();
for (Types.NestedField nf : schema.columns()) {
switch (nf.type().typeId()) {
case MAP:
case LIST:
case STRUCT:
continue;
default:
result.add(nf.name());
}
}
return result;
}
@Override
public List<Expression.OpType> getSupportedExpressionTypes() {
LOG.info(format("[%s]: getSupportedExpressionTypes()", signature));
return asList(OP_AND, OP_OR, OP_EQ, OP_NE, OP_NOT, OP_GE, OP_GT, OP_LE, OP_LT, OP_BETWEEN, OP_IN, OP_NULL);
}
@Override
public void setPushdownPredicate(Expression predicate) throws IOException {
LOG.info(format("[%s]: setPushdownPredicate()", signature));
LOG.info(format("[%s]: Pig predicate expression: %s", signature, predicate));
com.netflix.iceberg.expressions.Expression icebergExpression = convert(predicate);
LOG.info(format("[%s]: Iceberg predicate expression: %s", signature, icebergExpression));
storeInUDFContext(ICEBERG_FILTER_EXPRESSION, icebergExpression);
}
private com.netflix.iceberg.expressions.Expression convert(Expression e) throws IOException {
OpType op = e.getOpType();
if (e instanceof BinaryExpression) {
Expression lhs = ((BinaryExpression) e).getLhs();
Expression rhs = ((BinaryExpression) e).getRhs();
switch (op) {
case OP_AND:
return and(convert(lhs), convert(rhs));
case OP_OR:
return or(convert(lhs), convert(rhs));
case OP_BETWEEN:
BetweenExpression between = (BetweenExpression) rhs;
return and(
convert(OP_GE, (Column) lhs, (Const) between.getLower()),
convert(OP_LE, (Column) lhs, (Const) between.getUpper())
);
case OP_IN:
return ((InExpression) rhs).getValues().stream()
.map((value) -> convert(OP_EQ, (Column) lhs, (Const) value))
.reduce(Expressions.alwaysFalse(), (m, v) -> (or(m, v)));
default:
if (lhs instanceof Column && rhs instanceof Const) {
return convert(op, (Column) lhs, (Const) rhs);
} else if (lhs instanceof Const && rhs instanceof Column) {
throw new FrontendException("Invalid expression ordering " + e);
}
}
} else if (e instanceof UnaryExpression) {
Expression unary = ((UnaryExpression) e).getExpression();
switch (op) {
case OP_NOT: return not(convert(unary));
case OP_NULL: return isNull(((Column)unary).getName());
default:
throw new FrontendException("Unsupported unary operator" + op);
}
}
throw new FrontendException("Failed to pushdown expression " + e);
}
private com.netflix.iceberg.expressions.Expression convert(OpType op, Column col, Const constant) {
String name = col.getName();
Object value = constant.getValue();
switch (op) {
case OP_GE: return greaterThanOrEqual(name, value);
case OP_GT: return greaterThan(name, value);
case OP_LE: return lessThanOrEqual(name, value);
case OP_LT: return lessThan(name, value);
case OP_EQ: return equal(name, value);
case OP_NE: return notEqual(name, value);
}
throw new RuntimeException(format("[%s]: Failed to pushdown expression: %s %s %s", signature, col, op, constant));
}
@Override
public List<OperatorSet> getFeatures() {
return Collections.singletonList(OperatorSet.PROJECTION);
}
@Override
public RequiredFieldResponse pushProjection(RequiredFieldList requiredFieldList) {
LOG.info(format("[%s]: pushProjection() -> %s", signature, requiredFieldList));
try {
List<String> projection = requiredFieldList.getFields().stream().map(RequiredField::getAlias).collect(Collectors.toList());
storeInUDFContext(ICEBERG_PROJECTED_FIELDS, (Serializable) projection);
} catch (IOException e) {
throw new RuntimeException(e);
}
return new RequiredFieldResponse(true);
}
@Override
public void setUDFContextSignature(String signature) {
this.signature = signature;
}
private void storeInUDFContext(String key, Serializable value) throws IOException {
Properties properties = UDFContext.getUDFContext().getUDFProperties(this.getClass(), new String[]{signature});
properties.setProperty(key, ObjectSerializer.serialize(value));
}
private void copyUDFContextToConfiguration(Configuration conf, String key) {
String value = UDFContext.getUDFContext().getUDFProperties(this.getClass(), new String[]{signature}).getProperty(key);
if (value != null) {
conf.set(key, value);
}
}
@Override
public String relativeToAbsolutePath(String location, Path curDir) throws IOException {
return location;
}
@SuppressWarnings("unchecked")
public <T extends Serializable> T getFromUDFContext(String key, Class<T> clazz) throws IOException {
Properties properties = UDFContext.getUDFContext().getUDFProperties(this.getClass(), new String[]{signature});
return (T) ObjectSerializer.deserialize(properties.getProperty(key));
}
private Table load(String location, Job job) throws IOException {
if(iceberg == null) {
Class<?> tablesImpl = job.getConfiguration().getClass(PIG_ICEBERG_TABLES_IMPL, HadoopTables.class);
Log.info("Initializing iceberg tables implementation: " + tablesImpl);
iceberg = (Tables) ReflectionUtils.newInstance(tablesImpl, job.getConfiguration());
}
Table result = tables.get(location);
if (result == null) {
try {
LOG.info(format("[%s]: Loading table for location: %s", signature, location));
result = iceberg.load(location);
tables.put(location, result);
} catch (Exception e) {
throw new FrontendException("Failed to instantiate tables implementation", e);
}
}
return result;
}
}
| 1,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.