Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
language: java
jdk:
- oraclejdk8
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
# aws-java-sdk-examples
# aws-java-sdk-examples
[![Build Status](https://travis-ci.org/amol-can/aws-java-sdk-examples.svg?branch=develop)](https://travis-ci.org/amol-can/aws-java-sdk-examples)
61 changes: 61 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.amazonaws</groupId>
<artifactId>samples</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.507</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>amazon-kinesis-client</artifactId>
<version>1.2.1</version>
<scope>compile</scope>
</dependency>
</dependencies>

<build>
<plugins>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
${project.build.directory}/libs
</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>

<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>com.amazonaws.samples.AmazonDynamoDBSample</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>

</project>
169 changes: 169 additions & 0 deletions src/main/java/com/amazonaws/samples/AmazonDynamoDBSample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
package com.amazonaws.samples;
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.util.HashMap;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.PutItemRequest;
import com.amazonaws.services.dynamodbv2.model.PutItemResult;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.model.ScanRequest;
import com.amazonaws.services.dynamodbv2.model.ScanResult;
import com.amazonaws.services.dynamodbv2.model.TableDescription;
import com.amazonaws.services.dynamodbv2.util.TableUtils;

/**
* This sample demonstrates how to perform a few simple operations with the
* Amazon DynamoDB service.
*/
public class AmazonDynamoDBSample {

/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (C:\\Users\\syntel\\.aws\\credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/

static AmazonDynamoDB dynamoDB;

/**
* The only information needed to create a client are security credentials
* consisting of the AWS Access Key ID and Secret Access Key. All other
* configuration, such as the service endpoints, are performed
* automatically. Client parameters, such as proxies, can be specified in an
* optional ClientConfiguration object when constructing a client.
*
* @see com.amazonaws.auth.BasicAWSCredentials
* @see com.amazonaws.auth.ProfilesConfigFile
* @see com.amazonaws.ClientConfiguration
*/
private static void init() throws Exception {
/*
* The ProfileCredentialsProvider will return your [aws-personal]
* credential profile by reading from the credentials file located at
* (C:\\Users\\syntel\\.aws\\credentials).
*/
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.getCredentials();
System.out.println("credentail loadeds");
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\syntel\\.aws\\credentials), and is in valid format.",
e);
}
dynamoDB = AmazonDynamoDBClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-east-2")
.build();
}

public static void main(String[] args) throws Exception {
init();

try {
String tableName = "my-favorite-movies-table";

// Create a table with a primary hash key named 'name', which holds a string
CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
.withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH))
.withAttributeDefinitions(new AttributeDefinition().withAttributeName("name").withAttributeType(ScalarAttributeType.S))
.withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));

// Create table if it does not exist yet
TableUtils.createTableIfNotExists(dynamoDB, createTableRequest);
// wait for the table to move into ACTIVE state
TableUtils.waitUntilActive(dynamoDB, tableName);

// Describe our new table
DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
System.out.println("Table Description: " + tableDescription);

// Add an item
Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James", "Sara");
PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
System.out.println("Result: " + putItemResult);

// Add another item
item = newItem("Airplane", 1980, "*****", "James", "Billy Bob");
putItemRequest = new PutItemRequest(tableName, item);
putItemResult = dynamoDB.putItem(putItemRequest);
System.out.println("Result: " + putItemResult);

// Scan items for movies with a year attribute greater than 1985
HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
Condition condition = new Condition()
.withComparisonOperator(ComparisonOperator.GT.toString())
.withAttributeValueList(new AttributeValue().withN("1985"));
scanFilter.put("year", condition);
ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
ScanResult scanResult = dynamoDB.scan(scanRequest);
System.out.println("Result: " + scanResult);

} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means your request made it "
+ "to AWS, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with AWS, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}

private static Map<String, AttributeValue> newItem(String name, int year, String rating, String... fans) {
Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
item.put("name", new AttributeValue(name));
item.put("year", new AttributeValue().withN(Integer.toString(year)));
item.put("rating", new AttributeValue(rating));
item.put("fans", new AttributeValue().withSS(fans));

return item;
}

}
125 changes: 125 additions & 0 deletions src/main/java/com/amazonaws/samples/AttachRolePolicy.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package com.amazonaws.samples;

import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder;
import com.amazonaws.services.identitymanagement.model.AttachRolePolicyRequest;
import com.amazonaws.services.identitymanagement.model.AttachedPolicy;
import com.amazonaws.services.identitymanagement.model.CreateRoleRequest;
import com.amazonaws.services.identitymanagement.model.CreateRoleResult;
import com.amazonaws.services.identitymanagement.model.GetRolePolicyRequest;
import com.amazonaws.services.identitymanagement.model.GetRoleRequest;
import com.amazonaws.services.identitymanagement.model.GetRoleResult;
import com.amazonaws.services.identitymanagement.model.ListAttachedRolePoliciesRequest;
import com.amazonaws.services.identitymanagement.model.ListAttachedRolePoliciesResult;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class AttachRolePolicy {

static AmazonIdentityManagement iam;
public static final String POLICY_ARN =
"arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess";

private static void init() throws Exception {

ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.getCredentials();
System.out.println("credentail loadeds");
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\syntel\\.aws\\credentials), and is in valid format.",
e);
}
iam = AmazonIdentityManagementClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-east-2")
.build();
}

public static void main(String[] args) throws Exception {
init();
createIamRole();
//attatchPolicyToRole();
}

public static void createIamRole() {
String role_name = "testSdkRole";
String POLICY_DOCUMENT =
"{\r\n" +
" \"Version\": \"2012-10-17\",\r\n" +
" \"Statement\": {\r\n" +
" \"Effect\": \"Allow\",\r\n" +
" \"Principal\": {\"Service\": \"ec2.amazonaws.com\"},\r\n" +
" \"Action\": \"sts:AssumeRole\"\r\n" +
" }\r\n" +
"}";

GetRoleRequest req = new GetRoleRequest().withRoleName("SQSRole");
GetRoleResult res = iam.getRole(req);
System.out.println(res);


CreateRoleRequest request2 = new CreateRoleRequest().withPath("/service-role/").withRoleName(role_name).withAssumeRolePolicyDocument(POLICY_DOCUMENT).withDescription("Created through AWS SDK");
CreateRoleResult response2 = iam.createRole(request2);
System.out.println("Role Created");

}


/**
* Attach policy to role
*/
public static void attatchPolicyToRole() {
String role_name = "SQSRole";

ListAttachedRolePoliciesRequest request =
new ListAttachedRolePoliciesRequest()
.withRoleName(role_name);



List<AttachedPolicy> matching_policies = new ArrayList<>();

boolean done = false;

while(!done) {
ListAttachedRolePoliciesResult response =
iam.listAttachedRolePolicies(request);

matching_policies.addAll(
response.getAttachedPolicies()
.stream()
.filter(p -> p.getPolicyName().equals(role_name))
.collect(Collectors.toList()));

if(!response.getIsTruncated()) {
done = true;
}
request.setMarker(response.getMarker());
}

if (matching_policies.size() > 0) {
System.out.println(role_name +
" policy is already attached to this role.");
return;
}

AttachRolePolicyRequest attach_request =
new AttachRolePolicyRequest()
.withRoleName(role_name)
.withPolicyArn(POLICY_ARN);

iam.attachRolePolicy(attach_request);

System.out.println("Successfully attached policy " + POLICY_ARN +
" to role " + role_name);
}
}

10 changes: 10 additions & 0 deletions src/main/java/com/amazonaws/samples/CreateRole.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.amazonaws.samples;

public class CreateRole {

public static void main(String[] args) {
// TODO Auto-generated method stub

}

}