com.amazonaws.services.sqs.AmazonSQSClientBuilder Java Examples

The following examples show how to use com.amazonaws.services.sqs.AmazonSQSClientBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocalstackContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void sqsTestOverBridgeNetwork() {
    AmazonSQS sqs = AmazonSQSClientBuilder.standard()
        .withEndpointConfiguration(localstack.getEndpointConfiguration(SQS))
        .withCredentials(localstack.getDefaultCredentialsProvider())
        .build();

    CreateQueueResult queueResult = sqs.createQueue("baz");
    String fooQueueUrl = queueResult.getQueueUrl();
    assertThat("Created queue has external hostname URL", fooQueueUrl,
        containsString("http://" + DockerClientFactory.instance().dockerHostIpAddress() + ":" + localstack.getMappedPort(SQS.getPort())));

    sqs.sendMessage(fooQueueUrl, "test");
    final long messageCount = sqs.receiveMessage(fooQueueUrl).getMessages().stream()
        .filter(message -> message.getBody().equals("test"))
        .count();
    assertEquals("the sent message can be received", 1L, messageCount);
}
 
Example #2
Source File: VisibilityTimeout.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void changeMessageVisibilityMultiple(
        String queue_url, int timeout)
{
    AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient();

    List<ChangeMessageVisibilityBatchRequestEntry> entries =
        new ArrayList<ChangeMessageVisibilityBatchRequestEntry>();

    entries.add(new ChangeMessageVisibilityBatchRequestEntry(
                "unique_id_msg1",
                sqs.receiveMessage(queue_url)
                   .getMessages()
                   .get(0)
                   .getReceiptHandle())
            .withVisibilityTimeout(timeout));

    entries.add(new ChangeMessageVisibilityBatchRequestEntry(
                "unique_id_msg2",
                sqs.receiveMessage(queue_url)
                   .getMessages()
                   .get(0)
                   .getReceiptHandle())
            .withVisibilityTimeout(timeout + 200));

    sqs.changeMessageVisibilityBatch(queue_url, entries);
}
 
Example #3
Source File: SqsIOTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Override
protected void before() {
  sqsRestServer = SQSRestServerBuilder.start();

  String endpoint = "http://localhost:9324";
  String region = "elasticmq";
  String accessKey = "x";
  String secretKey = "x";

  client =
      AmazonSQSClientBuilder.standard()
          .withCredentials(
              new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
          .withEndpointConfiguration(
              new AwsClientBuilder.EndpointConfiguration(endpoint, region))
          .build();
  final CreateQueueResult queue = client.createQueue("test");
  queueUrl = queue.getQueueUrl();
}
 
Example #4
Source File: TagTest.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
@Test
public void testSqsTagsAreSameAsHerdEC2Stack() throws Exception {
    String sqsNamePrefix = INSTANCE_NAME;
    String herdStackNamePrefix = APP_STACK_NAME + "-MdlStack-";

    CloudFormationClient cloudFormationClient = new CloudFormationClient(APP_STACK_NAME);
    List<Tag> stackTags = cloudFormationClient.getStackByNamePrefix(herdStackNamePrefix).getTags();

    System.out.println("Listing all queues with prefix: " + sqsNamePrefix);
    AmazonSQS sqs = AmazonSQSClientBuilder.standard().withRegion(Regions.getCurrentRegion().getName())
        .withCredentials(new InstanceProfileCredentialsProvider(true)).build();
    List<String> queueUrls = sqs.listQueues(sqsNamePrefix).getQueueUrls();
    assertEquals(2, queueUrls.size(), "2 queues are expected");
    for (String queueUrl : queueUrls) {
        System.out.println("QueueUrl: " + queueUrl);
        Map<String, String> sqsTags = sqs.listQueueTags(queueUrl).getTags();

        LogVerification("Verify sqs tags are the same as herd stack");
        stackTags.forEach(tag -> {
            String key = tag.getKey();
            assertTrue(sqsTags.containsKey(key));
            assertEquals(tag.getValue(), sqsTags.get(key));
        });
    }
}
 
Example #5
Source File: IntegrationTest.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
protected AmazonSQS getBuddyPrincipalClient() {
    AWSCredentialsProvider credentialsProvider = getBuddyCredentials();
    AmazonSQS client = AmazonSQSClientBuilder.standard()
            .withRegion("us-west-2")
            .withCredentials(credentialsProvider)
            .build();

    // Assume that the principal is not able to send messages to arbitrary queues
    String queueUrl = sqs.createQueue(queueNamePrefix + "TestQueue").getQueueUrl();
    try {
        client.sendMessage(queueUrl, "Haxxors!!");
        assumeTrue("The buddy credentials should not authorize sending to arbitrary queues", false);
    } catch (AmazonSQSException e) {
        // Access Denied
        assumeThat(e.getStatusCode(), equalTo(403));
    } finally {
        sqs.deleteQueue(queueUrl);
    }

    return client;
}
 
Example #6
Source File: SqsClient.java    From kafka-connect-sqs with Apache License 2.0 6 votes vote down vote up
public SqsClient(Map<String, ?> configs) {
    log.warn(".ctor:configs={}", configs);
    AWSCredentialsProvider provider = null;
    try {
      provider = getCredentialsProvider(configs);
    } catch ( Exception e ) {
      log.error("Problem initializing provider", e);
    }
    final AmazonSQSClientBuilder builder = AmazonSQSClientBuilder.standard();
    builder.setCredentials(provider);

//    // If there's an AWS credentials profile and/or region configured in the
//    // environment we will use it.
//    final String profile = System.getenv(AWS_PROFILE);
//    final String region = System.getenv(AWS_REGION);
//    if (Facility.isNotNullNorEmpty(profile)) {
//      builder.setCredentials(provider);
//    }
//    if (Facility.isNotNullNorEmpty(region)) {
//      builder.setRegion(region);
//    }
//    log.info("AmazonSQS using profile={}, region={}", profile, region);

    client = builder.build();
  }
 
Example #7
Source File: SQSConnectionFactory.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
public SQSConnectionFactory(ProviderConfiguration providerConfiguration, final AmazonSQSClientBuilder clientBuilder) {
    if (providerConfiguration == null) {
        throw new IllegalArgumentException("Provider configuration cannot be null");
    }
    if (clientBuilder == null) {
        throw new IllegalArgumentException("AmazonSQS client builder cannot be null");
    }
    this.providerConfiguration = providerConfiguration;
    this.amazonSQSClientSupplier = new AmazonSQSClientSupplier() {
        @Override
        public AmazonSQS get() {
            return clientBuilder.build();
        }
    };
}
 
Example #8
Source File: AWSCloudTrailProcessingExecutor.java    From aws-cloudtrail-processing-library with Apache License 2.0 5 votes vote down vote up
private void buildSqsClient() {
    if (sqsClient == null) {
        sqsClient = AmazonSQSClientBuilder.standard()
                .withCredentials(config.getAwsCredentialsProvider())
                .withRegion(config.getSqsRegion())
                .build();
    }
}
 
Example #9
Source File: S3Config.java    From front50 with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty("spinnaker.s3.eventing.enabled")
public AmazonSQS awsSQSClient(
    AWSCredentialsProvider awsCredentialsProvider, S3MetadataStorageProperties s3Properties) {
  return AmazonSQSClientBuilder.standard()
      .withCredentials(awsCredentialsProvider)
      .withClientConfiguration(new ClientConfiguration())
      .withRegion(s3Properties.getRegion())
      .build();
}
 
Example #10
Source File: CloudtrailSQSClient.java    From graylog-plugin-aws with Apache License 2.0 5 votes vote down vote up
public CloudtrailSQSClient(Region region, String queueName, AWSAuthProvider authProvider, HttpUrl proxyUrl, ObjectMapper objectMapper) {
    AmazonSQSClientBuilder clientBuilder = AmazonSQSClientBuilder.standard().withRegion(region.getName()).withCredentials(authProvider);

    if (proxyUrl != null) {
        clientBuilder.withClientConfiguration(Proxy.forAWS(proxyUrl));
    }

    this.sqs = clientBuilder.build();

    this.queueName = queueName;
    this.objectMapper = objectMapper;
}
 
Example #11
Source File: SQSUtils.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
public static AmazonSQSClient createSQSClient() {
    BasicCredentialsProvider credentials = BasicCredentialsProvider.standard();
    AmazonSQSClient client = !credentials.isValid() ? null : (AmazonSQSClient)
            AmazonSQSClientBuilder.standard()
            .withCredentials(credentials)
            .withRegion("eu-west-1").build();
    return client;
}
 
Example #12
Source File: SQSConnectionFactoryTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void canCreateFactoryWithCustomBuilder() throws JMSException {
    AmazonSQSClientBuilder clientBuilder = AmazonSQSClientBuilder.standard().withRegion(Regions.US_EAST_1);
    SQSConnectionFactory factory = new SQSConnectionFactory(new ProviderConfiguration(), clientBuilder);
    SQSConnection connection = factory.createConnection();
    connection.close();
}
 
Example #13
Source File: AwsClientFactory.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a client for accessing Amazon SQS.
 *
 * @param awsParamsDto the AWS related parameters DTO that includes optional proxy information
 *
 * @return the Amazon SQS client
 */
@Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME)
public AmazonSQS getAmazonSQSClient(AwsParamsDto awsParamsDto)
{
    // Construct and return a new client to invoke service methods on Amazon SQS using default credentials provider chain.
    return AmazonSQSClientBuilder.standard().withClientConfiguration(awsHelper.getClientConfiguration(awsParamsDto))
        .withRegion(awsParamsDto.getAwsRegionName()).build();
}
 
Example #14
Source File: SQSConnectionFactoryTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void factoryWithCustomBuilderWillCreateNewClient() throws JMSException {
    AmazonSQSClientBuilder clientBuilder = AmazonSQSClientBuilder.standard().withRegion(Regions.US_EAST_1);
    SQSConnectionFactory factory = new SQSConnectionFactory(new ProviderConfiguration(), clientBuilder);
    SQSConnection connection1 = factory.createConnection();
    SQSConnection connection2 = factory.createConnection();
    
    assertNotSame(connection1.getAmazonSQSClient(), connection2.getAmazonSQSClient()); 
    
    connection1.close();
    connection2.close();
}
 
Example #15
Source File: SqsIO.java    From beam with Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() {
  sqs =
      AmazonSQSClientBuilder.standard()
          .withClientConfiguration(sqsConfiguration.getClientConfiguration())
          .withCredentials(sqsConfiguration.getAwsCredentialsProvider())
          .withRegion(sqsConfiguration.getAwsRegion())
          .build();
}
 
Example #16
Source File: SqsUnboundedSource.java    From beam with Apache License 2.0 5 votes vote down vote up
public SqsUnboundedSource(Read read, SqsConfiguration sqsConfiguration) {
  this.read = read;
  this.sqsConfiguration = sqsConfiguration;

  sqs =
      Suppliers.memoize(
          (Supplier<AmazonSQS> & Serializable)
              () ->
                  AmazonSQSClientBuilder.standard()
                      .withClientConfiguration(sqsConfiguration.getClientConfiguration())
                      .withCredentials(sqsConfiguration.getAwsCredentialsProvider())
                      .withRegion(sqsConfiguration.getAwsRegion())
                      .build());
}
 
Example #17
Source File: SendReceiveMessages.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    final AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient();

    try {
        CreateQueueResult create_result = sqs.createQueue(QUEUE_NAME);
    } catch (AmazonSQSException e) {
        if (!e.getErrorCode().equals("QueueAlreadyExists")) {
            throw e;
        }
    }

    String queueUrl = sqs.getQueueUrl(QUEUE_NAME).getQueueUrl();

    SendMessageRequest send_msg_request = new SendMessageRequest()
            .withQueueUrl(queueUrl)
            .withMessageBody("hello world")
            .withDelaySeconds(5);
    sqs.sendMessage(send_msg_request);


    // Send multiple messages to the queue
    SendMessageBatchRequest send_batch_request = new SendMessageBatchRequest()
            .withQueueUrl(queueUrl)
            .withEntries(
                    new SendMessageBatchRequestEntry(
                            "msg_1", "Hello from message 1"),
                    new SendMessageBatchRequestEntry(
                            "msg_2", "Hello from message 2")
                            .withDelaySeconds(10));
    sqs.sendMessageBatch(send_batch_request);

    // receive messages from the queue
    List<Message> messages = sqs.receiveMessage(queueUrl).getMessages();

    // delete messages from the queue
    for (Message m : messages) {
        sqs.deleteMessage(queueUrl, m.getReceiptHandle());
    }
}
 
Example #18
Source File: VisibilityTimeout.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    final String queue_name = "testQueue" + new Date().getTime();
    AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient();

    // first, create a queue (unless it exists already)
    try {
        CreateQueueResult cq_result = sqs.createQueue(queue_name);
    } catch (AmazonSQSException e) {
        if (!e.getErrorCode().equals("QueueAlreadyExists")) {
            throw e;
        }
    }

    final String queue_url = sqs.getQueueUrl(queue_name).getQueueUrl();

    // Send some messages to the queue
    for (int i = 0; i < 20; i++) {
        sqs.sendMessage(queue_url, "This is message " + i);
    }

    // change visibility timeout (single)
    changeMessageVisibilitySingle(queue_url, 60 * 60); //1 hour

    // change visibility timeout (multiple)
    changeMessageVisibilityMultiple(queue_url, 30 * 60 ); //30 minutes
}
 
Example #19
Source File: AWSSQSLocalContainerService.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
@Override
public AWSSQSClient getClient() {
    AmazonSQS sqs = AmazonSQSClientBuilder
            .standard()
            .withEndpointConfiguration(getContainer()
                    .getEndpointConfiguration(LocalStackContainer.Service.SQS))
            .withCredentials(getContainer().getDefaultCredentialsProvider())
            .build();

    return new AWSSQSClient(sqs);
}
 
Example #20
Source File: AWSSNSLocalContainerService.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
@Override
public AWSSQSClient getClient() {
    AmazonSQS sqs = AmazonSQSClientBuilder
            .standard()
            .withEndpointConfiguration(getContainer()
                    .getEndpointConfiguration(LocalStackContainer.Service.SQS))
            .withCredentials(getContainer().getDefaultCredentialsProvider())
            .build();

    return new AWSSQSClient(sqs);
}
 
Example #21
Source File: AmazonSQSRule.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
public AmazonSQSRule start(int httpPort) {
  if (server == null) {
    server = SQSRestServerBuilder.withPort(httpPort).withSQSLimits(SQSLimits.Strict()).start();
    server.waitUntilStarted();
  }

  if (client == null) {
    client = AmazonSQSClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("x", "x")))
        .withEndpointConfiguration(new EndpointConfiguration(String.format("http://localhost:%d", httpPort), null))
        .build();
    queueUrl = client.createQueue("zipkin").getQueueUrl();
  }
  return this;
}
 
Example #22
Source File: AWSClientUtils.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
public static AmazonSQS newSQSClient() {
    LOG.debug("Creating a custom SQS client for running a AWS SNS test");
    AmazonSQSClientBuilder clientBuilder = AmazonSQSClientBuilder
            .standard();

    String awsInstanceType = System.getProperty("aws-service.instance.type");
    String region = getRegion();

    if (awsInstanceType == null || awsInstanceType.equals("local-aws-container")) {
        String amazonHost = System.getProperty(AWSConfigs.AMAZON_AWS_HOST);

        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTP);

        clientBuilder
                .withClientConfiguration(clientConfiguration)
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(amazonHost, region))
                .withCredentials(new TestAWSCredentialsProvider("accesskey", "secretkey"));
    } else {
        clientBuilder
                .withRegion(region)
                .withCredentials(new TestAWSCredentialsProvider());
    }



    return clientBuilder.build();
}
 
Example #23
Source File: AmazonDockerClientsHolder.java    From spring-localstack with Apache License 2.0 5 votes vote down vote up
@Override
public AmazonSQS amazonSQS() {
    return decorateWithConfigsAndBuild(
        AmazonSQSClientBuilder.standard(),
        LocalstackDocker::getEndpointSQS
    );
}
 
Example #24
Source File: AWSSQSMetaDataExtension.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<MetaData> meta(Map<String, Object> parameters) {
    final String accessKey = ConnectorOptions.extractOption(parameters, "accessKey");
    final String secretKey = ConnectorOptions.extractOption(parameters, "secretKey");
    final String region = ConnectorOptions.extractOption(parameters, "region");
    AmazonSQSClientBuilder clientBuilder;
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
    clientBuilder = AmazonSQSClientBuilder.standard().withCredentials(credentialsProvider);
    clientBuilder = clientBuilder.withRegion(Regions.valueOf(region));
    AmazonSQS sqsClient = clientBuilder.build();
    List<String> attributeNames = new ArrayList<String>();
    attributeNames.add("All");
    try {
        ListQueuesResult result = sqsClient.listQueues();
        Set<String> setQueue = new HashSet<String>();
        if (result.getQueueUrls() != null) {
            for (String entry : result.getQueueUrls()) {
                GetQueueAttributesRequest req = new GetQueueAttributesRequest();
                req.setQueueUrl(entry);
                req.setAttributeNames(attributeNames);
                GetQueueAttributesResult c = sqsClient.getQueueAttributes(req);
                setQueue.add(c.getAttributes().get(QueueAttributeName.QueueArn.name()));
            }
        }
        return Optional.of(MetaDataBuilder.on(getCamelContext()).withAttribute(MetaData.CONTENT_TYPE, "text/plain").withAttribute(MetaData.JAVA_TYPE, String.class)
            .withPayload(setQueue).build());
    } catch (Exception e) {
        throw new IllegalStateException("Get information about existing queues with has failed.", e);
    }
}
 
Example #25
Source File: VisibilityTimeout.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void changeMessageVisibilitySingle(
        String queue_url, int timeout)
{
    AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient();

    // Get the receipt handle for the first message in the queue.
    String receipt = sqs.receiveMessage(queue_url)
                        .getMessages()
                        .get(0)
                        .getReceiptHandle();

    sqs.changeMessageVisibility(queue_url, receipt, timeout);
}
 
Example #26
Source File: SQSSubscriberProvider.java    From kork with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void start() {
  Preconditions.checkNotNull(
      properties, "Can't initialize SQSSubscriberProvider with null properties");

  ExecutorService executorService =
      Executors.newFixedThreadPool(properties.getSubscriptions().size());

  List<PubsubSubscriber> subscribers = new ArrayList<>();

  properties
      .getSubscriptions()
      .forEach(
          (AmazonPubsubProperties.AmazonPubsubSubscription subscription) -> {
            log.info("Bootstrapping SQS for SNS topic: {}", subscription.getTopicARN());
            ARN queueArn = new ARN(subscription.getQueueARN());
            ARN topicArn = new ARN(subscription.getTopicARN());

            SQSSubscriber worker =
                new SQSSubscriber(
                    subscription,
                    pubsubMessageHandlerFactory.create(subscription),
                    messageAcknowledger,
                    AmazonSNSClientBuilder.standard()
                        .withCredentials(awsCredentialsProvider)
                        .withClientConfiguration(new ClientConfiguration())
                        .withRegion(topicArn.getRegion())
                        .build(),
                    AmazonSQSClientBuilder.standard()
                        .withCredentials(awsCredentialsProvider)
                        .withClientConfiguration(new ClientConfiguration())
                        .withRegion(queueArn.getRegion())
                        .build(),
                    PubSubUtils.getEnabledSupplier(dynamicConfig, subscription, eurekaStatus),
                    registry);
            try {
              executorService.submit(worker);
              subscribers.add(worker);
              log.debug(
                  "Created worker {} for subscription: {}",
                  worker.getWorkerName(),
                  subscription.getName());
            } catch (RejectedExecutionException e) {
              log.error("Could not start {}", worker.getWorkerName(), e);
            }
          });

  pubsubSubscribers.putAll(subscribers);
}
 
Example #27
Source File: SpringCloudAwsTestUtil.java    From tutorials with MIT License 4 votes vote down vote up
public static AmazonSQS amazonSQS() {
    return AmazonSQSClientBuilder.standard()
        .withCredentials(awsCredentialsProvider())
        .withRegion(defaultRegion)
        .build();
}
 
Example #28
Source File: LambdaSqsSdkReceiveSendBatchHandler.java    From Serverless-Programming-Cookbook with MIT License 4 votes vote down vote up
public LambdaSqsSdkReceiveSendBatchHandler() {
    this.sqsClient = AmazonSQSClientBuilder.standard()
            .withRegion(System.getenv("AWS_REGION"))
            .build();
}
 
Example #29
Source File: SQSConnectionFactory.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 4 votes vote down vote up
public SQSConnectionFactory(ProviderConfiguration providerConfiguration) {
    this(providerConfiguration, AmazonSQSClientBuilder.standard());
}
 
Example #30
Source File: LambdaSqsEventHandler.java    From Serverless-Programming-Cookbook with MIT License 4 votes vote down vote up
public LambdaSqsEventHandler() {
    this.sqsClient = AmazonSQSClientBuilder.standard()
            .withRegion(System.getenv("AWS_REGION"))
            .build();
}