Appstore Blogs

Appstore Blogs

Want the latest?

appstore topics

Recent Posts

Archive

Showing posts by gdierkes

December 16, 2011

gdierkes

Overview

This article discusses how mobile apps can use Amazon Web Services to communicate with users via e-mail, short message service (SMS), and other communication channels. The sample code presented here uses Amazon Simple Notification Service and Amazon Simple Queue Service. Amazon Simple Notification Service (Amazon SNS) makes it easy to set up, manage, and send notifications from mobile apps and have these notifications delivered immediately to any users who have chosen to subscribe to them. Amazon SNS provides a highly scalable, flexible, and cost-effective method to implement such notification systems.

Amazon Simple Queue Service (Amazon SQS), also discussed here, offers a reliable, highly scalable, hosted queue for storing messages. The types of messages supported by Amazon SQS include—but aren't limited to—the notification messages sent from Amazon SNS.

Together, Amazon SNS and Amazon SQS enable developers to create apps that can message large numbers of users in multiple formats quickly and easily.

The sample app described here demostrates how mobile apps can message their users through Amazon SNS and Amazon SQS. The sample demonstrates how to use Amazon SNS to create a topic, subscribe users to that topic, and publish notifications to the topic. Subscribers to the topic can receive their notifications via e-mail, SMS, or an Amazon SQS queue. Amazon SQS and Amazon SNS can also be used to create other types of communication systems not shown here.

This article shows sample code but the complete sample code and project files are included in the AWS SDK for Android. A link to the SDK is available at the end of this article.

To use the AWS SDK for Android, you will need AWS credentials, that is, an Access Key ID and Secret Access Key. If you haven't already signed up for Amazon Web Services (AWS), you will need to do that first to get your credentials. You can sign up for AWS here. After you sign up, you can retrieve your credentials at this page.

Creating Amazon SQS and Amazon SNS Clients

Making requests to Amazon SNS and Amazon SQS requires creating a client for each service. The code below shows how to create a client:

AWSCredentials credentials =      new BasicAWSCredentials( Constants.ACCESS_KEY_ID, Constants.SECRET_KEY );		AmazonSNSClient snsClient = new AmazonSNSClient( credentials );AmazonSQSClient sqsClient = new AmazonSQSClient( credentials );

Topic Creation

Amazon SNS uses topics to route notifications from publishers to subscribers. The term publisher refers to an app that sends notifications; the term subscriber refers to an entity, such as a user, that receives notifications. Topics provide a junction point for publishers and subscribers to communicate with each other. Once a topic is created, subscribers can be added to the topic and receive notifications/messages. The DisplayName attribute is added to a topic to allow notifications to be sent via SMS.

CreateTopicRequest ctr = new CreateTopicRequest( Constants.TOPIC_NAME );CreateTopicResult result = snsClient.createTopic( ctr );	        SetTopicAttributesRequest tar      = new SetTopicAttributesRequest( result.getTopicArn(), "DisplayName", "MessageBoard" );this.snsClient.setTopicAttributes( tar );  

Subscribing to Topics

In order for notifications sent to a topic to be received, you have to subscribe an endpoint to that topic. The endpoint corresponds to a recipient. An endpoint is an e-mail address, SMS number, web server, or Amazon SQS queue. If you are using an Amazon SQS queue, it needs to be configured to receive notification messages from Amazon SNS. Once you subscribe an endpoint to a topic and the subscription is confirmed, the endpoint will receive all messages published to that topic.

SubscribeRequest sr = new SubscribeRequest( this.topicARN, "email", email );this.snsClient.subscribe( sr );

Listing a Topic's Subscribers

Listing the subscribers for a topic provides the endpoint and corresponding protocol for each subscriber who receives notification via that topic. The protocol for an endpoint depends on the type of endpoint. For example, endpoints that are e-mail addresses have a protocol of SMTP.

ListSubscriptionsByTopicRequest ls = new ListSubscriptionsByTopicRequest( this.topicARN );ListSubscriptionsByTopicResult response = this.snsClient.listSubscriptionsByTopic( ls );return response.getSubscriptions();

Publishing Notifications

Publishers send notifications to topics. Once a new notification is published, Amazon SNS attempts to deliver that notification to every endpoint that is subscribed to the topic.

PublishRequest pr = new PublishRequest( this.topicARN, message );this.snsClient.publish( pr );	

Unsubscribing from Topics

Unsubscribing removes the endpoint from the topic and stops notifications from being received.

UnsubscribeRequest unsubscribeRequest = new UnsubscribeRequest( subscriptionArn );this.snsClient.unsubscribe( unsubscribeRequest );

Creating a Queue

The first task in using Amazon SQS is to create a queue. Once a queue is created it can be subscribed as an endpoint to an Amazon SNS topic.

CreateQueueRequest cqr = new CreateQueueRequest( Constants.QUEUE_NAME );CreateQueueResult result = this.sqsClient.createQueue( cqr );return result.getQueueUrl();

Subscribing a Queue to a Topic

Here's how to subscribe a queue to a topic. However, for the queue to receive messages, you must also add a policy to the queue. See below.

String queueArn = this.createMessageQueue();		SubscribeRequest request = new SubscribeRequest();request.withEndpoint( queueArn ).withProtocol( "sqs" ).withTopicArn( this.topicARN );		this.snsClient.subscribe( request );

Adding a policy to a Queue

In order for a queue to receive messages from a topic, the queue must have a policy object that specifies that the topic has sqs:SendMessage permission for the queue. For further details see the Amazon SNS FAQ. For more information about queue policies see the Amazon SQS documentation. Once the policy object is created it can be attached to the queue as follows:

HashMap attributes = new HashMap();attributes.put("Policy", generateSqsPolicyForTopic( queueArn, this.topicARN ) );this.sqsClient.setQueueAttributes(new SetQueueAttributesRequest( queueUrl, attributes ) );

Receiving Messages from a Queue

Now that a message is in the queue, you can receive it, which requires getting it from the queue. When requesting to get a message from the queue, you can't specify which message to get. Instead, you simply specify the maximum number of messages you want to get (up to 10), and Amazon SQS returns up to that maximum number. Because Amazon SQS is a distributed system and the particular queue we're working with here has very few messages in it, the response to the receive request might be empty. Therefore, you should rerun the sample until you get the message. You should design your own app so that it continues to poll the queue until it gets one or more messages.

ReceiveMessageRequest rmr = new ReceiveMessageRequest( this.queueUrl );rmr.setMaxNumberOfMessages( 10 );rmr.setVisibilityTimeout( 30 );ReceiveMessageResult result = this.sqsClient.receiveMessage( rmr );

Delete Messages from a Queue

Amazon SQS doesn't automatically delete a message after returning it to the app. By default, it keeps the message to protect against the case where the receiving app fails or loses its connection. In these cases, a different app—or perhaps a new instance of the same app— might attempt to get the message.

To delete the message, you must send a separate request. You specify which message to delete by providing the receipt handle that Amazon SQS returned when you received the message. You can delete only one message per call. Deleting the message acknowledges that you've successfully received and processed it.

DeleteMessageRequest request      = new DeleteMessageRequest( this.queueUrl, message.getReceiptHandle() );this.sqsClient.deleteMessage( request );

References

A sample app that includes this code is provided with the SDK. The download link can be found on the following page:

For more information about using AWS credentials with mobile apps see the following article:

Questions?

Please feel free to ask questions or provide comments in the Mobile Development Forum.

November 30, 2011

gdierkes

Screen shot 2011-11-29 at 10.40.45 AM

This article highlights the benefits of connecting mobile devices to the cloud while also presenting an Amazon SimpleDB use case. Amazon SimpleDB is a highly available, flexible, and scalable non-relational data store that offloads the work of database administration. The app described here demonstrates how to store a high score list or leader board in SimpleDB. The app enables the user to view the high scores sorted by name or score, add and remove scores, and more. This article shows sample code for the Android platform. The complete sample code and project files are included in the AWS SDK for Android. A link to the SDK is available at the end of this article.

To use the AWS SDK for Android, you will need your AWS credentials, that is, your Access Key ID and Secret Access Key. If you haven't already signed up for Amazon Web Services (AWS), you will need to do that first to get your AWS credentials. You can sign up for AWS here. After you have signed up, you can retrieve your credentials at this page.

Overview

SimpleDB stores data in domains. Each domain is a collection of items and each item is a collection of attribute/value pairs. For the app, we create a single domain to store our high score list. Each item in the domain represents an individual player. The items will have two attributes, the player's name and their score. Items also have a unique identifier called the item name that, in this case, is equal to the player's name. Storing the player's name and score as item attributes enables us to sort the items by name or score.

The app demonstrates how to add and remove individual players, sort the scores by player name or score, and retrieve a single item from the domain. The app also demonstrates how to create and delete SimpleDB domains.

Creating a SimpleDB Client

Making requests to SimpleDB requires a client. Creating a SimpleDB client for Android is shown below.

AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY_ID, SECRET_KEY);AmazonSimpleDBClient sdbClient = new AmazonSimpleDBClient( credentials);

High Score List Creation (Domain Creation)

Individual player scores are stored as items in a SimpleDB domain. This requires that we create the domain first. Using the appropriate client that we created above, we can use the following code to create the domain.

CreateDomainRequest cdr = new CreateDomainRequest( HIGH_SCORES_DOMAIN );sdbClient.createDomain( cdr );

Add Score (Item Creation)

An item is a collection of attribute/value pairs. For our items, we create two attributes, one for the player's name and one for the player's score. These are added to a request along with an item name in order to create the item. Because a player appears at most only once on the high score list, we use the player's name to uniquely identify each item. All data in SimpleDB are stored as strings, therefore numbers must be zero padded if you want to sort them properly. The AWS SDK for Android includes a utility to pad numbers, used below.

String paddedScore = SimpleDBUtils.encodeZeroPadding( score, 10 );		ReplaceableAttribute playerAttribute =     new ReplaceableAttribute(PLAYER_ATTRIBUTE, player, Boolean.TRUE);ReplaceableAttribute scoreAttribute =     new ReplaceableAttribute(SCORE_ATTRIBUTE, paddedScore, Boolean.TRUE);		List attrs = new ArrayList(2);attrs.add( playerAttribute );attrs.add( scoreAttribute );		PutAttributesRequest par = new PutAttributesRequest(HIGH_SCORES_DOMAIN, player, attrs);		sdbClient.putAttributes( par );

Remove Score (Item Deletion)

Removing a score from the list simply means deleting an item from the domain. Deleting an item requires the unique name for the item you wish to delete. In SimpleDB, deleting an item is done by removing all the attributes from that item. Invoking deleteAttributes with no specified attributes removes all the attributes by default.

DeleteAttributesRequest dar = new DeleteAttributesRequest( HIGH_SCORES_DOMAIN, player );sdbClient.deleteAttributes( dar );

Player View (Getting an Item)

Knowing an item's name makes it easy to find the item. This next snippet shows how to get all the attributes for an item using the item name. Note that items may contain many attributes and values.

GetAttributesRequest gar = new GetAttributesRequest( HIGH_SCORES_DOMAIN, player );GetAttributesResult response = sdbClient.getAttributes(gar);

List View and Sorting (Select)

Getting a collection of scores, sorted by player name or the score itself requires the use of a select request. A select request uses a simple query language to determine which items to match and what data to return and how. Select requests are paginated because the number of items matching the query can be large. Therefore, select requests return a next token that enables you to "page" through the data in an ordered fashion. The code here shows how to return items ordered by score from highest to lowest. Only the score and player attributes are returned. More information regarding SimpleDB queries can be found in a reference article linked below.

String select = "select player, score from HighScores where score >= '0' order by score desc";SelectRequest selectRequest = new SelectRequest( select ).withConsistentRead( true );selectRequest.setNextToken( nextToken );		SelectResult response = sdbClient.select( selectRequest );nextToken = response.getNextToken();

List Deletion (Domain Deletion)

The quickest and easiest way to remove the entire high score list would be to delete the SimpleDB domain. Here is how to do that.

DeleteDomainRequest ddr = new DeleteDomainRequest( HIGH_SCORES_DOMAIN );sdbClient.deleteDomain(ddr);

Conclusion

The code in this article demonstrates how to use Amazon SimpleDB as an indexed storage device for your app. The complete sample app is included as part of the AWS mobile SDKs, which are linked below. The reference section also contains a link to a SimpleDB article which discusses writing queries for SimpleDB in detail.

References

Find more information about SimpleDB here.

A sample app that includes this code is provided with the AWS SDK for Android

For more information about using AWS credentials with apps see the article, Authenticating Users of AWS Mobile Applications with a Token Vending Machine
 

Questions?

Please feel free to ask questions or provide comments in the Mobile Development Forum.

November 10, 2011

gdierkes

This article demonstrates how to use the AWS SDK for Android to uploadan image to Amazon Simple StorageService (S3) from your mobile device and how to make that imageavailable on the web. Amazon S3 is storage for the Internet. It's a simplestorage service that offers software developers a highly-scalable,reliable, secure, fast, and inexpensive data storage. The complete samplecode and project files are included in the AWS SDK for Android which canbe found here.

To use the AWS SDK for Android, you will need your AWS credentials,that is, your Access Key ID and Secret Access Key. If you haven'talready signed up for Amazon WebServices (AWS), you will need to do that first to get your AWScredentials. You can sign up for AWS here.

Here's what the sample app looks like at start up on Android:

Android-Uploader

Photo Upload

The app uses each platform's "image picker" utility to have theend-user select an image for upload. The app then creates an Amazon S3client, uses the client to create an Amazon S3 bucket in which to storethe image, and finally uploads the image into the bucket. A bucket is acontainer for objects stored in Amazon S3. Every object--such as animage--is contained within a bucket.      

Get the image

The first step is to retrieve the content, in this case an image, tobe uploaded to Amazon S3. For this sample app, selecting an image from thedevice itself is an easy choice.

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);intent.setType("image/*");startActivityForResult(intent, PHOTO_SELECTED);

Android-Image-Picker

Once an image is selected, a callback method is invoked with theselected image's information. The app uses this information to completethe upload.

Upload the image

Once we have the image, we can attempt to upload it to Amazon S3.

First, create an Amazon S3 client to communicate withthe service.

AmazonS3Client s3Client =   new AmazonS3Client( new BasicAWSCredentials( MY_ACCESS_KEY_ID, MY_SECRET_KEY ) );

Second, create an Amazon S3 bucket to store thepicture.

s3Client.createBucket( MY_PICTURE_BUCKET );

Finally, put the image object into the Amazon S3bucket.

PutObjectRequest por =    new PutObjectRequest( Constants.getPictureBucket(),                          Constants.PICTURE_NAME,                          new java.io.File( filePath) );s3Client.putObject( por );

Browser Display

The app makes the image available for viewing in a browser bygenerating a pre-signed URL. A pre-signed URL is a URL for an Amazon S3resource that is signed with current AWS security credentials. Thepre-signed URL can then be shared with other users, allowing them toaccess resources without providing an account's AWS securitycredentials.

First, create an override content type to ensure thatthe "content" will be treated as an image by the browser.

ResponseHeaderOverrides override = new ResponseHeaderOverrides();override.setContentType( "image/jpeg" );

Second, create the pre-signed URL request. Pre-signedURLs can be created with an expiration date, that is, a date andtime after which the resource will no longer be available. In the sample,the pre-signed URLs are valid for only one hour.

GeneratePresignedUrlRequest urlRequest =    new GeneratePresignedUrlRequest( Constants.getPictureBucket(),                                     Constants.PICTURE_NAME );// Added an hour's worth of milliseconds to the current time.urlRequest.setExpiration(    new Date( System.currentTimeMillis() + 3600000 ) );urlRequest.setResponseHeaders( override );

Third, generate the pre-signed URL. 

URL url = s3Client.generatePresignedUrl( urlRequest );

Finally, launch the browser to view the pre-signed URLwhich will display the image. 

startActivity(    new Intent( Intent.ACTION_VIEW, Uri.parse( url.toURI().toString() ) ));

Android-ShowPic

Next Steps

These few lines of code demonstrate how Amazon S3 could become alimitless storage device for your mobile photos. A photo sharing app thatallows users to view photos from other users would not be a difficultextension to the above code. Also, the content that is uploaded and sharedis not limited to images. The content could be audio files, video files,text, or other content that users want to store and share. 

References

A sample app that includes this code is provided with both mobile SDKs.The download links can be found here: AWS SDK for Android.

For more information about using AWS credentials with mobileapplications see the following article: Authenticating Users of AWS Mobile Applications with a Token VendingMachine

Questions?

Please feel free to ask questions or make comments in the MobileDevelopment Forum.

Portions of this page are reproduced from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.

Want the latest?

appstore topics

Recent Posts

Archive