Expert AWS Development

2.3 (3 reviews total)
By Atul V. Mistry
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. AWS Tools and SDKs

About this book

Continuous deployment and Agile methodology have enabled huge advances in modern applications. This book will enable the reader to make use of this rapidly evolving technology to build highly scalable applications within AWS using different architectures.

You will begin with installation of AWS SDK and you will get hands-on experience on creating an application using AWS Management Console and AWS Command Line Interface (CLI). Next you will be integrating Applications with AWS services such as DynamoDB, Amazon Kinesis, AWS Lambda, Amazon SQS and Amazon SWF

Following this you will get well versed with CI/CD workflow and work with four major phases in Release processes – Source, Build, Test and Production. Next you will learn to apply AWS developer tools in your Continuous Integration (CI) and Continuous Deployment (CD) WorkFlow. Later you will learn about User Authentication using Amazon Cognito and also how you can evaluate the best architecture as per your infrastructure costs. You will learn about Amazon EC2 service and deploy an app using Amazon EC2.You will also get well versed with container service which is Amazon EC2 Container Service (Amazon ECS) and you will learn to deploy an app using Amazon ECS. Along with EC2 and ECS, you will also  deploying a practical real-world example of a CI/CD application with the Serverless Application Framework which is known as AWS Lambda.  Finally you will learn how to build, develop and deploy the Application using AWS Developer tools like AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy and AWS CodePipeline as per project needs. Also you can develop and deploy applications within minutes using AWS CodeStar from wizard.

By the end of this book, the reader will effectively build, deploy, and manage applications on AWS along with scaling and securing applications with best practices and troubleshooting tips.

Publication date:
March 2018
Publisher
Packt
Pages
408
ISBN
9781788477581

 

Chapter 1. AWS Tools and SDKs

Most probably, if you are reading this book, you are a code-drink lover who is trying to explore or probably using Amazon Web Services (AWS). AWS contains around 20 different kinds of category/product, which have 110+ services. In this chapter, we will explore AWS tools and SDKs, which are under the Developer tools category of AWS products.   

In the software world, a software development kit is known asSDK. It includes software development tools that allow you to create applications, software packages, frameworks, computer systems, gaming consoles, hardware platforms, operating systems, or similar kinds of software/hardware development platforms. Some SDKs are useful for developing platform-specific applications; for example, for Android applications on Java, you need the Java Development Kit(JDK) and for iOS applications, you need the iOS SDK. This is the basic idea of SDKs.

AWS also provides primary developer tools, command-line tools, toolkits, and SDKs to develop and manage AWS applications. It provides a variety of tools and SDKs as per the programming knowledge and project needs. With the help of these tools and SDKs, you can quickly and easily build and manage great applications on the AWS Cloud. This chapter will show you how to install and use these SDKs for different programming languages.

By the end of this chapter, you will understand how to install AWS SDKs and use them for development in different programming languages.  

This chapter will cover the following topics: 

  • Brief introduction to AWS tools and SDKs
  • AWS SDK for Java
  • AWS SDK for Java using Apache Maven
  • Configuring an SDK as a Maven dependency
  • AWS SDK for Java using Gradle
  • AWS SDK for Java using Eclipse IDE
  • AWS SDK for Node.js
 

Brief introduction to AWS tools and SDKs


As we discussed in the introduction, AWS provides developer and command-line tools, toolkits, and SDKs to develop and manage AWS applications. Currently, AWS provides nine SDKs for different programming languages, six SDKs for IoT devices, and five SDKs for mobile devices. Let's take a brief look at this:

  • Developer tools: Developer tools are used to store source code securely and version-control it. They also help with build automation and testing and deploying applications to AWS or on-premise. They include the AWS CodeCommit, AWS CodePipeline, AWS CodeBuild, and AWS CodeDeploy services. We will cover these in Chapter 4, CI/CD in AWS Part 1 – CodeCommit, CodeBuild, and Testing and Chapter 5, CI/CD in AWS Part 2 – CodeDeploy, CodePipeline, and CodeStar.
  • SDKs: They provide APIs for programming languages, IoT, and mobile devices.
  • IDE toolkits: Cloud tools which can integrate to your integrated development environment to speed up your AWS development.
  • Command line: This is used to control AWS services from the command line and create scripts for automated service management.
  • Serverless development: Serverless applications built on AWS Lambda can test and deploy using AWS Serverless Application Model (SAM) and SAM Local. We will cover Amazon Lambda in Chapter 10, Amazon Lambda – AWS Serverless Architecture.

AWS provides SDKs for the different languages and hardware devices to connect AWS IoT and mobile devices.

The following are the different kinds of SDK. In this chapter, we will cover two programming language SDKs, Java and Node.js:

AWS SDK for Java

Let's start with the Java SDK. This SDK helps to minimize the complexity and provision to coding using Java APIs for AWS Services such as Amazon EC2, Amazon DynamoDB, Amazon S3, and many more. You can download a single package from the AWS website which includes the AWS Java library and code samples with documentation.

Currently, you can download the AWS SDK for Java v1.11.x code base and AWS has recently launched an AWS SDK for Java v2.0, which is major code change. This version is built on Java 8. It has added features such as non-blocking I/O and a pluggable API layer (by default, it will use Apache but you can change this as per your project needs). In this version, you can see some API changes:

  • Client builders are the only way to create the client services, which means the clients are immutable after creation
  • All Plain Old Java Objects (POJOs) are immutable and must be created from the builder
  • Many region classes such as Region, Regions, and RegionUtils are merged into a single Region class

Note

This AWS SDK for Java v2.0 is a developer preview version and not recommended for production use.

Let's explore how to install, set up, and use AWS SDK for Java.

 You need to set up AWS SDK for Java on your machine to use in your project. Please perform the following steps to set up the environment and run the sample code in Java using the AWS SDK:

  1. AWS account setup and IAM user creation: You have to set up an AWS account and credentials to use AWS SDK. To increase the level of security for your AWS account, it is always preferable to create an IAM user. Use the created IAM user instead of the root user. Once you create an IAM user, you have to create an access key. You can download or view the access key ID and secret access key in the resulting dialog box. It's always best practice to download and store them in your local environment.
  2. AWS credentials and region setup: For your local application development, you need to set up credentials and regions.

The AWS credentials profile file is located in your filesystem. It should be at the following path:

    • For Linux, macOS, or Unix: ~/.aws/credentials
    • For Windows: C:\Users\USERNAME\.aws\credentials

The file format should be as follows:

[default]
aws_access_key_id = downloaded_access_key_id
aws_secret_access_key = downloaded_secret_access_key

Another alternative is to set up AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables. Now, replace your AWS access key ID and secret access key for the values of downloaded_access_key_id and downloaded_secret_access_key.

The AWS region configuration file is located in your filesystem. It should be at the following path:

    • For Linux, macOS, or Unix: ~/.aws/config
    • For Windows: C:\Users\USERNAME\.aws\config

This file format should be as follows:

[default]
region = your_region_name

Now, replace your AWS region for the value or region. Another alternative is you can set up AWS_REGION as an environment variable.

  • Java Development Environment: JDK 6.0 or later versions are required for the AWS SDK. The latest JDK versions are available for download from the Oracle website. J2SE 6.0 does not support SHA 256-signed SSL certificates, which are required for all HTTP connections with AWS after September 2015. You can use J2SE7.0 or newer versions, which are not affected by the certificate issue.

You can use different methods to include the AWS SDK for your Java project. We will explore all methods in this chapter:

    • Apache Maven: You can use specific SDK components or the full SDK with the help of Apache Maven.
    • Gradle: Maven Bill of Materials (BOM) in a Gradle project can be used to automatically manage the dependency for your project.
    • Eclipse IDE: The AWS toolkit can be integrated into an existing Eclipse IDE. It will automatically download, install, and update the Java SDK with a few settings.

AWS SDK for Java using Apache Maven

Please perform the following steps to include AWS SDK for Java using Apache Maven.

  1. Assuming that you have already installed Maven in your machine, create a new folder called AWS SDK Example or any name. Go to this folder and execute the following command to set up the environment:
mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart
  1. After it has successfully executed, you will see the following folder structure under the AWS SDK Example folder:

    

You will see the pom.xml file generated under the ..\AWS SDK Example\java-maven-demo folder.

Configuring an SDK as a Maven dependency

Please perform the following steps to configure AWS SDK as Maven dependency.

  1. To add AWS SDK for Java in your project, you need to add the dependency to the pom.xml file. From SDK version 1.9.*, you can import single or individual components. If you want to add the entire SDK as a dependency, add the following code in the <dependency> tag in the pom.xml file:
  <dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>1.11.106</version>
  </dependency>
  1. If you are using SDK Version 1.9.* or above, you can import many individual components, such as EC2, S3, CodeCommit, or CodeDeploy:
  <dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-s3</artifactId>
  </dependency>
  1. After setting up the pom.xml file, you can build your project with the mvn package command. It will generate a Java Archive (JAR) file in the target directory after successful execution:
  1. Now you need to add the following code in the pom.xml file to connect with the AWS SDK. You have to mention your main Java class under the Configuration | mainClass tag. We will create the S3MavenExample.java file in the next step:
<build>
       <resources>
           <resource>
               <directory>${env.HOME}/.aws/</directory>
           </resource>
       </resources>
       <plugins>
           <plugin>
               <groupId>org.codehaus.mojo</groupId>
               <artifactId>exec-maven-plugin</artifactId>
               <version>1.2.1</version>
               <executions>
                   <execution>
                       <goals>
                           <goal>java</goal>
                       </goals>
                   </execution>
               </executions>
               <configuration>
              <mainClass>com.packt.example.S3MavenExample</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
  1. Let's create the S3MavenExample.java file in the com/packt/example package. We are going to create an S3 bucket as per the specific region with a random number generator, prefix it with s3-maven-bucket-, and then delete the bucket:
import java.util.UUID;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
  1. You have imported UUID to generate the pseudo random number. You are importing Region and Regions to create the bucket in a specific region, and AmazonS3 and AmazonS3Client to access the AWS S3 services:
AmazonS3 s3 = new AmazonS3Client();
Region s3Region = Region.getRegion(Regions.AP_SOUTHEAST_1);
s3.setRegion(s3Region);
  1. Here you are creating an S3 client and specifying the specific region where it will create the bucket:

Note

If you do not specify any region, it will create it at US East (N. Virginia). This means the default region is US East (N. Virginia).

String bucketName = "s3-maven-bucket-" + UUID.randomUUID();
  1. Here you are creating the s3-maven-bucket- prefix with some random UUID:
s3.createBucket(bucketName);
  1. To create the bucket, you can use createBucket() method. You have to pass the bucket name as a parameter in this method:
s3.deleteBucket(bucketName);
  1. To delete the bucket, you can use the deleteBucket() method. You have to pass the bucket name as a parameter in this method. After creating the Java file, execute the following command:
mvn clean compile exec:java

It will create and delete the bucket as per the specified regions:

If you have completed this step and you can see the creation and deletion of the bucket, it means you have successfully completed AWS SDK for Java using Maven in your project.

AWS SDK for Java using Gradle

Please perform the following steps to include AWS SDK for Java using Gradle:

  1. Assuming that you have already installed Gradle in your machine, create a new folder called java-gradle-demo or any other name. Go to this folder and copy the following files:
    • The gradle folder: Contains necessary files for the wrapper
    • build.gradle: Gradle build file
    • gradlew: Gradle startup script for Unix
    • gradlew.bat: Gradle startup script for Windows:
  1. Now execute the following command:
gradlew.bat

After completing this execution, you can see the .gradle folder.

  1. Now you need to update your build.gradlew file to connect with AWS:
apply plugin: 'java'
apply plugin: 'application'

mainClassName="com.packt.example.S3GradleExample"
repositories {
    mavenCentral()
}
dependencies {
    compile 'com.amazonaws:aws-java-sdk:1.9.6'
}
  1. Let's create a S3GradleExample.java file under the com.packt.example folder. This is the same file as S3MavenExample.java:
package com.packt.example;
import java.util.UUID;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
public class S3GradleExample {
    public static void main(String[] args) {
        AmazonS3 s3 = new AmazonS3Client();
        Region s3Region = Region.getRegion(Regions.AP_SOUTHEAST_1);
        s3.setRegion(s3Region);
       String bucketName = "s3-gradle-bucket-" + UUID.randomUUID();
        System.out.println("Amazon S3 will create/delete bucket");
        // Create a new bucket
        System.out.println("Creating bucket " + bucketName + "\n");
        s3.createBucket(bucketName);
        // Delete a bucket.
        System.out.println("Deleting bucket " + bucketName + "\n");
        s3.deleteBucket(bucketName);
    }
}
  1. After creating the Java file, execute the following command:
gradlew clean build run

It will create and delete the bucket as per the specified regions:

AWS SDK for Java using Eclipse IDE

I am assuming that you have already installed Eclipse 4.4 (Luna) or a higher version on your machine as the AWS toolkit supports that.

There are two ways to install an AWS toolkit in your IDE:

  • Click on Help | Install New Software… and install
  • Click on Help|Eclipse Marketplace, search forAWS, and install

We will install using the first method. Now please perform the following steps and refer to the following screenshot:

  1. Once you click on Install New Software, it will open the Available Software dialog box.
  2. In this dialog box, you have to click on Add to add the AWS toolkit.
  3.  It will open the Add Repository dialog box.
  4.  In this dialog box, add the Name and Location as https://aws.amazon.com/eclipse.
  5.  Click on OK.
  1. On the next page, you will see all available AWS tools. You can select AWS Core Management Tools and other tools as per your project requirements:
  1. A preview page will display to confirm the installation details. Click on Next and you will see the Review License page, where you click Accept and Finish to complete the AWS installation:
  1. After successful installation, your IDE will restart. After restarting, you will see the AWS toolkit icon in the toolbar:
  1. Now let's create a sample AWS Java project. When you click New AWS Java Project…., you will see the following screen. You need to add the necessary details for the project. Here I have used S3Demo as my Project name, com.packt as my Group ID, and examples as my Artifact ID. I have selected Amazon S3 Sample from the Java samples:
  1. If you want to add new AWS accounts, click on the Configure AWS accounts… link. You can add the credentials in two ways:
    • Add Profile Name, Access Key ID, and Secret Access Key under the Profile Details screen.
    • You can specify your credentials file path or browse to your credentials file. Once you have added that, you can select Apply and Close:
  1. Now it will generate the projects and create the necessary files. You can see the following screen with generated files. It will generate a S3Sample.java file. You can right-click on this file and select Run As | Java Application. It will create the bucket, list the bucket, upload a new object to S3, download an object, list an object, delete an object, and delete the bucket:

So far, you have learned how to add the AWS Java toolkit into your project using Maven, Gradle, and Eclipse IDE. Now we will see how to add the AWS SDK for Node.js into your project.

AWS SDK for Node.js

Node.js is a free, open source, cross-platform framework. It is used to execute JavaScript code on the server side. In Node.js, you can use AWS SDK for JavaScript. This SDK will help to remove the complexity of coding by providing JavaScript objects to use the AWS services. A single downloaded package includes the AWS JavaScript library as well documentation.

You can install AWS SDK for Node.js in two ways:

  • From GitHub: You can get the source code from https://github.com/aws/aws-sdk-js
  • From Node.js Package Manager (npm): You can install AWS SDK from the Node.js package manager

Let's install the AWS SDK package and create a sample application to create and delete a bucket on S3 using the following steps:

  1. You can download (https://nodejs.org/en/download/) and install Node.js If you haven't already installed it. Once you have installed Node.js, you can open the Node.js command prompt from (Run | Node.js command prompt in Windows.
  2. You need to create a package.json file to mention the required dependency to install AWS SDK and UUID. We need aws-sdk to install the required Node modules for AWS services and a UUID to create a pseudo random number:
package.json
{
    "dependencies": {
        "aws-sdk": ">= 2.0.9",
        "uuid": ">= 1.4.1"
    }
}
  1. Now open the command prompt and execute the following command:
npm install aws-sdk
  1. It will create a node_modules folder and install AWS SDK for Node.js. Now you need to set the credentials in the AWS credentials profile file on your local system, located at the following:
    • For Linux, macOS, or Unix: ~/.aws/credentials
    • For Windows: C:\Users\USERNAME\.aws\credentials
  2. The file format should be as follows:
[default]
aws_access_key_id = downloaded_access_key_id
aws_secret_access_key = downloaded_secret_access_key
  1. Now, replace your AWS credentials values with the values downloaded_access_key_id and downloaded_secret_access_key.
  2. Now let's create a S3Example.js file which will connect to AWS and create and delete the bucket on S3:
var AWS = require('aws-sdk');
var uuid = require('uuid');
  1. First, you have to create variable such as AWS and UUID to load SDK for JavaScript:
var s3 = new AWS.S3();
var bucketName = 'node-sdk-sample-' + uuid.v4();
var params={Bucket: bucketName}

Here you are creating s3 as an S3 service object, bucketname with node-sdk-sample as the prefix with a random number, and params as the parameters to call the bucket:

s3.createBucket(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else console.log("Successfully Created Bucket: "+bucketName); 
   // successful response
 });

The preceding method is used to create the bucket with parameters and callback functions:

s3.waitFor('bucketExists', params, function(err, data) {
 if (err) console.log(err, err.stack); // an error occurred
  else {
      s3.deleteBucket(params, function(err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else console.log("Successfully Deleted Bucket:"+bucketName);         
        // successful response
      });
  } 
});

Here it will check whether the bucket is exists or not. If it exists then it will delete the bucket. If it is not exist than it is trying to delete the bucket which is not created yet. In that case, you will get an error.

  1. You can execute the file with node S3Example.js and you can see that it will create and delete the bucket:

Previously, we discussed AWS SDKs for different programming languages and we have covered Java and Node.js with setup and examples. Now we will see how you can set up SDKs on IoT devices.

 

AWS SDKs for IoT devices


IoT is the Internet of Things, where the internet is connected with things such as software, hardware, physical devices, home appliances, vehicles, or any kind of sensor, actuator, or network, and exchanges data between them. In simple terms, your thing or device will collect, sense, and act on data and send it to an other device from the internet. These connected devices are communicating with each other from various technologies and flow data autonomously. IoT devices can be useful for consumer applications, enterprise applications, smart homes, agriculture, and many industries.

AWS provides different kinds of SDK for the IoT to connect securely and seamlessly to your hardware devices.

The following are the different kinds of AWS SDK:

AWS SDKs for mobile devices

AWS provides different kinds of SDKs to connect securely and seamlessly to your mobile devices.

The following are the different kinds of AWS SDKs. In this chapter, we will cover AWS SDK for Android:

AWS Mobile SDK for Android

For Android, AWS provides an open source SDK that is distributed under an Apache license. This will provide libraries, code examples, and documentation to develop mobile applications using AWS.

Currently, AWS supports the following services for AWS Mobile SDK for Android:

  • Amazon Cognito Identity:
    • Controls authentication and provides temporary credentials to connect devices and/or other untrusted environments
    • Saves user data and synchronizes it
    • Manages identity throughout the lifetime of an application
    • We will discuss this topic in more detail in Chapter 6, User Authentication with AWS Cognito
  • Amazon Cognito Sync:
    • Enables application-specific data to sync on cross-devices
    • Syncs user data across the web and devices
    • Caches data locally so the device can access data offline; it can sync when the device is online
    • Notifies other devices if sync push is set up
  • Mobile Analytics:
    • Collects, analyzes, visualizes, and understand the apps
    • Generates reports for users, sessions, in-app revenues, and events
    • Filters reports by data range and platform
  • Amazon S3:
    • Mobile apps can directly access Amazon S3 to store data
    • Provides Transfer Utility/Transfer Manager (Older Version) to consume S3 services
  • DynamoDB:
    • SDK contains a high-level library to access and work with DynamoDB Object Mapper
    • Can perform CRUD operations such as Create, Read, Update, and Delete for client-class
  • Amazon Kinesis:
    • Provides simple, high-level design
    • Stores real-time data on disk and sends it all together to save battery life
  • Lambda:
    • Lambda function receives app and device data to create a personalized and rich app experience
  • Amazon Lex:
    • You can integrate a chat box on mobile devices
  • Amazon Polly:
    • Mobile SDK provides add text to speech integration for Amazon Polly
  • Amazon Pinpoint:
    • Integrates Amazon Pinpoint to send push notification campaigns from Android apps

Note

Currently, Android 2.3.3 (API level 10) or higher can use AWS Mobile SDKs.

Now let's understand how to set up the AWS Mobile SDK and then we will see an example with Amazon S3.

The AWS Mobile SDK is available at the following two resources for download:

This SDK includes class libraries, code example, and documentation:

  • Class libraries will include the Java Archive Files (.jar) files for the AWS services. You can include the class for the service which you are using in your applications.
  • The code example provides you with an example of using the service in your application using class libraries.
  • Documentation is reference material for the use of AWS Mobile SDK for Android.

Note

AWS Secure Token Service (STS) and Amazon Cognito Identity are bundled with the AWS Mobile SDK core library. You will get a compile-time error if you include it as a separate JAR file.

In the next section, you will see how to set up AWS Mobile SDK for Android.

AWS Mobile SDK setup for Android

With the help of the AWS Mobile SDK, you can create a new project or update an existing project.

The following are prerequisites:

You need to do the following configuration:

  • Configure AWS Mobile SDK for Android
  • Set permissions in the Android manifest file
  • Use Amazon Cognito to set the AWS credentials

Now let's explore the entire configuration step by step and make changes accordingly.

Configuring AWS Mobile SDK for Android

Let's start configuring AWS Mobile SDK for Android in the following three ways:

  • Using Maven: Apache Maven is a build automation and dependency management tool, which contains a pom.xmlfile for configurations. It is used to mention the specific Amazon web service which you will use in the project instead of the entire SDK.

Note

Amazon Mobile SDK for Android v 2.1.3 or above supports Maven.

In the pom.xml file, you have to add a <dependency> element in which you have to add three subelements such as groupid, artifactid, and version.

groupid will be the same as com.amazonaws for all AWS services.

In artifactid, you have to mention the appropriate service which you are using in your applications.

In version, you have to mention the acceptable AWS Mobile SDK version for Android for the given dependency:

  • Using Gradle: When using Android Studio, you can add additional individual services with aws-android-sdk-core services as a dependency in your build.gradle file:

        

Note

Avoid + in version numbers. Use com.amazonaws:aws-android-sdk-core:#.#.# instead of com.amazonaws:aws-android-sdk-core:#.#.+.

  • Import JAR files: As mentioned previously, you can download the AWS Mobile SDK from the AWS website or GitHub and use it into your project.

In Android Studio, you can add the AWS Mobile SDK JAR file in your application by dragging it into the Project View. You can also add the individual JAR file for your services. It will add it to the build path automatically. Then use the Gradle file to sync your project.   

Note

Set a permission in the Android manifest file. In your AndroidManifest.xml file, you need to set the following permission: <uses-permission android:name="android.permission.INTERNET" />.

Using Amazon Cognito to set AWS credentials

You have to use Amazon Cognito Identity Provider to obtain AWS credentials. Those credentials you can use in your mobile application to access AWS services. You can also set user-specific permissions to access particular AWS services. You don't have to embed personal credentials. Amazon Cognito will be covered in more detail in Chapter 6, User Authentication with AWS Cognito.

So far, we have covered AWS SDK for IoT and AWS Mobile SDK for Android. Let's explore an example for the Transfer Utility to consume Amazon S3 services. Here we will upload a file from a mobile device and download a file to a mobile device. We will use Android Studio, Amazon Cognito, Amazon S3, and Amazon IAM. Please perform the following steps:

  1. Start Android Studio and create a new project. Add the required information and click Next:
  1. Select the Target Android Devices. Here I have selected Phone and Tablet and the API version is 15, which supports 100% of devices:
  1. Select the activity as per your project needs:
  1. In the Configure Activity screen, you can change the Activity Name and Layout Name or you can keep them as they are:
  1. You can see the following screen after successfully creating the project:
  1. Open the app/build.gradle file and add the following modules as dependencies for the AWS Mobile SDK:
compile 'com.amazonaws:aws-android-sdk-core:2.6.6'
compile 'com.amazonaws:aws-android-sdk-cognito:2.6.6'
compile 'com.amazonaws:aws-android-sdk-s3:2.6.6'
  1. Amazon S3 will transfer files using the TranferUtility service. For that, open the app/manifests/AndroidManifest.xml file and add the TransferUtility service in the application:
<service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
android:enabled="true" />
  1. Add the following permissions under the manifest tag, which will give you permission to upload and download files from the internet through Android devices:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACTION_DOWN"/>
<uses-permission android:name="android.permission.SMARTBONDING_FEATURE_ENABLED" />
  1. To access Amazon services from your mobile applications, you have to configure the AWS credentials. Amazon Cognito is used as the credential provider. You have to create the identity pool under the Federated Identities in Amazon Cognito and provide the IAM role. You have to create two roles, one for authenticated users and another for unauthenticated users, and provide the following policy. We will cover user authentication with Amazon Cognito in more detail in Chapter 6, User Authentication with AWS Cognito:
{
    "Version": "2012-10-17",
    "Statement": [{
        "Sid": "Stmt1510936216000",
        "Effect": "Allow",
        "Action": ["s3:*"],
        "Resource": ["arn:aws:s3:::<Bucket_Name>/*"]
    }]
}
  1. To enable file upload and download to and from S3, we need to create a button and add an onClick event. You have to add the following code into your acitvity_main.xml file:
<Button
    android:id="@+id/upload_file"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="File Upload to S3"
    android:onClick="uploadFile"/>

<Button
    android:id="@+id/downaload_file"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="File Download from S3"
    app:layout_constraintLeft_toRightOf="@id/upload_file"
    android:onClick="downloadFile"/>
  1. You need to add following imports in the MainActivity.java file to use the Amazon Cognito, Amazon S3, and TransferUtility services:
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
  1. You need to create an instance of S3 and TransferUtility. You need to specify the file path for upload and download:
AmazonS3 s3Client;
TransferUtility transferUtility;
File uploadFilePath = new File(<FILE_UPLOAD_PATH>);
File downloadFilePath = new File(<FILE_DOWNLOAD_PATH);
  1. The onCreate method will initialize the activity. Add the following method for Cognito credentials and Transfer Utility:
getCognitoCredentials();
createTransferUtility();
  1. The following method will create Cognito credential providers. You can pass the Android context, Identity Pool, and region to create the instance:
Public void getCognitoCredentials(){
    CognitoCachingCredentialsProvider credentials

 = new CognitoCachingCredentialsProvider(
            getApplicationContext(),
            <Identity_Pool_ID>,
            Regions.<Your_Cognito_IdentityPool_Region>
    );
    createS3Client(credentials);
}
  1. The following method will create the Amazon S3 client where you have to pass Cognito credentials and set your bucket region:
public void createS3Client(CognitoCachingCredentialsProvider credentials){
    s3 = new AmazonS3Client(credentials);
    s3.setRegion(Region.getRegion(Regions.US_EAST_1));
}
  1. The following method will create a Transfer Utility instance. Note that TransferUtility is used to upload a single file in multiple parts using multiple threads. It is useful for uploading large files mentioning the file path than stream:
public void createTransferUtility(){
    transferUtility = new TransferUtility(s3, getApplicationContext());
}
  1. The following method will be used to upload files from transferUtility's upload. You have to specify the bucket name, filename, and upload file path:
public void uploadFile(View view){

    TransferObserver transferObserver = transferUtility.upload(
            "<S3_Bucket_Name>", 
            "<Upload_File_Key_Name>", 
            uploadFilePath 

    );
}
  1. The following method will be used to download files from transferUtility's download. You have to specify the bucket name, filename, and download file path:
public void downloadFile(View view){

    TransferObserver transferObserver = transferUtility.download(
            "<S3_Bucket_Name>",

           "<Download_File_Key_Name>",
            downloadFilePath 
    );
}
  1. You will see the following screen on your mobile device after successfully running the application:

When you tab on FILE UPLOAD TO S3, if the file is uploaded successfully, you can see it in your S3 bucket from the console:

 When you click on FILE DOWNLOAD FROM S3, if the file is downloaded successfully, you can see it in your folder or path: 

 

Summary


So far, we have completed the setup of AWS SDK on Java and Node.js with examples. This is a good starting point for developers who have a limited knowledge of AWS SDKs.

In the next chapter, you will see how to integrate applications with relevant AWS services such as DynamoDB, Amazon Kinesis, AWS Lambda, Amazon SQS, and Amazon SWF.

 

About the Author

  • Atul V. Mistry

    Atul V. Mistry holds all three AWS Associate certifications and has been a winner at AWS IoT HackDay, 2017 event in Singapore. He has worked consistently with AWS and on software design and development with JEE technology. He has diverse work experience, having worked around the globe, and participated extensively in cross-functional project delivery in the finance industry.

    Browse publications by this author

Latest Reviews

(3 reviews total)
I was able to write one application on AWS. But I didn't use this bokk
Not a good book..Provide proper explanation
Very good prices for well written books. Books sold in packags helps to visualize the topic subjects.
Book Title
Access this book, plus 7,500 other titles for FREE
Access now