Book Image

Expert AWS Development

By : Atul Mistry
Book Image

Expert AWS Development

By: Atul Mistry

Overview of this book

Expert AWS Development begins with the installation of the AWS SDK and you will go on to get hands-on experience of creating an application using the AWS Management Console and the AWS Command Line Interface (CLI). Then, you will integrate 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 the release process – Source, Build, Test, and Production. Then, you will learn to apply AWS Developer tools to 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 will deploy an app using it. You will also deploy 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 such as AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline, as per your project requirements.
Table of Contents (16 chapters)
Title Page
Packt Upsell
Contributors
Preface
Index

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 6User 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: