Sample code for 30+ languages & platforms
Android™ Requires Chilkat v11.6.0+

Amazon SNS: Inspect and Set the Topic Message-Size Limit

See more Amazon SNS Examples

Uses the current Amazon SNS Query API (Version=2010-03-31) through Chilkat.Rest and AuthAws, with HTTPS, Signature Version 4, and service sns. The API version date remains current. Action and input parameters are URL-encoded into a POST body, avoiding message text and recipient addresses in the URL. Set the actual region once; other AWS partitions need their documented endpoint suffix and ARN partition.

Load private qa_data/aws/sns.json with nonempty string fields access_key, secret_key, and session_token when using temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles, obtain credentials, or refresh them automatically. The session token is included in the signed form body on every request. A Socket explicitly enables TLS certificate verification before passing the connection to Rest.

Checks setup calls, transport completion, HTTP status, XML parsing, result root, and required fields. Normal output includes identifiers, not full messages or headers. Keep detailed diagnostics private. For retryable failures, use bounded backoff with jitter in the application; these examples do not automatically retry writes. A Publish timeout can leave an accepted message and retrying a standard-topic/SMS publish can duplicate it. A returned MessageId confirms SNS acceptance, not subscriber or handset delivery.

Reads the current value, then intentionally sets MaximumMessageSize to 524288 bytes. Supported values are 1024 through 1048576, with default 262144. Values above 256 KiB require at most 100 subscriptions, all using SQS, Firehose or Lambda; SNS rejects incompatible topics. This example does not remove subscriptions or automatically raise limits during publishing. The new setting also bounds combined batch payload size.

Required IAM actions: sns:GetTopicAttributes, sns:SetTopicAttributes. Related SQS/KMS permissions are separate.

AWS references: GetTopicAttributes SetTopicAttributes

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    CkStringBuilder stringCompare = new CkStringBuilder();
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Private credentials; do not put this file in public web content or source control.
    CkJsonObject credentials = new CkJsonObject();
    credentials.put_Strict(true);
    success = credentials.LoadFile("qa_data/aws/sns.json");
    if (success != true) {
        Log.i(TAG, "Could not load private SNS credentials.");
        return;
        }

    stringCompare.SetString(credentials.stringOf("access_key"));
    boolean stringMatch1 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == true)) {
        Log.i(TAG, "Missing or invalid access_key.");
        return;
        }

    stringCompare.SetString(credentials.stringOf("secret_key"));
    boolean stringMatch2 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == true)) {
        Log.i(TAG, "Missing or invalid secret_key.");
        return;
        }

    String region = "us-west-2";
    CkStringBuilder endpoint = new CkStringBuilder();
    endpoint.Append("sns.");
    endpoint.Append(region);
    endpoint.Append(".amazonaws.com");
    CkAuthAws aws = new CkAuthAws();
    aws.put_AccessKey(credentials.stringOf("access_key"));
    aws.put_SecretKey(credentials.stringOf("secret_key"));
    aws.put_Region(region);
    aws.put_ServiceName("sns");
    aws.put_SignatureVersion(4);
    CkRest rest = new CkRest();
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    rest.put_VerboseLogging(false);
    success = rest.SetAuthAws(aws);
    if (success != true) {
        Log.i(TAG, "Could not configure AWS signing.");
        return;
        }

    if (credentials.HasMember("session_token") == true) {
        stringCompare.SetString(credentials.stringOf("session_token"));
        boolean stringMatch3 = stringCompare.ContentsEqual("",true);
        if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch3 == true)) {
            Log.i(TAG, "session_token must be a nonempty string when supplied.");
            return;
            }

        }

    CkXml xml = new CkXml();
    xml.put_Strict(true);
    String value;
    String responseXml;
    String topicArn = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example";
    CkStringBuilder topic = new CkStringBuilder();
    topic.Append(topicArn);
    CkStringBuilder arnPrefix = new CkStringBuilder();
    arnPrefix.Append("arn:aws:sns:");
    arnPrefix.Append(region);
    arnPrefix.Append(":");
    if (topic.StartsWith(arnPrefix.getAsString(),true) != true) {
        Log.i(TAG, "Select an SNS topic ARN in the configured region and commercial AWS partition.");
        return;
        }

    //  Explicit certificate verification; keep this Socket alive while Rest uses it.
    CkSocket connection = new CkSocket();
    connection.put_RequireSslCertVerify(true);
    connection.put_MaxReadIdleMs(60000);
    connection.put_MaxSendIdleMs(60000);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        Log.i(TAG, "TLS connection failed; inspect diagnostics privately.");
        return;
        }

    success = rest.UseConnection(connection,true);
    if (success != true) {
        Log.i(TAG, "Could not attach TLS connection.");
        return;
        }

    success = rest.ClearAllQueryParams();
    if (success != true) {
        Log.i(TAG, "Could not clear parameters from the previous request.");
        return;
        }

    //  Build a fresh form for each request; do not retain parameters from a previous action.
    //  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
    success = rest.AddQueryParam("Action","GetTopicAttributes");
    if (success != true) {
        Log.i(TAG, "Could not set Action.");
        return;
        }

    success = rest.AddQueryParam("Version","2010-03-31");
    if (success != true) {
        Log.i(TAG, "Could not set Version.");
        return;
        }

    //  Include temporary credentials in the signed form body on every request.
    if (credentials.HasMember("session_token") == true) {
        success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"));
        if (success != true) {
            Log.i(TAG, "Could not set X-Amz-Security-Token.");
            return;
            }

        }

    success = rest.AddQueryParam("TopicArn",topicArn);
    if (success != true) {
        Log.i(TAG, "Could not set TopicArn.");
        return;
        }

    responseXml = rest.fullRequestFormUrlEncoded("POST","/");
    if (rest.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Request did not complete. Inspect diagnostics privately.");
        return;
        }

    success = xml.LoadXml(responseXml);
    if (rest.get_ResponseStatusCode() != 200) {
        Log.i(TAG, "SNS HTTP status: " + String.valueOf(rest.get_ResponseStatusCode()));
        if (success == true) {
            value = xml.getChildContent("Error|Code");
            if (xml.get_LastMethodSuccess() == true) {
                Log.i(TAG, "AWS error code: " + value);
                }

            value = xml.getChildContent("RequestId");
            if (xml.get_LastMethodSuccess() == true) {
                Log.i(TAG, "AWS request ID: " + value);
                }

            }

        //  Full messages, headers, and signing diagnostics may contain private data.
        return;
        }

    if (success != true) {
        Log.i(TAG, "Expected a well-formed XML response.");
        return;
        }

    stringCompare.SetString(xml.tag());
    boolean stringMatch4 = stringCompare.ContentsEqual("GetTopicAttributesResponse",true);
    if (stringMatch4 != true) {
        Log.i(TAG, "Unexpected SNS response element.");
        return;
        }

    value = xml.getChildContent("ResponseMetadata|RequestId");
    stringCompare.SetString(value);
    boolean stringMatch5 = stringCompare.ContentsEqual("",true);
    if ((xml.get_LastMethodSuccess() != true) or (stringMatch5 == true)) {
        Log.i(TAG, "Missing or empty ResponseMetadata|RequestId.");
        return;
        }

    Log.i(TAG, "AWS request ID: " + value);
    if (xml.HasChildWithTag("GetTopicAttributesResult") != true) {
        Log.i(TAG, "Missing result.");
        return;
        }

    CkJsonObject attributes = new CkJsonObject();
    int mapIndex = 0;
    while ((mapIndex < xml.NumChildrenAt("GetTopicAttributesResult|Attributes"))) {
        xml.put_I(mapIndex);
        value = xml.getChildContent("GetTopicAttributesResult|Attributes|entry[i]|key");
        stringCompare.SetString(value);
        boolean stringMatch6 = stringCompare.ContentsEqual("",true);
        if ((xml.get_LastMethodSuccess() != true) or (stringMatch6 == true)) {
            Log.i(TAG, "Missing or empty GetTopicAttributesResult|Attributes|entry[i]|key.");
            return;
            }

        String mapKey = value;
        value = xml.getChildContent("GetTopicAttributesResult|Attributes|entry[i]|value");
        if (xml.get_LastMethodSuccess() != true) {
            Log.i(TAG, "Missing map value.");
            return;
            }

        success = attributes.AppendString(mapKey,value);
        if (success != true) {
            Log.i(TAG, "Invalid or duplicate map entry.");
            return;
            }

        mapIndex = mapIndex + 1;
        }

    Log.i(TAG, "Current MaximumMessageSize: " + attributes.stringOf("MaximumMessageSize"));
    success = rest.ClearAllQueryParams();
    if (success != true) {
        Log.i(TAG, "Could not clear parameters from the previous request.");
        return;
        }

    //  Build a fresh form for each request; do not retain parameters from a previous action.
    //  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
    success = rest.AddQueryParam("Action","SetTopicAttributes");
    if (success != true) {
        Log.i(TAG, "Could not set Action.");
        return;
        }

    success = rest.AddQueryParam("Version","2010-03-31");
    if (success != true) {
        Log.i(TAG, "Could not set Version.");
        return;
        }

    //  Include temporary credentials in the signed form body on every request.
    if (credentials.HasMember("session_token") == true) {
        success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"));
        if (success != true) {
            Log.i(TAG, "Could not set X-Amz-Security-Token.");
            return;
            }

        }

    success = rest.AddQueryParam("TopicArn",topicArn);
    if (success != true) {
        Log.i(TAG, "Could not set TopicArn.");
        return;
        }

    success = rest.AddQueryParam("AttributeName","MaximumMessageSize");
    if (success != true) {
        Log.i(TAG, "Could not set AttributeName.");
        return;
        }

    success = rest.AddQueryParam("AttributeValue","524288");
    if (success != true) {
        Log.i(TAG, "Could not set AttributeValue.");
        return;
        }

    responseXml = rest.fullRequestFormUrlEncoded("POST","/");
    if (rest.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Request did not complete. Its outcome may be uncertain; reconcile before retrying.");
        return;
        }

    success = xml.LoadXml(responseXml);
    if (rest.get_ResponseStatusCode() != 200) {
        Log.i(TAG, "SNS HTTP status: " + String.valueOf(rest.get_ResponseStatusCode()));
        if (success == true) {
            value = xml.getChildContent("Error|Code");
            if (xml.get_LastMethodSuccess() == true) {
                Log.i(TAG, "AWS error code: " + value);
                }

            value = xml.getChildContent("RequestId");
            if (xml.get_LastMethodSuccess() == true) {
                Log.i(TAG, "AWS request ID: " + value);
                }

            }

        //  Full messages, headers, and signing diagnostics may contain private data.
        return;
        }

    if (success != true) {
        Log.i(TAG, "Expected a well-formed XML response.");
        return;
        }

    stringCompare.SetString(xml.tag());
    boolean stringMatch7 = stringCompare.ContentsEqual("SetTopicAttributesResponse",true);
    if (stringMatch7 != true) {
        Log.i(TAG, "Unexpected SNS response element.");
        return;
        }

    value = xml.getChildContent("ResponseMetadata|RequestId");
    stringCompare.SetString(value);
    boolean stringMatch8 = stringCompare.ContentsEqual("",true);
    if ((xml.get_LastMethodSuccess() != true) or (stringMatch8 == true)) {
        Log.i(TAG, "Missing or empty ResponseMetadata|RequestId.");
        return;
        }

    Log.i(TAG, "AWS request ID: " + value);
    Log.i(TAG, "Example completed.");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}