diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..e796965 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +language: java +jdk: + - oraclejdk8 \ No newline at end of file diff --git a/README.md b/README.md index 0728f1b..f5cd194 100644 --- a/README.md +++ b/README.md @@ -1 +1,2 @@ -# aws-java-sdk-examples \ No newline at end of file +# 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) diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..0066251 --- /dev/null +++ b/pom.xml @@ -0,0 +1,61 @@ + + 4.0.0 + com.amazonaws + samples + 1.0.0 + + + com.amazonaws + aws-java-sdk + 1.11.507 + compile + + + com.amazonaws + amazon-kinesis-client + 1.2.1 + compile + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + + ${project.build.directory}/libs + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + + true + libs/ + com.amazonaws.samples.AmazonDynamoDBSample + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/amazonaws/samples/AmazonDynamoDBSample.java b/src/main/java/com/amazonaws/samples/AmazonDynamoDBSample.java new file mode 100644 index 0000000..fb8ee74 --- /dev/null +++ b/src/main/java/com/amazonaws/samples/AmazonDynamoDBSample.java @@ -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 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 scanFilter = new HashMap(); + 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 newItem(String name, int year, String rating, String... fans) { + Map item = new HashMap(); + 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; + } + +} diff --git a/src/main/java/com/amazonaws/samples/AttachRolePolicy.java b/src/main/java/com/amazonaws/samples/AttachRolePolicy.java new file mode 100644 index 0000000..b0a726a --- /dev/null +++ b/src/main/java/com/amazonaws/samples/AttachRolePolicy.java @@ -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 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); + } +} + diff --git a/src/main/java/com/amazonaws/samples/CreateRole.java b/src/main/java/com/amazonaws/samples/CreateRole.java new file mode 100644 index 0000000..65698ab --- /dev/null +++ b/src/main/java/com/amazonaws/samples/CreateRole.java @@ -0,0 +1,10 @@ +package com.amazonaws.samples; + +public class CreateRole { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +}