### Initialize SNS and SQS Clients and Start Workflow Source: https://docs.aws.amazon.com/sns/latest/dg/example_sqs_Scenario_TopicsAndQueues_section.md Sets up the necessary AWS SDK clients for SNS and SQS, along with a prompter and logger, to initiate the workflow scenario. This is the entry point for the example. ```javascript import { SNSClient } from "@aws-sdk/client-sns"; import { SQSClient } from "@aws-sdk/client-sqs"; import { TopicsQueuesWkflw } from "./TopicsQueuesWkflw.js"; import { Prompter } from "@aws-doc-sdk-examples/lib/prompter.js"; export const startSnsWorkflow = () => { const snsClient = new SNSClient({}); const sqsClient = new SQSClient({}); const prompter = new Prompter(); const logger = console; const wkflw = new TopicsQueuesWkflw(snsClient, sqsClient, prompter, logger); wkflw.start(); }; ``` -------------------------------- ### Demonstrate Subscribing Queues to an SNS FIFO Topic (Python) Source: https://docs.aws.amazon.com/sns/latest/dg/fifo-topic-code-examples.md This example demonstrates how to create an Amazon SNS FIFO topic, subscribe Amazon SQS FIFO and standard queues to it, and publish a message. It includes setup, execution, and cleanup of resources. ```python def usage_demo(): """Shows how to subscribe queues to a FIFO topic.""" print("-" * 88) print("Welcome to the `Subscribe queues to a FIFO topic` demo!") print("-" * 88) sns = boto3.resource("sns") sqs = boto3.resource("sqs") fifo_topic_wrapper = FifoTopicWrapper(sns) sns_wrapper = SnsWrapper(sns) prefix = "sqs-subscribe-demo-" queues = set() subscriptions = set() wholesale_queue = sqs.create_queue( QueueName=prefix + "wholesale.fifo", Attributes={ "MaximumMessageSize": str(4096), "ReceiveMessageWaitTimeSeconds": str(10), "VisibilityTimeout": str(300), "FifoQueue": str(True), "ContentBasedDeduplication": str(True), }, ) queues.add(wholesale_queue) print(f"Created FIFO queue with URL: {wholesale_queue.url}.") retail_queue = sqs.create_queue( QueueName=prefix + "retail.fifo", Attributes={ "MaximumMessageSize": str(4096), "ReceiveMessageWaitTimeSeconds": str(10), "VisibilityTimeout": str(300), "FifoQueue": str(True), "ContentBasedDeduplication": str(True), }, ) queues.add(retail_queue) print(f"Created FIFO queue with URL: {retail_queue.url}.") analytics_queue = sqs.create_queue(QueueName=prefix + "analytics", Attributes={}) queues.add(analytics_queue) print(f"Created standard queue with URL: {analytics_queue.url}.") topic = fifo_topic_wrapper.create_fifo_topic("price-updates-topic.fifo") print(f"Created FIFO topic: {topic.attributes['TopicArn']}.") for q in queues: fifo_topic_wrapper.add_access_policy(q, topic.attributes["TopicArn"]) print(f"Added access policies for topic: {topic.attributes['TopicArn']}.") for q in queues: sub = fifo_topic_wrapper.subscribe_queue_to_topic( topic, q.attributes["QueueArn"] ) subscriptions.add(sub) print(f"Subscribed queues to topic: {topic.attributes['TopicArn']}.") input("Press Enter to publish a message to the topic.") message_id = fifo_topic_wrapper.publish_price_update( topic, '{"product": 214, "price": 79.99}', "Consumables" ) print(f"Published price update with message ID: {message_id}.") # Clean up the subscriptions, queues, and topic. input("Press Enter to clean up resources.") for s in subscriptions: sns_wrapper.delete_subscription(s) sns_wrapper.delete_topic(topic) for q in queues: fifo_topic_wrapper.delete_queue(q) print(f"Deleted subscriptions, queues, and topic.") print("Thanks for watching!") print("-" * 88) ``` -------------------------------- ### ListPlatformApplications Request Example Source: https://docs.aws.amazon.com/sns/latest/api/API_ListPlatformApplications.md This example demonstrates how to call the ListPlatformApplications API to retrieve a list of platform applications. The AUTHPARAMS placeholder should be replaced with actual authentication parameters. ```HTTP https://sns.us-west-2.amazonaws.com/?Action=ListPlatformApplications &Version=2010-03-31 &AUTHPARAMS ``` -------------------------------- ### Publish API Example Source: https://docs.aws.amazon.com/sns/latest/api/API_Publish.md This example demonstrates how to publish a message using the Publish API. It includes a sample request URL and the expected response structure. ```APIDOC ## Publish API Example ### Description This example illustrates one usage of Publish. ### Sample Request ``` https://sns.us-west-2.amazonaws.com/?Action=Publish &TargetArn=arn%3Aaws%3Asns%3Aus-west-2%3A803981987763%3Aendpoint%2FAPNS_SANDBOX%2Fpushapp%2F98e9ced9-f136-3893-9d60-776547eafebb &Message=%7B%22default%22%3A%22This+is+the+default+Message%22%2C%22APNS_SANDBOX%22%3A%22%7B+%5C%22aps%5C%22+%3A+%7B+%5C%22alert%5C%22+%3A+%5C%22You+have+got+email.%5C%22%2C+%5C%22badge%5C%22+%3A+9%2C%5C%22sound%5C%22+%3A%5C%22default%5C%22%7D%7D%22%7D &Version=2010-03-31 &AUTHPARAMS ``` ### Sample Response ``` 567910cd-659e-55d4-8ccb-5aaf14679dc0 d74b8436-ae13-5ab4-a9ff-ce54dfea72a0 ``` ``` -------------------------------- ### AWS CLI Script for SNS Getting Started Source: https://docs.aws.amazon.com/sns/latest/dg/example_sns_GettingStarted_048_section.md This Bash script automates the process of creating an SNS topic, subscribing an email address, and cleaning up resources. It includes error handling and logging. Ensure AWS CLI and jq are installed and configured. ```bash #!/bin/bash # Amazon SNS Getting Started Script # This script demonstrates how to create an SNS topic, subscribe to it, publish a message, # and clean up resources. set -euo pipefail # Set up logging with secure file permissions LOG_FILE="sns-tutorial.log" touch "$LOG_FILE" chmod 600 "$LOG_FILE" exec > >(tee -a "$LOG_FILE") 2>&1 echo "Starting Amazon SNS Getting Started Tutorial..." echo "$(date)" echo "==============================================" # Function to handle errors handle_error() { echo "ERROR: $1" >&2 echo "Attempting to clean up resources..." cleanup_resources exit 1 } # Function to clean up resources cleanup_resources() { local exit_code=$? if [ -n "${SUBSCRIPTION_ARN:-}" ] && [ "$SUBSCRIPTION_ARN" != "pending confirmation" ] && [ "$SUBSCRIPTION_ARN" != "PendingConfirmation" ]; then echo "Deleting subscription: $SUBSCRIPTION_ARN" if ! aws sns unsubscribe --subscription-arn "$SUBSCRIPTION_ARN" --region "$AWS_REGION" 2>/dev/null; then echo "Warning: Failed to delete subscription" >&2 fi fi if [ -n "${TOPIC_ARN:-}" ]; then echo "Deleting topic: $TOPIC_ARN" if ! aws sns delete-topic --topic-arn "$TOPIC_ARN" --region "$AWS_REGION" 2>/dev/null; then echo "Warning: Failed to delete topic" >&2 fi fi return $exit_code } # Validate AWS region AWS_REGION="${AWS_REGION:-us-east-1}" if [[ ! "$AWS_REGION" =~ ^[a-z]{2}-[a-z]+-[0-9]{1}$ ]]; then handle_error "Invalid AWS region format: $AWS_REGION" fi # Set trap to cleanup on exit trap cleanup_resources EXIT # Verify AWS CLI is installed and configured if ! command -v aws &> /dev/null; then handle_error "AWS CLI is not installed or not in PATH" fi if ! command -v jq &> /dev/null; then handle_error "jq is not installed or not in PATH" fi if ! aws sts get-caller-identity --region "$AWS_REGION" &> /dev/null; then handle_error "AWS credentials are not configured or invalid" fi # Generate a random topic name suffix using secure method RANDOM_SUFFIX=$(openssl rand -hex 4) TOPIC_NAME="my-topic-${RANDOM_SUFFIX}" # Validate topic name length (max 256 characters) if [ ${#TOPIC_NAME} -gt 256 ]; then handle_error "Topic name exceeds maximum length of 256 characters" fi # Step 1: Create an SNS topic echo "Creating SNS topic: $TOPIC_NAME" TOPIC_RESULT=$(aws sns create-topic \ --name "$TOPIC_NAME" \ --region "$AWS_REGION" \ --tags Key=project,Value=doc-smith Key=tutorial,Value=amazon-simple-notification-service-gs \ --output json) || handle_error "Failed to create SNS topic" # Extract the topic ARN using jq for reliable parsing TOPIC_ARN=$(echo "$TOPIC_RESULT" | jq -r '.TopicArn // empty') || handle_error "Failed to parse topic result" if [ -z "$TOPIC_ARN" ]; then handle_error "Failed to extract topic ARN from result: $TOPIC_RESULT" fi # Validate ARN format if [[ ! "$TOPIC_ARN" =~ ^arn:aws:sns:[a-z0-9-]+:[0-9]{12}:[a-zA-Z0-9_-]+$ ]]; then handle_error "Invalid SNS topic ARN format: $TOPIC_ARN" fi echo "Successfully created topic with ARN: $TOPIC_ARN" # Step 2: Subscribe to the topic using Email-JSON protocol to reduce costs echo "" echo "==============================================" echo "EMAIL SUBSCRIPTION" echo "==============================================" EMAIL_ADDRESS="test-${RANDOM_SUFFIX}@example.com" # Validate email format (basic validation) if [[ ! "$EMAIL_ADDRESS" =~ ^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then handle_error "Invalid email format: $EMAIL_ADDRESS" fi echo "Subscribing email: $EMAIL_ADDRESS to topic using Email-JSON protocol" SUBSCRIPTION_RESULT=$(aws sns subscribe \ --topic-arn "$TOPIC_ARN" \ --protocol email-json \ --notification-endpoint "$EMAIL_ADDRESS" \ --region "$AWS_REGION" \ --output json) || handle_error "Failed to create subscription" # Extract the subscription ARN using jq SUBSCRIPTION_ARN=$(echo "$SUBSCRIPTION_RESULT" | jq -r '.SubscriptionArn // empty') || handle_error "Failed to parse subscription result" echo "Subscription created: $SUBSCRIPTION_ARN" echo "A confirmation email has been sent to $EMAIL_ADDRESS" echo "" ``` -------------------------------- ### Hello SNS C++ Example Source: https://docs.aws.amazon.com/sns/latest/dg/example_sns_Hello_section.md Initializes the AWS SDK and an SNS client, then lists all SNS topics in the account, handling pagination. Errors during the API call are printed to stderr. ```cpp #include #include #include #include /* * A "Hello SNS" starter application which initializes an Amazon Simple Notification * Service (Amazon SNS) client and lists the SNS topics in the current account. * * main function * * Usage: 'hello_sns' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfig); Aws::Vector allTopics; Aws::String nextToken; // Next token is used to handle a paginated response. do { Aws::SNS::Model::ListTopicsRequest request; if (!nextToken.empty()) { request.SetNextToken(nextToken); } const Aws::SNS::Model::ListTopicsOutcome outcome = snsClient.ListTopics( request); if (outcome.IsSuccess()) { const Aws::Vector &paginatedTopics = outcome.GetResult().GetTopics(); if (!paginatedTopics.empty()) { allTopics.insert(allTopics.cend(), paginatedTopics.cbegin(), paginatedTopics.cend()); } } else { std::cerr << "Error listing topics " << outcome.GetError().GetMessage() << std::endl; return 1; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); std::cout << "Hello Amazon SNS! You have " << allTopics.size() << " topic" << (allTopics.size() == 1 ? "" : "s") << " in your account." << std::endl; if (!allTopics.empty()) { std::cout << "Here are your topic ARNs." << std::endl; for (const Aws::SNS::Model::Topic &topic: allTopics) { std::cout << " * " << topic.GetTopicArn() << std::endl; } } } Aws::ShutdownAPI(options); // Should only be called once. return 0; } ``` -------------------------------- ### Get SNS Topic Attributes with AWS SDK for SAP ABAP Source: https://docs.aws.amazon.com/sns/latest/dg/example_sns_GetTopicAttributes_section.md This example shows how to get the attributes of an SNS topic using the AWS SDK for SAP ABAP. It includes basic error handling for a non-existent topic. ```abap TRY. oo_result = lo_sns->gettopicattributes( iv_topicarn = iv_topic_arn ). " oo_result is returned for testing purposes. " DATA(lt_attributes) = oo_result->get_attributes( ). MESSAGE 'Retrieved attributes/properties of a topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY. ``` -------------------------------- ### Run Cross-Service Messaging Example Source: https://docs.aws.amazon.com/sns/latest/dg/example_sqs_Scenario_TopicsAndQueues_section.md Initializes SNS and SQS clients and prompts the user for configuration options for creating an SNS topic and its subscriptions. ```swift /// Called by ``main()`` to run the bulk of the example. func runAsync() async throws { let rowOfStars = String(repeating: "*", count: 75) print(""" \(rowOfStars) Welcome to the cross-service messaging with topics and queues example. In this workflow, you'll create an SNS topic, then create two SQS queues which will be subscribed to that topic. You can specify several options for configuring the topic, as well as the queue subscriptions. You can then post messages to the topic and receive the results on the queues. \(rowOfStars)\n """) // 0. Create SNS and SQS clients. let snsConfig = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: snsConfig) let sqsConfig = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: sqsConfig) // 1. Ask the user whether to create a FIFO topic. If so, ask whether // to use content-based deduplication instead of requiring a // deduplication ID. let isFIFO = yesNoRequest(prompt: "Do you want to create a FIFO topic (Y/N)? ") var isContentBasedDeduplication = false if isFIFO { print(""" \(rowOfStars) Because you've chosen to create a FIFO topic, deduplication is supported. Deduplication IDs are either set in the message or are automatically generated from the content using a hash function. If a message is successfully published to an SNS FIFO topic, any message published and found to have the same deduplication ID (within a five-minute deduplication interval), is accepted but not delivered. For more information about deduplication, see: https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html. """) isContentBasedDeduplication = yesNoRequest( prompt: "Use content-based deduplication instead of entering a deduplication ID (Y/N)? ") print(rowOfStars) } var topicName = stringRequest(prompt: "Enter the name of the topic to create: ") // 2. Create the topic. Append ".fifo" to the name if FIFO was // requested, and set the "FifoTopic" attribute to "true" if so as // well. Set the "ContentBasedDeduplication" attribute to "true" if // content-based deduplication was requested. if isFIFO { topicName += ".fifo" } print("Topic name: \(topicName)") var attributes = [ "FifoTopic": (isFIFO ? "true" : "false") ] // If it's a FIFO topic with content-based deduplication, set the // "ContentBasedDeduplication" attribute. if isContentBasedDeduplication { attributes["ContentBasedDeduplication"] = "true" } // Create the topic and retrieve the ARN. let output = try await snsClient.createTopic( input: CreateTopicInput( ``` -------------------------------- ### AWS CLI Script for IoT Device Defender Setup Source: https://docs.aws.amazon.com/sns/latest/dg/example_iot_GettingStarted_079_section.md This Bash script automates the setup and configuration of AWS IoT Device Defender, including IAM roles, audit checks, mitigation actions, and logging. It requires AWS CLI and jq to be installed. ```bash #!/bin/bash # AWS IoT Device Defender Getting Started Script # This script demonstrates how to use AWS IoT Device Defender to enable audit checks, # view audit results, create mitigation actions, and apply them to findings. set -euo pipefail # Set up logging LOG_FILE="iot-device-defender-script-$(date +%Y%m%d%H%M%S).log" exec > >(tee -a "$LOG_FILE") 2>&1 echo "===================================================" echo "AWS IoT Device Defender Getting Started Script" echo "===================================================" echo "Starting script execution at $(date)" echo "" # Function to check for errors in command output check_error() { if echo "$1" | grep -iE "An error occurred|Exception|Failed|usage: aws" > /dev/null; then echo "ERROR: Command failed with the following output:" echo "$1" return 1 fi return 0 } # Function to safely extract JSON values using jq extract_json_value() { local json="$1" local key="$2" echo "$json" | jq -r ".${key} // empty" 2>/dev/null || echo "" } # Function to validate JSON validate_json() { local json="$1" echo "$json" | jq empty 2>/dev/null } # Function to check AWS CLI availability check_aws_cli() { if ! command -v aws &> /dev/null; then echo "ERROR: AWS CLI is not installed or not in PATH" return 1 fi if ! command -v jq &> /dev/null; then echo "ERROR: jq is not installed or not in PATH" return 1 fi return 0 } # Function to get AWS account ID get_account_id() { local account_id account_id=$(aws sts get-caller-identity --query 'Account' --output text 2>/dev/null) || true if [ -z "$account_id" ]; then echo "ERROR: Could not retrieve AWS account ID" return 1 fi echo "$account_id" return 0 } ``` -------------------------------- ### Anything-But with Prefix Message Body Source: https://docs.aws.amazon.com/sns/latest/dg/string-value-matching.md An example of a message body value that matches an 'anything-but' policy with a prefix. It matches if the value does not start with the specified prefix. ```json { "event": "data-entry" } ``` -------------------------------- ### Anything-But with Prefix Policy Source: https://docs.aws.amazon.com/sns/latest/dg/string-value-matching.md Uses 'anything-but' with a 'prefix' to deny messages where the attribute or body value starts with a specific string. This example denies the 'order-' prefix. ```json "event":[{"anything-but": {"prefix": "order-"}}] ``` -------------------------------- ### List SNS Topics in Go Source: https://docs.aws.amazon.com/sns/latest/dg/example_sns_Hello_section.md Initializes an SNS client using default configuration and lists all topics in your AWS account. Ensure your AWS credentials and configuration are set up. ```Go package main import ( "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Notification Service // (Amazon SNS) client and list the topics in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { ctx := context.Background() sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } snsClient := sns.NewFromConfig(sdkConfig) fmt.Println("Let's list the topics for your account.") var topics []types.Topic paginator := sns.NewListTopicsPaginator(snsClient, &sns.ListTopicsInput{}) for paginator.HasMorePages() { output, err := paginator.NextPage(ctx) if err != nil { log.Printf("Couldn't get topics. Here's why: %v\n", err) break } else { topics = append(topics, output.Topics...) } } if len(topics) == 0 { fmt.Println("You don't have any topics!") } else { for _, topic := range topics { fmt.Printf("\t%v\n", *topic.TopicArn) } } } ``` -------------------------------- ### SNS and SQS Messaging Workflow Setup in C++ Source: https://docs.aws.amazon.com/sns/latest/dg/example_sqs_Scenario_TopicsAndQueues_section.md Initializes client configuration and demonstrates the main workflow function for messaging with SNS topics and SQS queues. Handles user prompts for FIFO topic selection and deduplication preferences. ```cpp Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Workflow for messaging with topics and queues using Amazon SNS and Amazon SQS. /*! \param clientConfig Aws client configuration. \return bool: Successful completion. */ bool AwsDoc::TopicsAndQueues::messagingWithTopicsAndQueues( const Aws::Client::ClientConfiguration &clientConfiguration) { std::cout << "Welcome to messaging with topics and queues." << std::endl; printAsterisksLine(); std::cout << "In this workflow, you will create an SNS topic and subscribe " << NUMBER_OF_QUEUES << " SQS queues to the topic." << std::endl; std::cout << "You can select from several options for configuring the topic and the subscriptions for the " << NUMBER_OF_QUEUES << " queues." << std::endl; std::cout << "You can then post to the topic and see the results in the queues." << std::endl; Aws::SNS::SNSClient snsClient(clientConfiguration); printAsterisksLine(); std::cout << "SNS topics can be configured as FIFO (First-In-First-Out)." << std::endl; std::cout << "FIFO topics deliver messages in order and support deduplication and message filtering." << std::endl; bool isFifoTopic = askYesNoQuestion( "Would you like to work with FIFO topics? (y/n) "); bool contentBasedDeduplication = false; Aws::String topicName; if (isFifoTopic) { printAsterisksLine(); std::cout << "Because you have chosen a FIFO topic, deduplication is supported." << std::endl; std::cout << "Deduplication IDs are either set in the message or automatically generated " << "from content using a hash function." << std::endl; std::cout << "If a message is successfully published to an SNS FIFO topic, any message " << "published and determined to have the same deduplication ID, " << std::endl; std::cout << "within the five-minute deduplication interval, is accepted but not delivered." << std::endl; std::cout << "For more information about deduplication, " << "see https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html." << std::endl; contentBasedDeduplication = askYesNoQuestion( "Use content-based deduplication instead of entering a deduplication ID? (y/n) "); } printAsterisksLine(); Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::Vector queueURLS; Aws::Vector subscriptionARNS; Aws::String topicARN; { topicName = askQuestion("Enter a name for your SNS topic. "); // 1. Create an Amazon SNS topic, either FIFO or non-FIFO. Aws::SNS::Model::CreateTopicRequest request; if (isFifoTopic) { request.AddAttributes("FifoTopic", "true"); if (contentBasedDeduplication) { request.AddAttributes("ContentBasedDeduplication", "true"); } topicName = topicName + FIFO_SUFFIX; std::cout << "Because you have selected a FIFO topic, '.fifo' must be appended to the topic name." << std::endl; } request.SetName(topicName); Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request); if (outcome.IsSuccess()) { topicARN = outcome.GetResult().GetTopicArn(); std::cout << "Your new topic with the name '" << topicName << "' and the topic Amazon Resource Name (ARN) " << std::endl; std::cout << "'" << topicARN << "' has been created." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::CreateTopic. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } printAsterisksLine(); std::cout << "Now you will create " << NUMBER_OF_QUEUES << " SQS queues to subscribe to the topic." << std::endl; Aws::Vector queueNames; bool filteringMessages = false; bool first = true; for (int i = 1; i <= NUMBER_OF_QUEUES; ++i) { Aws::String queueURL; ``` -------------------------------- ### TopicsAndQueuesScenario Class in Python Source: https://docs.aws.amazon.com/sns/latest/dg/example_sqs_Scenario_TopicsAndQueues_section.md Manages the setup, demonstration, and cleanup of an SNS topic and SQS queue scenario. Use this class to run an interactive example of messaging between topics and queues. ```python class TopicsAndQueuesScenario: """Manages the Topics and Queues feature scenario.""" DASHES = "-" * 80 def __init__(self, sns_wrapper: SnsWrapper, sqs_wrapper: SqsWrapper) -> None: """ Initialize the Topics and Queues scenario. :param sns_wrapper: SnsWrapper instance for SNS operations. :param sqs_wrapper: SqsWrapper instance for SQS operations. """ self.sns_wrapper = sns_wrapper self.sqs_wrapper = sqs_wrapper # Scenario state self.use_fifo_topic = False self.use_content_based_deduplication = False self.topic_name = None self.topic_arn = None self.queue_count = 2 self.queue_urls = [] self.subscription_arns = [] self.tones = ["cheerful", "funny", "serious", "sincere"] def run_scenario(self) -> None: """Run the Topics and Queues feature scenario.""" print(self.DASHES) print("Welcome to messaging with topics and queues.") print(self.DASHES) print(f""" In this scenario, you will create an SNS topic and subscribe {self.queue_count} SQS queues to the topic. You can select from several options for configuring the topic and the subscriptions for the queues. You can then post to the topic and see the results in the queues. ") try: # Setup Phase print(self.DASHES) self._setup_topic() print(self.DASHES) self._setup_queues() print(self.DASHES) # Demonstration Phase self._publish_messages() print(self.DASHES) # Examination Phase self._poll_queues_for_messages() print(self.DASHES) # Cleanup Phase self._cleanup_resources() print(self.DASHES) except Exception as e: logger.error(f"Scenario failed: {e}") print(f"There was a problem with the scenario: {e}") print("\nInitiating cleanup...") try: self._cleanup_resources() except Exception as cleanup_error: logger.error(f"Error during cleanup: {cleanup_error}") print("Messaging with topics and queues scenario is complete.") print(self.DASHES) def _setup_topic(self) -> None: """Set up the SNS topic to be used with the queues.""" print("SNS topics can be configured as FIFO (First-In-First-Out).") print("FIFO topics deliver messages in order and support deduplication and message filtering.") print() self.use_fifo_topic = q.ask("Would you like to work with FIFO topics? (y/n): ", q.is_yesno) if self.use_fifo_topic: print(self.DASHES) self.topic_name = q.ask("Enter a name for your SNS topic: ", q.non_empty) print("Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.") print() print(self.DASHES) print(""" Because you have chosen a FIFO topic, deduplication is supported. Deduplication IDs are either set in the message or automatically generated from content using a hash function. If a message is successfully published to an SNS FIFO topic, any message published and determined to have the same deduplication ID, within the five-minute deduplication interval, is accepted but not delivered. For more information about deduplication, see https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html. ") self.use_content_based_deduplication = q.ask( "Use content-based deduplication instead of entering a deduplication ID? (y/n): ", q.is_yesno ) else: self.topic_name = q.ask("Enter a name for your SNS topic: ", q.non_empty) print(self.DASHES) # Create the topic self.topic_arn = self.sns_wrapper.create_topic( self.topic_name, self.use_fifo_topic, self.use_content_based_deduplication ) print(f"Your new topic with the name {self.topic_name}") print(f" and Amazon Resource Name (ARN) {self.topic_arn}") print(f" has been created.") print() def _setup_queues(self) -> None: """Set up the SQS queues and subscribe them to the topic.""" print(f"Now you will create {self.queue_count} Amazon Simple Queue Service (Amazon SQS) queues to subscribe to the topic.") for i in range(self.queue_count): ``` -------------------------------- ### Get SNS Topic Attributes using AWS CLI Source: https://docs.aws.amazon.com/sns/latest/dg/example_sns_GetTopicAttributes_section.md Use the AWS CLI to retrieve the attributes of a specified SNS topic. Ensure you have the AWS CLI installed and configured. ```bash aws sns get-topic-attributes \ --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" ``` -------------------------------- ### Run Topics and Queues Scenario (Go) Source: https://docs.aws.amazon.com/sns/latest/dg/example_sqs_Scenario_TopicsAndQueues_section.md Orchestrates the interactive example for creating and using SNS topics and SQS queues. It handles resource creation, subscription, message publishing, polling, and cleanup, using a questioner for user input. ```Go // RunTopicsAndQueuesScenario is an interactive example that shows you how to use the // AWS SDK for Go to create and use Amazon SNS topics and Amazon SQS queues. // // 1. Create a topic (FIFO or non-FIFO). // 2. Subscribe several queues to the topic with an option to apply a filter. // 3. Publish messages to the topic. // 4. Poll the queues for messages received. // 5. Delete the topic and the queues. // // This example creates service clients from the specified sdkConfig so that // you can replace it with a mocked or stubbed config for unit testing. // // It uses a questioner from the `demotools` package to get input during the example. // This package can be found in the ..\..\demotools folder of this repo. func RunTopicsAndQueuesScenario( ctx context.Context, sdkConfig aws.Config, questioner demotools.IQuestioner) { resources := Resources{} defer func() { if r := recover(); r != nil { log.Println("Something went wrong with the demo.\n" + "Cleaning up any resources that were created...") resources.Cleanup(ctx) } }() queueCount := 2 log.Println(strings.Repeat("-", 88)) log.Printf("Welcome to messaging with topics and queues.\n\n" + "In this scenario, you will create an SNS topic and subscribe %v SQS queues to the\n" + ``` -------------------------------- ### Get SMS Attributes using AWS SDK for JavaScript (v3) Source: https://docs.aws.amazon.com/sns/latest/dg/example_sns_GetSMSAttributes_section.md Fetches the 'DefaultSMSType' attribute. If account-level mobile settings are not modified, this attribute might be undefined. The example assumes it was set to 'Transactional'. ```javascript import { GetSMSAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const getSmsAttributes = async () => { const response = await snsClient.send( // If you have not modified the account-level mobile settings of SNS, // the DefaultSMSType is undefined. For this example, it was set to // Transactional. new GetSMSAttributesCommand({ attributes: ["DefaultSMSType"] }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '67ad8386-4169-58f1-bdb9-debd281d48d5', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // attributes: { DefaultSMSType: 'Transactional' } // } return response; }; ``` -------------------------------- ### ListPlatformApplications Response Example Source: https://docs.aws.amazon.com/sns/latest/api/API_ListPlatformApplications.md This is a sample response from the ListPlatformApplications API, showing the structure of the returned platform applications, including their ARNs and attributes. ```XML arn:aws:sns:us-west-2:123456789012:app/APNS_SANDBOX/apnspushapp AllowEndpointPolicies false arn:aws:sns:us-west-2:123456789012:app/GCM/gcmpushapp AllowEndpointPolicies false 315a335e-85d8-52df-9349-791283cbb529 ``` -------------------------------- ### Get Subscription Attributes Request Source: https://docs.aws.amazon.com/sns/latest/api/API_GetSubscriptionAttributes.md This example shows how to make a request to the GetSubscriptionAttributes API to retrieve the properties of a specific subscription. Ensure you replace placeholder values with your actual subscription ARN and authentication parameters. ```api https://sns.us-east-2.amazonaws.com/?Action=GetSubscriptionAttributes &SubscriptionArn=arn%3Aaws%3Asns%3Aus-east-2%3A123456789012%3AMy-Topic%3A80289ba6-0fd4-4079-afb4-ce8c8260f0ca &Version=2010-03-31 &AUTHPARAMS ``` -------------------------------- ### Create and Publish to an SNS FIFO Topic with SQS Subscriptions (Java) Source: https://docs.aws.amazon.com/sns/latest/dg/example_sns_PublishFifoTopic_section.md This example creates an Amazon SNS FIFO topic, two Amazon SQS FIFO queues, and one Standard queue. It then subscribes the queues to the topic, adds access policies, and publishes a message. Finally, it cleans up by deleting subscriptions, queues, and the topic. Ensure you have the necessary IAM permissions. ```java public class PriceUpdateExample { public final static SnsClient snsClient = SnsClient.create(); public final static SqsClient sqsClient = SqsClient.create(); public static void main(String[] args) { final String usage = "\n" + "Usage: " + " \n\n" + "Where:\n" + " fifoTopicName - The name of the FIFO topic that you want to create. \n\n" + " wholesaleQueueARN - The name of a SQS FIFO queue that will be created for the wholesale consumer. \n\n" + " retailQueueARN - The name of a SQS FIFO queue that will created for the retail consumer. \n\n" + " analyticsQueueARN - The name of a SQS standard queue that will be created for the analytics consumer. \n\n"; if (args.length != 4) { System.out.println(usage); System.exit(1); } final String fifoTopicName = args[0]; final String wholeSaleQueueName = args[1]; final String retailQueueName = args[2]; final String analyticsQueueName = args[3]; // For convenience, the QueueData class holds metadata about a queue: ARN, URL, // name and type. List queues = List.of( new QueueData(wholeSaleQueueName, QueueType.FIFO), new QueueData(retailQueueName, QueueType.FIFO), new QueueData(analyticsQueueName, QueueType.Standard)); // Create queues. createQueues(queues); // Create a topic. String topicARN = createFIFOTopic(fifoTopicName); // Subscribe each queue to the topic. subscribeQueues(queues, topicARN); // Allow the newly created topic to send messages to the queues. addAccessPolicyToQueuesFINAL(queues, topicARN); // Publish a sample price update message with payload. publishPriceUpdate(topicARN, "{\"product\": 214, \"price\": 79.99}", "Consumables"); // Clean up resources. deleteSubscriptions(queues); deleteQueues(queues); deleteTopic(topicARN); } public static String createFIFOTopic(String topicName) { try { // Create a FIFO topic by using the SNS service client. Map topicAttributes = Map.of( "FifoTopic", "true", "ContentBasedDeduplication", "false", "FifoThroughputScope", "MessageGroup"); CreateTopicRequest topicRequest = CreateTopicRequest.builder() .name(topicName) .attributes(topicAttributes) .build(); CreateTopicResponse response = snsClient.createTopic(topicRequest); String topicArn = response.topicArn(); System.out.println("The topic ARN is" + topicArn); return topicArn; } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static void subscribeQueues(List queues, String topicARN) { queues.forEach(queue -> { SubscribeRequest subscribeRequest = SubscribeRequest.builder() .topicArn(topicARN) .endpoint(queue.queueARN) .protocol("sqs") .build(); // Subscribe to the endpoint by using the SNS service client. // Only Amazon SQS queues can receive notifications from an Amazon SNS FIFO // topic. SubscribeResponse subscribeResponse = snsClient.subscribe(subscribeRequest); System.out.println("The queue [" + queue.queueARN + "] subscribed to the topic [" + topicARN + "]"); queue.subscriptionARN = subscribeResponse.subscriptionArn(); }); } public static void publishPriceUpdate(String topicArn, String payload, String groupId) { try { // Create and publish a message that updates the wholesale price. ``` -------------------------------- ### CheckIfPhoneNumberIsOptedOut (JavaScript) Source: https://docs.aws.amazon.com/sns/latest/dg/example_sns_CheckIfPhoneNumberIsOptedOut_section.md This JavaScript code example demonstrates how to check if a given phone number has opted out of receiving SNS messages using the AWS SDK for JavaScript (v3). It shows client setup and API invocation. ```APIDOC ## CheckIfPhoneNumberIsOptedOut ### Description Checks if a phone number is opted out of receiving SNS messages using the AWS SDK for JavaScript (v3). ### Method `CheckIfPhoneNumberIsOptedOutCommand` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **phoneNumber** (string) - Required - The phone number to check. ### Request Example ```javascript import { CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const checkIfPhoneNumberIsOptedOut = async ( phoneNumber = "5555555555", ) => { const command = new CheckIfPhoneNumberIsOptedOutCommand({ phoneNumber, }); const response = await snsClient.send(command); console.log(response); return response; }; ``` ### Response #### Success Response (200) - **isOptedOut** (boolean) - Indicates whether the phone number is opted out. #### Response Example ```json { "$metadata": { "httpStatusCode": 200, "requestId": "3341c28a-cdc8-5b39-a3ee-9fb0ee125732", "extendedRequestId": undefined, "cfId": undefined, "attempts": 1, "totalRetryDelay": 0 }, "isOptedOut": false } ``` ``` -------------------------------- ### Resource Cleanup (Go) Source: https://docs.aws.amazon.com/sns/latest/dg/example_sqs_Scenario_TopicsAndQueues_section.md Manages cleanup of AWS resources created during an example, including SNS topics and SQS queues. It uses defer to ensure cleanup runs even if errors occur. ```Go import ( "context" "fmt" "log" "topics_and_queues/actions" ) // Resources keeps track of AWS resources created during an example and handles // cleanup when the example finishes. type Resources struct { topicArn string queueUrls []string snsActor *actions.SnsActions sqsActor *actions.SqsActions } // Cleanup deletes all AWS resources created during an example. func (resources Resources) Cleanup(ctx context.Context) { defer func() { if r := recover(); r != nil { fmt.Println("Something went wrong during cleanup. Use the AWS Management Console\n" + "to remove any remaining resources that were created for this scenario.") } }() var err error if resources.topicArn != "" { log.Printf("Deleting topic %v.\n", resources.topicArn) err = resources.snsActor.DeleteTopic(ctx, resources.topicArn) if err != nil { panic(err) } } for _, queueUrl := range resources.queueUrls { log.Printf("Deleting queue %v.\n", queueUrl) err = resources.sqsActor.DeleteQueue(ctx, queueUrl) if err != nil { panic(err) } } } ```