Skip to content

Commit

Permalink
Test AWS 2 SNS properly
Browse files Browse the repository at this point in the history
  • Loading branch information
ppalaga committed Feb 9, 2021
1 parent af400d3 commit 073835c
Show file tree
Hide file tree
Showing 13 changed files with 256 additions and 124 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ protected void setMockProperties(final Map<String, String> result) {

switch (service) {
case SQS:
case SNS:
// TODO https://github.com/apache/camel-quarkus/issues/2216
break;
default:
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
<relativePath>../pom.xml</relativePath>
</parent>

<artifactId>camel-quarkus-integration-test-aws2-sqs</artifactId>
<name>Camel Quarkus :: Integration Tests :: AWS 2 Simple Queue Service (SQS)</name>
<description>Integration tests for Camel Quarkus AWS 2 Simple Queue Service (SQS) extension</description>
<artifactId>camel-quarkus-integration-test-aws2-sqs-sns</artifactId>
<name>Camel Quarkus :: Integration Tests :: AWS 2 SQS and SNS</name>
<description>Integration tests for SQS and SNS extensions</description>

<dependencyManagement>
<dependencies>
Expand All @@ -49,6 +49,10 @@
<groupId>org.apache.camel.quarkus</groupId>
<artifactId>camel-quarkus-main</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.quarkus</groupId>
<artifactId>camel-quarkus-aws2-sns</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.quarkus</groupId>
<artifactId>camel-quarkus-aws2-sqs</artifactId>
Expand Down Expand Up @@ -84,6 +88,21 @@
<scope>test</scope>
</dependency>

<!-- The following dependencies guarantee that this module is built after them. You can update them by running `mvn process-resources -Pformat -N` from the source tree root directory -->
<dependency>
<groupId>org.apache.camel.quarkus</groupId>
<artifactId>camel-quarkus-aws2-sns-deployment</artifactId>
<version>${project.version}</version>
<type>pom</type>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>

<!-- The following dependencies guarantee that this module is built after them. You can update them by running `mvn process-resources -Pformat -N` from the source tree root directory -->
<dependency>
<groupId>org.apache.camel.quarkus</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

Expand All @@ -34,39 +35,48 @@
import org.eclipse.microprofile.config.inject.ConfigProperty;
import software.amazon.awssdk.services.sqs.model.ListQueuesResponse;

@Path("/aws2-sqs")
@Path("/aws2-sqs-sns")
@ApplicationScoped
public class Aws2SqsResource {

@ConfigProperty(name = "aws-sqs.queue-name")
String queueName;

@ConfigProperty(name = "aws-sqs.sns-receiver-queue-name")
String snsReceiverQueueName;

@ConfigProperty(name = "aws2-sqs.sns-receiver-queue-arn")
String snsReceiverQueueArn;

@ConfigProperty(name = "aws-sns.topic-name")
String topicName;

@Inject
ProducerTemplate producerTemplate;

@Inject
ConsumerTemplate consumerTemplate;

@Path("/send")
@Path("/sqs/send")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response send(String message) throws Exception {
public Response sqsSend(String message) throws Exception {
final String response = producerTemplate.requestBody(componentUri(), message, String.class);
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response)
.build();
}

@Path("/receive")
@Path("/sqs/receive")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String receive() throws Exception {
@Produces(MediaType.TEXT_PLAIN)
public String sqsReceive() throws Exception {
return consumerTemplate.receiveBody(componentUri(), 10000, String.class);
}

@Path("/queues")
@Path("/sqs/queues")
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<String> listQueues() throws Exception {
Expand All @@ -78,4 +88,26 @@ private String componentUri() {
return "aws2-sqs://" + queueName;
}

@Path("/sns/send")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response snsSend(String message, @QueryParam("queueUrl") String queueUrl) throws Exception {

final String response = producerTemplate.requestBody(
"aws2-sns://" + topicName + "?subscribeSNStoSQS=true&queueUrl=RAW(" + snsReceiverQueueArn + ")", message,
String.class);
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response)
.build();
}

@Path("/sns/receiveViaSqs")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String sqsReceiveViaSqs() throws Exception {
return consumerTemplate.receiveBody("aws2-sqs://" + snsReceiverQueueName, 10000, String.class);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
## limitations under the License.
## ---------------------------------------------------------------------------

camel.component.aws2-sns.access-key=${AWS_ACCESS_KEY}
camel.component.aws2-sns.secret-key=${AWS_SECRET_KEY}
camel.component.aws2-sns.region=${AWS_REGION:us-east-1}

camel.component.aws2-sqs.access-key=${AWS_ACCESS_KEY}
camel.component.aws2-sqs.secret-key=${AWS_SECRET_KEY}
camel.component.aws2-sqs.region=${AWS_REGION:us-east-1}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/
package org.apache.camel.quarkus.component.aws2.sqs.it;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

Expand All @@ -31,36 +32,56 @@
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;

import static org.hamcrest.core.Is.is;

@QuarkusTest
@QuarkusTestResource(Aws2SqsTestResource.class)
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY", matches = "[a-zA-Z0-9]+") // TODO
// https://github.com/apache/camel-quarkus/issues/2216
class Aws2SqsTest {

@Test
public void sendReceive() {
public void sqs() {
final Config config = ConfigProvider.getConfig();
final String queueName = config.getValue("aws-sqs.queue-name", String.class);

String[] queues = RestAssured.get("/aws2-sqs/queues")
String[] queues = RestAssured.get("/aws2-sqs-sns/sqs/queues")
.then()
.statusCode(200)
.extract()
.body().as(String[].class);
Assertions.assertTrue(Stream.of(queues).anyMatch(url -> url.contains(queueName)));

final String msg = java.util.UUID.randomUUID().toString().replace("-", "");
RestAssured.given() //
final String msg = "sqs" + UUID.randomUUID().toString().replace("-", "");
RestAssured.given()
.contentType(ContentType.TEXT)
.body(msg)
.post("/aws2-sqs/send") //
.post("/aws2-sqs-sns/sqs/send")
.then()
.statusCode(201);

Awaitility.await().pollInterval(1, TimeUnit.SECONDS).atMost(120, TimeUnit.SECONDS).until(
() -> RestAssured.get("/aws2-sqs/receive").then().statusCode(200).extract().body().asString(),
() -> RestAssured.get("/aws2-sqs-sns/sqs/receive").then().statusCode(200).extract().body().asString(),
Matchers.is(msg));

}

@Test
void sns() {
final String snsMsg = "sns" + UUID.randomUUID().toString().replace("-", "");
RestAssured.given()
.contentType(ContentType.TEXT)
.body(snsMsg)
.post("/aws2-sqs-sns/sns/send")
.then()
.statusCode(201);

RestAssured
.get("/aws2-sqs-sns/sns/receiveViaSqs")
.then()
.statusCode(200)
.body("Message", is(snsMsg));

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
* 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.quarkus.component.aws2.sqs.it;

import java.util.Collections;
import java.util.Locale;
import java.util.Map;

import org.apache.camel.quarkus.test.support.aws2.Aws2TestResource;
import org.apache.commons.lang3.RandomStringUtils;
import org.testcontainers.containers.localstack.LocalStackContainer;
import org.testcontainers.containers.localstack.LocalStackContainer.Service;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.SnsClientBuilder;
import software.amazon.awssdk.services.sns.model.CreateTopicRequest;
import software.amazon.awssdk.services.sns.model.DeleteTopicRequest;
import software.amazon.awssdk.services.sns.model.ListSubscriptionsByTopicRequest;
import software.amazon.awssdk.services.sns.model.Subscription;
import software.amazon.awssdk.services.sns.model.UnsubscribeRequest;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.SqsClientBuilder;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest;
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest;

public class Aws2SqsTestResource extends Aws2TestResource {

public Aws2SqsTestResource() {
super(Service.SQS, Service.SNS);
}

@Override
public Map<String, String> start() {
Map<String, String> result = super.start();

/* SQS */
final String queueName = "camel-quarkus-" + RandomStringUtils.randomAlphanumeric(49).toLowerCase(Locale.ROOT);
result.put("aws-sqs.queue-name", queueName);

final SqsClientBuilder clientBuilder = SqsClient
.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)))
.region(Region.of(region));
if (usingMockBackend) {
clientBuilder.endpointOverride(localstack.getEndpointOverride(LocalStackContainer.Service.SQS));
}
final SqsClient sqsClient = clientBuilder.build();
{
final String queueUrl = sqsClient.createQueue(
CreateQueueRequest.builder()
.queueName(queueName)
.build())
.queueUrl();
closeables.add(() -> {
sqsClient.deleteQueue(DeleteQueueRequest.builder().queueUrl(queueUrl).build());
sqsClient.close();
});
}

/* SNS */
{
final String topicName = "camel-quarkus-" + RandomStringUtils.randomAlphanumeric(49).toLowerCase(Locale.ROOT);
result.put("aws-sns.topic-name", topicName);

final SnsClientBuilder snsClientBuilder = SnsClient
.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)))
.region(Region.of(region));
if (usingMockBackend) {
snsClientBuilder.endpointOverride(localstack.getEndpointOverride(LocalStackContainer.Service.SQS));
}
final SnsClient snsClient = snsClientBuilder.build();

final String topicArn = snsClient.createTopic(CreateTopicRequest.builder().name(topicName).build()).topicArn();

closeables.add(() -> {
snsClient.listSubscriptionsByTopic(ListSubscriptionsByTopicRequest.builder().topicArn(topicArn).build())
.subscriptions()
.stream()
.map(Subscription::subscriptionArn)
.forEach(arn -> snsClient.unsubscribe(UnsubscribeRequest.builder().subscriptionArn(arn).build()));
snsClient.deleteTopic(DeleteTopicRequest.builder().topicArn(topicArn).build());
snsClient.close();
});

final String snsReceiverQueueName = "camel-quarkus-sns-receiver-"
+ RandomStringUtils.randomAlphanumeric(30).toLowerCase(Locale.ROOT);
result.put("aws-sqs.sns-receiver-queue-name", snsReceiverQueueName);
final String snsReceiverQueueUrl = sqsClient.createQueue(
CreateQueueRequest.builder()
.queueName(snsReceiverQueueName)
.build())
.queueUrl();
result.put("aws2-sqs.sns-receiver-queue-url", snsReceiverQueueUrl);

/*
* We need queue ARN instead of queue URL when creating a subscription of an SQS Queue to an SNS Topic
* See https://stackoverflow.com/a/59255978
*/
final String snsReceiverQueueArn = sqsClient.getQueueAttributes(
GetQueueAttributesRequest.builder()
.queueUrl(snsReceiverQueueUrl)
.attributeNamesWithStrings("All")
.build())
.attributesAsStrings()
.get("QueueArn");
result.put("aws2-sqs.sns-receiver-queue-arn", snsReceiverQueueArn);

final String policy = "{"
+ " \"Version\": \"2008-10-17\","
+ " \"Id\": \"policy-" + snsReceiverQueueName + "\","
+ " \"Statement\": ["
+ " {"
+ " \"Sid\": \"sid-" + snsReceiverQueueName + "\","
+ " \"Effect\": \"Allow\","
+ " \"Principal\": {"
+ " \"AWS\": \"*\""
+ " },"
+ " \"Action\": \"SQS:*\","
+ " \"Resource\": \"" + snsReceiverQueueArn + "\""
+ " }"
+ " ]"
+ "}";
sqsClient.setQueueAttributes(
SetQueueAttributesRequest.builder()
.queueUrl(snsReceiverQueueUrl)
.attributes(
Collections.singletonMap(
QueueAttributeName.POLICY,
policy))
.build());

closeables.add(() -> {
sqsClient.deleteQueue(DeleteQueueRequest.builder().queueUrl(snsReceiverQueueUrl).build());
});

}

return Collections.unmodifiableMap(result);
}

}

0 comments on commit 073835c

Please sign in to comment.