├── src ├── main │ ├── resources │ │ └── publicKeyFile │ └── java │ │ └── com │ │ └── wazcov │ │ └── awsJavaSamples │ │ ├── AwsShared │ │ └── AWSSharedUtils.java │ │ ├── V1SDK │ │ ├── Lambda │ │ │ └── Lambda_Start.java │ │ ├── SQS │ │ │ └── SQS_Start.java │ │ ├── SNS │ │ │ └── SNS_Start.java │ │ ├── SES │ │ │ └── SES_Start.java │ │ ├── SM │ │ │ └── SM_Start.java │ │ └── RDS │ │ │ └── RDS_Start.java │ │ └── V2SDK │ │ ├── S3 │ │ └── S3_Start.java │ │ └── SM │ │ └── SM_Start.java └── test │ └── java │ └── CredentialsTest.java ├── .gitignore ├── README.md └── pom.xml /src/main/resources/publicKeyFile: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wazcov/AWS-Java-Samples/HEAD/src/main/resources/publicKeyFile -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | target/ 3 | *.iml 4 | .DS_Store 5 | 6 | # Compiled class file 7 | *.class 8 | 9 | # Log file 10 | *.log 11 | 12 | # BlueJ files 13 | *.ctxt 14 | 15 | # Mobile Tools for Java (J2ME) 16 | .mtj.tmp/ 17 | 18 | # Package Files # 19 | *.jar 20 | *.war 21 | *.nar 22 | *.ear 23 | *.zip 24 | *.tar.gz 25 | *.rar 26 | 27 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 28 | hs_err_pid* 29 | -------------------------------------------------------------------------------- /src/main/java/com/wazcov/awsJavaSamples/AwsShared/AWSSharedUtils.java: -------------------------------------------------------------------------------- 1 | package com.wazcov.awsJavaSamples.AwsShared; 2 | 3 | import com.amazonaws.auth.BasicAWSCredentials; 4 | import com.amazonaws.regions.Regions; 5 | import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; 6 | 7 | /* 8 | Enter your own credentials here 9 | */ 10 | public class AWSSharedUtils { 11 | public static Regions region = Regions.EU_WEST_1; //e.g Regions.US_EAST_1; 12 | public static String receiverEmailAddress = "XXX"; 13 | public static String accessKey = "xxx"; 14 | public static String secretKey = "xxx"; 15 | 16 | //V1 SDK 17 | public static BasicAWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey); 18 | //V2 SDK 19 | public static AwsBasicCredentials basicCredentials = AwsBasicCredentials.create(accessKey, secretKey); 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/CredentialsTest.java: -------------------------------------------------------------------------------- 1 | import com.wazcov.awsJavaSamples.AwsShared.AWSSharedUtils; 2 | import org.junit.Test; 3 | 4 | import static org.junit.Assert.assertNotEquals; 5 | import static org.junit.Assert.assertNotNull; 6 | 7 | public class CredentialsTest { 8 | 9 | /* 10 | Run this test to confirm you have changed all of the appropriate settings 11 | 12 | It doesn't check your settings are correct however. 13 | */ 14 | 15 | @Test 16 | public void checkCredsAreSet() { 17 | assertNotEquals(AWSSharedUtils.creds.getAWSAccessKeyId(), "XXX"); 18 | assertNotEquals(AWSSharedUtils.creds.getAWSSecretKey(), "XXX"); 19 | assertNotEquals(AWSSharedUtils.basicCredentials.accessKeyId(), "XXX"); 20 | assertNotEquals(AWSSharedUtils.basicCredentials.secretAccessKey(), "XXX"); 21 | assertNotEquals(AWSSharedUtils.receiverEmailAddress, "XXX"); 22 | assertNotNull(AWSSharedUtils.region); 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/wazcov/awsJavaSamples/V1SDK/Lambda/Lambda_Start.java: -------------------------------------------------------------------------------- 1 | package com.wazcov.awsJavaSamples.V1SDK.Lambda; 2 | 3 | import com.amazonaws.services.lambda.runtime.events.S3Event; 4 | import com.amazonaws.services.s3.AmazonS3; 5 | import com.amazonaws.services.s3.AmazonS3Client; 6 | 7 | import java.net.URLDecoder; 8 | 9 | /* 10 | This is an example function for processing data from an S3 Bucket in AWS Lambda. 11 | 12 | 1) Upload a .jar file containing a class like this one to AWS Lambda. 13 | 2) Set an S3 Trigger of "Event type: ObjectCreated" TODO: Add infrastructure code to build this 14 | 3) Set the Handler to match "com.wazcov.awsJavaSamples.V1SDK.Lambda.Lambda_Start::testCode" 15 | 4) Upload a file with text in it to S3 16 | 5) Check CloudWatch logs for the System.out statements 17 | */ 18 | 19 | public class Lambda_Start { 20 | public static void testCode(S3Event s3Event) throws Exception { 21 | 22 | StringBuilder stringBuilder = new StringBuilder(); 23 | 24 | s3Event.getRecords().forEach(e -> { 25 | try { 26 | String bucket = e.getS3().getBucket().getName(); 27 | 28 | String key = e.getS3().getObject().getKey().replace('+', ' '); 29 | key = URLDecoder.decode(key, "UTF-8"); 30 | 31 | AmazonS3 s3Client = AmazonS3Client.builder().build(); 32 | s3Client.getObjectAsString(bucket, key); 33 | stringBuilder.append(s3Client.getObjectAsString(bucket, key)); 34 | 35 | } catch (Exception ex) { 36 | System.out.println(ex.toString()); 37 | } 38 | }); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AWS Java Samples 2 | A repository of basic AWS samples to get you started connecting to various AWS Services using the V1 and V2 SDKs. 3 | 4 | ## Assumptions: 5 | 6 | Much of this code is intentionally not commented, as variables and methods are named in such a way that it should be fairly straightforward to understand what is happening. 7 | 8 | This does assume a basic knowledge of Java. 9 | 10 | This also assumes you have created an AWS account. Basic information on what you need to do in the UI is documented in each of the samples. 11 | 12 | ## Important: 13 | 14 | Remember to add your own credentials into the AWS Shared package ([how-to](https://aws.amazon.com/premiumsupport/knowledge-center/create-access-key/)). 15 | 16 | You can run the test [InitTest](src/test/java/InitTest.java) to confirm that you have at least changed all the values (although it does not validate them). 17 | 18 | Each section contains a brief comment detailing the steps you need to take in the AWS Web UI to get set up. The program won't run unless you do these tasks. 19 | 20 | ## SDK V1 Samples 21 | (V1 Is still supported and widely used): 22 | 23 | * [Amazon SQS - Simple Queue Service](src/main/java/com/waynecovell/awsJavaSamples/V1SDK/SQS/SQS_Start.java) 24 | * [Amazon SNS - Simple Notification Service](src/main/java/com/waynecovell/awsJavaSamples/V1SDK/SNS/SNS_Start.java) 25 | * [Amazon SES - Simple Email Service](src/main/java/com/waynecovell/awsJavaSamples/V1SDK/SES/SES_Start.java) 26 | * [Amazon RDS - Relational Database Service](src/main/java/com/waynecovell/awsJavaSamples/V1SDK/RDS/RDS_Start.java) 27 | * [Amazon SM - Secrets Manager](src/main/java/com/waynecovell/awsJavaSamples/V1SDK/SM/SM_Start.java) 28 | 29 | ## SDK V2 Samples: 30 | 31 | * [Amazon SM - Secrets Manager](src/main/java/com/waynecovell/awsJavaSamples/V2SDK/SM/SM_Start.java) 32 | * [Amazon S3 - S3](src/main/java/com/waynecovell/awsJavaSamples/V2SDK/S3/S3_Start.java) 33 | 34 | ## Don't forget to star this repository if you find it useful :-) 35 | -------------------------------------------------------------------------------- /src/main/java/com/wazcov/awsJavaSamples/V1SDK/SQS/SQS_Start.java: -------------------------------------------------------------------------------- 1 | package com.wazcov.awsJavaSamples.V1SDK.SQS; 2 | 3 | import com.wazcov.awsJavaSamples.AwsShared.AWSSharedUtils; 4 | import com.amazon.sqs.javamessaging.ProviderConfiguration; 5 | import com.amazon.sqs.javamessaging.SQSConnection; 6 | import com.amazon.sqs.javamessaging.SQSConnectionFactory; 7 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 8 | import com.amazonaws.auth.BasicAWSCredentials; 9 | import com.amazonaws.services.sqs.AmazonSQSClientBuilder; 10 | 11 | import javax.jms.Message; 12 | import javax.jms.MessageConsumer; 13 | import javax.jms.MessageProducer; 14 | import javax.jms.Queue; 15 | import javax.jms.Session; 16 | import javax.jms.TextMessage; 17 | 18 | public class SQS_Start { 19 | 20 | /* 21 | To Use AWS com.waynecovell.awsJavaSamples.V1SDK.SQS, you need to ensure you have the following: 22 | 23 | - A user created in AWS IAM 24 | - Appropriate user, region, etc details updated in in AWSSharedUtils 25 | - AmazonSQSFullAccess Group assigned to that user in IAM 26 | - A queue created in the UI for com.waynecovell.awsJavaSamples.V1SDK.SQS, with the same name used below 27 | - A region specified in AWSSharedUtils that matches the region you created the aformetnioned queue in, in AWS UI. 28 | */ 29 | 30 | private static SQSConnection connection = null; 31 | private static Session session = null; 32 | private static Queue queue = null; 33 | 34 | public static void main(String[] args) { 35 | try { 36 | openQueueConnection(); 37 | sendMessageOnAQueue(); 38 | receiveMessagesFromAQueue(); 39 | closeQueueConnection(); 40 | } 41 | catch(Exception e) { 42 | System.out.println(e.toString()); 43 | } 44 | } 45 | 46 | private static void closeQueueConnection() throws Exception { 47 | connection.close(); 48 | } 49 | 50 | public static void receiveMessagesFromAQueue() throws Exception { 51 | MessageConsumer consumer = session.createConsumer(queue); 52 | connection.start(); 53 | Message receivedMessage = consumer.receive(1000); 54 | if (receivedMessage != null) { 55 | System.out.println("Received: " + ((TextMessage) receivedMessage).getText()); 56 | } 57 | } 58 | 59 | public static void sendMessageOnAQueue() throws Exception { 60 | MessageProducer producer = session.createProducer(queue); 61 | TextMessage message = session.createTextMessage("Hello World!"); 62 | producer.send(message); 63 | System.out.println("JMS Message " + message.getJMSMessageID()); 64 | } 65 | 66 | public static void openQueueConnection() throws Exception { 67 | //Get these credentials from IAM in the AWS Web UI 68 | BasicAWSCredentials creds = AWSSharedUtils.creds; 69 | SQSConnectionFactory connectionFactory = new SQSConnectionFactory( 70 | new ProviderConfiguration(), 71 | AmazonSQSClientBuilder.standard() 72 | .withCredentials(new AWSStaticCredentialsProvider(creds)) 73 | .withRegion(AWSSharedUtils.region).build() 74 | ); 75 | connection = connectionFactory.createConnection(); 76 | session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 77 | queue = session.createQueue("MyQueue"); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/wazcov/awsJavaSamples/V2SDK/S3/S3_Start.java: -------------------------------------------------------------------------------- 1 | package com.wazcov.awsJavaSamples.V2SDK.S3; 2 | 3 | import com.wazcov.awsJavaSamples.AwsShared.AWSSharedUtils; 4 | import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; 5 | import software.amazon.awssdk.core.sync.RequestBody; 6 | import software.amazon.awssdk.services.s3.S3Client; 7 | import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration; 8 | import software.amazon.awssdk.services.s3.model.CreateBucketRequest; 9 | import software.amazon.awssdk.services.s3.model.ListBucketsRequest; 10 | import software.amazon.awssdk.services.s3.model.ListBucketsResponse; 11 | import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; 12 | import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; 13 | import software.amazon.awssdk.services.s3.model.PutObjectRequest; 14 | 15 | import java.nio.ByteBuffer; 16 | import java.util.List; 17 | import java.util.stream.Collectors; 18 | 19 | public class S3_Start { 20 | 21 | private static final String BUCKET_NAME = "testing"; 22 | private static S3Client client = null; 23 | 24 | public static void main(String[] args) { 25 | setupS3(); 26 | createBucket(BUCKET_NAME); 27 | if (listBuckets().contains(BUCKET_NAME)) { 28 | System.out.println("Bucket Exists"); 29 | uploadToS3(BUCKET_NAME, "Sample_File.txt"); 30 | listObjectsInS3Bucket(BUCKET_NAME); 31 | } 32 | } 33 | 34 | private static void setupS3() { 35 | client = S3Client.builder().credentialsProvider(StaticCredentialsProvider.create(AWSSharedUtils.basicCredentials)).build(); 36 | } 37 | 38 | private static void createBucket(String bucket_name) { 39 | CreateBucketRequest createBucketRequest = CreateBucketRequest 40 | .builder() 41 | .bucket(bucket_name) 42 | .createBucketConfiguration(CreateBucketConfiguration.builder() 43 | .locationConstraint(AWSSharedUtils.region.getName()) 44 | .build()) 45 | .build(); 46 | client.createBucket(createBucketRequest); 47 | System.out.println("Created Bucket"); 48 | } 49 | 50 | private static List listBuckets() { 51 | ListBucketsRequest listBucketsRequest = ListBucketsRequest.builder().build(); 52 | ListBucketsResponse listBucketsResponse = client.listBuckets(listBucketsRequest); 53 | List buckets = listBucketsResponse.buckets().stream().map(x -> x.name()).collect(Collectors.toList()); 54 | System.out.println("Listing Buckets"); 55 | return buckets; 56 | } 57 | 58 | private static void uploadToS3(String bucket_name, String key_name) { 59 | try { 60 | client.putObject(PutObjectRequest.builder() 61 | .bucket(bucket_name) 62 | .key(key_name) 63 | .build(), RequestBody.fromByteBuffer(ByteBuffer.wrap("Hello World".getBytes()))); 64 | System.out.println("Uploaded File"); 65 | } catch (Exception e) { 66 | e.printStackTrace(); 67 | } 68 | } 69 | 70 | private static void listObjectsInS3Bucket(String bucket_name) { 71 | ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder().bucket(bucket_name).build(); 72 | ListObjectsV2Response listObjectsV2Response; 73 | listObjectsV2Response = client.listObjectsV2(listObjectsV2Request); 74 | listObjectsV2Response.contents().stream().map(x -> x.key()).forEach(e -> System.out.println(e)); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/wazcov/awsJavaSamples/V1SDK/SNS/SNS_Start.java: -------------------------------------------------------------------------------- 1 | package com.wazcov.awsJavaSamples.V1SDK.SNS; 2 | 3 | import com.wazcov.awsJavaSamples.AwsShared.AWSSharedUtils; 4 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 5 | import com.amazonaws.auth.BasicAWSCredentials; 6 | import com.amazonaws.services.sns.AmazonSNS; 7 | import com.amazonaws.services.sns.AmazonSNSClient; 8 | import com.amazonaws.services.sns.model.CreateTopicRequest; 9 | import com.amazonaws.services.sns.model.CreateTopicResult; 10 | import com.amazonaws.services.sns.model.PublishRequest; 11 | import com.amazonaws.services.sns.model.PublishResult; 12 | import com.amazonaws.services.sns.model.SubscribeRequest; 13 | 14 | public class SNS_Start { 15 | 16 | /* 17 | To Use AWS com.waynecovell.awsJavaSamples.V1SDK.SNS, you need to ensure you have the following: 18 | 19 | - A user created in AWS IAM 20 | - Appropriate user, region, etc details updated in in AWSSharedUtils 21 | - AmazonSNSFullAccess Group assigned to that user in IAM 22 | - A valid email address, specified below (after subscribing you have to confirm with your email) 23 | 24 | Create A Topic method shows how one could create a topic programmatically, however you could create 25 | this in the AWS UI and hard-code it. 26 | */ 27 | 28 | private static AmazonSNS amazonSNSClient = null; 29 | 30 | public static void main(String[] args) { 31 | openSNSConnection(); 32 | String arn = createATopic(); 33 | subscribeToATopic(arn); 34 | publishToATopic(arn); 35 | } 36 | 37 | public static void openSNSConnection() { 38 | BasicAWSCredentials creds = AWSSharedUtils.creds; 39 | amazonSNSClient = AmazonSNSClient.builder() 40 | .withCredentials(new AWSStaticCredentialsProvider(creds)) 41 | .withRegion(AWSSharedUtils.region) 42 | .build(); 43 | } 44 | 45 | public static String createATopic() { 46 | final CreateTopicRequest createTopicRequest = new CreateTopicRequest("MyTopic"); 47 | final CreateTopicResult createTopicResponse = amazonSNSClient.createTopic(createTopicRequest); 48 | System.out.println("TopicArn:" + createTopicResponse.getTopicArn()); 49 | System.out.println("CreateTopicRequest: " + amazonSNSClient.getCachedResponseMetadata(createTopicRequest)); 50 | return createTopicResponse.getTopicArn(); 51 | } 52 | 53 | public static void subscribeToATopic(String topicArn) { 54 | final SubscribeRequest subscribeRequest = new SubscribeRequest(topicArn, "email", AWSSharedUtils.receiverEmailAddress); 55 | amazonSNSClient.subscribe(subscribeRequest); 56 | 57 | System.out.println("SubscribeRequest: " + amazonSNSClient.getCachedResponseMetadata(subscribeRequest)); 58 | System.out.println("To confirm the subscription, check your email."); 59 | } 60 | 61 | public static void publishToATopic(String topicArn) { 62 | try { 63 | Thread.sleep(30000); //You have 30 seconds to confirm the subscription in your email account 64 | }catch(InterruptedException ie){} 65 | 66 | final String msg = "If you receive this message, publishing a message to an Amazon com.waynecovell.awsJavaSamples.V1SDK.SNS topic works."; 67 | final PublishRequest publishRequest = new PublishRequest(topicArn, msg); 68 | final PublishResult publishResponse = amazonSNSClient.publish(publishRequest); 69 | 70 | System.out.println("MessageId: " + publishResponse.getMessageId()); 71 | //Now check your email for a notification 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/wazcov/awsJavaSamples/V1SDK/SES/SES_Start.java: -------------------------------------------------------------------------------- 1 | package com.wazcov.awsJavaSamples.V1SDK.SES; 2 | 3 | import com.wazcov.awsJavaSamples.AwsShared.AWSSharedUtils; 4 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 5 | import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; 6 | import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder; 7 | import com.amazonaws.services.simpleemail.model.Body; 8 | import com.amazonaws.services.simpleemail.model.Content; 9 | import com.amazonaws.services.simpleemail.model.Destination; 10 | import com.amazonaws.services.simpleemail.model.Message; 11 | import com.amazonaws.services.simpleemail.model.SendEmailRequest; 12 | 13 | import java.io.IOException; 14 | 15 | public class SES_Start { 16 | 17 | /* 18 | To Use AWS com.waynecovell.awsJavaSamples.V1SDK.SES, you need to ensure you have the following: 19 | 20 | - A user created in AWS IAM 21 | - Appropriate user, region, etc details updated in in AWSSharedUtils 22 | - AmazonSESFullAccess Group assigned to that user in IAM 23 | - Two valid, email addresses, both verified in AWS com.waynecovell.awsJavaSamples.V1SDK.SES 24 | - A valid configuration set, created in AWS com.waynecovell.awsJavaSamples.V1SDK.SES ( I selected CloudWatch with a tag of a:1) 25 | */ 26 | 27 | private static final String fromAddress = "wayne.covell@infinityworks.com"; 28 | private static final String toAddress = AWSSharedUtils.receiverEmailAddress; 29 | private static final String configSet = "MyConfig"; 30 | 31 | private static final String subject = "Amazon com.waynecovell.awsJavaSamples.V1SDK.SES test (AWS SDK for Java)"; 32 | private static final String htmlBody = "

Amazon com.waynecovell.awsJavaSamples.V1SDK.SES test (AWS SDK for Java)

" 33 | + "

This email was sent with " 34 | + "Amazon com.waynecovell.awsJavaSamples.V1SDK.SES using the " 35 | + "AWS SDK for Java"; 36 | 37 | private static final String nonHtmlClientBody = "This email was sent through Amazon com.waynecovell.awsJavaSamples.V1SDK.SES " 38 | + "using the AWS SDK for Java."; 39 | 40 | public static void main(String[] args) throws IOException { 41 | 42 | try { 43 | AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder 44 | .standard() 45 | .withCredentials(new AWSStaticCredentialsProvider(AWSSharedUtils.creds)) 46 | .withRegion(AWSSharedUtils.region).build(); 47 | 48 | SendEmailRequest request = new SendEmailRequest() 49 | .withDestination( 50 | new Destination().withToAddresses(toAddress)) 51 | .withMessage(new Message() 52 | .withBody(new Body() 53 | .withHtml(new Content() 54 | .withCharset("UTF-8").withData(htmlBody)) 55 | .withText(new Content() 56 | .withCharset("UTF-8").withData(nonHtmlClientBody))) 57 | .withSubject(new Content() 58 | .withCharset("UTF-8").withData(subject))) 59 | .withSource(fromAddress) 60 | .withConfigurationSetName(configSet); 61 | client.sendEmail(request); 62 | System.out.println("Email sent!"); 63 | } catch (Exception ex) { 64 | System.out.println("The email was not sent. Error message: " 65 | + ex.getMessage()); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 5 | 4.0.0 6 | com.infinityworks.wayne 7 | aws-sample 8 | jar 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | org.apache.maven.plugins 14 | maven-compiler-plugin 15 | 16 | 8 17 | 8 18 | 19 | 20 | 21 | 22 | AWS Samples 23 | http://maven.apache.org 24 | 25 | 26 | 27 | 28 | 29 | software.amazon.awssdk 30 | bom 31 | 2.5.25 32 | pom 33 | import 34 | 35 | 36 | 37 | 38 | 39 | 40 | org.postgresql 41 | postgresql 42 | 42.2.5 43 | 44 | 45 | org.springframework 46 | spring-jdbc 47 | 5.0.8.RELEASE 48 | 49 | 50 | junit 51 | junit 52 | 4.11 53 | test 54 | 55 | 56 | 57 | software.amazon.awssdk 58 | secretsmanager 59 | 60 | 61 | software.amazon.awssdk 62 | s3 63 | 64 | 65 | 66 | com.amazonaws 67 | amazon-sqs-java-messaging-lib 68 | 1.0.4 69 | jar 70 | 71 | 72 | com.amazonaws 73 | aws-lambda-java-events 74 | 1.3.0 75 | 76 | 77 | com.amazonaws 78 | aws-java-sdk-s3 79 | 1.11.534 80 | 81 | 82 | com.amazonaws 83 | aws-java-sdk-rds 84 | 1.11.327 85 | 86 | 87 | com.amazonaws 88 | aws-java-sdk-ses 89 | 1.11.327 90 | 91 | 92 | com.amazonaws 93 | aws-java-sdk-sns 94 | 1.11.327 95 | 96 | 97 | com.amazonaws 98 | aws-java-sdk-secretsmanager 99 | 1.11.327 100 | 101 | 102 | -------------------------------------------------------------------------------- /src/main/java/com/wazcov/awsJavaSamples/V1SDK/SM/SM_Start.java: -------------------------------------------------------------------------------- 1 | package com.wazcov.awsJavaSamples.V1SDK.SM; 2 | 3 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 4 | import com.amazonaws.services.secretsmanager.AWSSecretsManager; 5 | import com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder; 6 | import com.amazonaws.services.secretsmanager.model.CreateSecretRequest; 7 | import com.amazonaws.services.secretsmanager.model.GetSecretValueRequest; 8 | import com.amazonaws.services.secretsmanager.model.GetSecretValueResult; 9 | import com.amazonaws.services.secretsmanager.model.ListSecretsRequest; 10 | import com.amazonaws.services.secretsmanager.model.ListSecretsResult; 11 | import com.amazonaws.util.IOUtils; 12 | import com.wazcov.awsJavaSamples.AwsShared.AWSSharedUtils; 13 | 14 | import java.io.InputStream; 15 | import java.nio.ByteBuffer; 16 | import java.security.KeyFactory; 17 | import java.security.PublicKey; 18 | import java.security.spec.X509EncodedKeySpec; 19 | 20 | public class SM_Start { 21 | 22 | private static final String region = "us-east-2"; 23 | private static AWSSecretsManager client = null; 24 | private static final String STRING_KEY_NAME = "StringKeyX"; 25 | private static final String BINARY_FILE_KEY_NAME = "FileKeyX"; 26 | 27 | public static void main(String[] args) { 28 | 29 | SM_Start secretsManagerApplication = new SM_Start(); 30 | 31 | try { 32 | secretsManagerApplication.setupSecretManager(); 33 | 34 | //Example Storing Key String 35 | secretsManagerApplication.createSecretString(); 36 | secretsManagerApplication.getSecretStringValue(); 37 | 38 | //Example Storing Key Binary 39 | secretsManagerApplication.createSecretFromFile(); 40 | secretsManagerApplication.getSecretFileValue(); 41 | 42 | } catch (Exception e) { 43 | e.printStackTrace(); 44 | } 45 | } 46 | 47 | private void setupSecretManager() { 48 | client = AWSSecretsManagerClientBuilder.standard() 49 | .withRegion(region) 50 | .withCredentials(new AWSStaticCredentialsProvider(AWSSharedUtils.creds)) 51 | .build(); 52 | } 53 | 54 | private void createSecretString() { 55 | CreateSecretRequest createSecretRequest = new CreateSecretRequest().withName(STRING_KEY_NAME).withSecretString("Hello World"); 56 | client.createSecret(createSecretRequest); 57 | System.out.println("Stored Secret String"); 58 | } 59 | 60 | private void getSecretStringValue() { 61 | ListSecretsRequest listSecretsRequest = new ListSecretsRequest(); 62 | ListSecretsResult secretsResult = client.listSecrets(listSecretsRequest); 63 | secretsResult.getSecretList().forEach(e -> System.out.println("Retrieved: " + e.getName())); 64 | 65 | GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest().withSecretId(STRING_KEY_NAME); 66 | GetSecretValueResult secretValueResult = client.getSecretValue(getSecretValueRequest); 67 | String secretString = secretValueResult.getSecretString(); 68 | 69 | System.out.println("Retrieved String Value: " + secretString); 70 | } 71 | 72 | private void createSecretFromFile() throws Exception { 73 | InputStream publicKeyStream = this.getClass().getClassLoader().getResourceAsStream("publicKeyFile"); 74 | byte[] targetArray = IOUtils.toByteArray(publicKeyStream); 75 | ByteBuffer secretBinaryByteBuffer = ByteBuffer.wrap(targetArray); 76 | 77 | CreateSecretRequest createSecretRequest = new CreateSecretRequest().withName(BINARY_FILE_KEY_NAME).withSecretBinary(secretBinaryByteBuffer); 78 | client.createSecret(createSecretRequest); 79 | 80 | System.out.println("Stored Secret File"); 81 | } 82 | 83 | private void getSecretFileValue() throws Exception { 84 | GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest().withSecretId(BINARY_FILE_KEY_NAME); 85 | GetSecretValueResult secretValueResult = client.getSecretValue(getSecretValueRequest); 86 | ByteBuffer secretBinaryByteBuffer = secretValueResult.getSecretBinary(); 87 | 88 | byte[] bytes = new byte[secretBinaryByteBuffer.capacity()]; 89 | secretBinaryByteBuffer.get(bytes, 0, bytes.length); 90 | 91 | X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes); 92 | KeyFactory kf = KeyFactory.getInstance("RSA"); 93 | PublicKey binary = kf.generatePublic(spec); 94 | 95 | System.out.println("Retrieved Secret Binary:"); 96 | System.out.println(binary.toString()); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/com/wazcov/awsJavaSamples/V2SDK/SM/SM_Start.java: -------------------------------------------------------------------------------- 1 | package com.wazcov.awsJavaSamples.V2SDK.SM; 2 | 3 | import com.amazonaws.util.IOUtils; 4 | import com.wazcov.awsJavaSamples.AwsShared.AWSSharedUtils; 5 | import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; 6 | import software.amazon.awssdk.core.SdkBytes; 7 | import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; 8 | import software.amazon.awssdk.services.secretsmanager.model.CreateSecretRequest; 9 | import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; 10 | import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; 11 | import software.amazon.awssdk.services.secretsmanager.model.ListSecretsRequest; 12 | import software.amazon.awssdk.services.secretsmanager.model.ListSecretsResponse; 13 | 14 | import java.io.InputStream; 15 | import java.nio.ByteBuffer; 16 | import java.security.KeyFactory; 17 | import java.security.PublicKey; 18 | import java.security.spec.X509EncodedKeySpec; 19 | 20 | public class SM_Start { 21 | 22 | private static SecretsManagerClient client = null; 23 | private static final String STRING_KEY_NAME = "StringKeyX"; 24 | private static final String BINARY_FILE_KEY_NAME = "FileKeyX"; 25 | 26 | public static void main(String[] args) { 27 | 28 | SM_Start secretsManagerApplication = new SM_Start(); 29 | 30 | try { 31 | secretsManagerApplication.setupSecretManager(); 32 | 33 | //Example Storing Key String 34 | secretsManagerApplication.createSecretString(); 35 | secretsManagerApplication.getSecretStringValue(); 36 | 37 | //Example Storing Key Binary 38 | secretsManagerApplication.createSecretFromFile(); 39 | secretsManagerApplication.getSecretFileValue(); 40 | 41 | } catch (Exception e) { 42 | e.printStackTrace(); 43 | } 44 | } 45 | 46 | private void setupSecretManager() { 47 | client = SecretsManagerClient.builder().credentialsProvider(StaticCredentialsProvider.create(AWSSharedUtils.basicCredentials)).build(); 48 | } 49 | 50 | private void createSecretString() { 51 | CreateSecretRequest createSecretRequest = CreateSecretRequest.builder().name(STRING_KEY_NAME).secretString("Hello World").build(); 52 | client.createSecret(createSecretRequest); 53 | System.out.println("Stored Secret String"); 54 | } 55 | 56 | private void getSecretStringValue() { 57 | ListSecretsRequest listSecretsRequest = ListSecretsRequest.builder().build(); 58 | ListSecretsResponse listSecretsResponse = client.listSecrets(listSecretsRequest); 59 | 60 | listSecretsResponse.secretList().forEach(e -> System.out.println("Retrieved: " + e.name())); 61 | 62 | GetSecretValueRequest getSecretValueRequest = GetSecretValueRequest.builder().secretId(STRING_KEY_NAME).build(); 63 | GetSecretValueResponse secretValueResponse = client.getSecretValue(getSecretValueRequest); 64 | String secretString = secretValueResponse.secretString(); 65 | 66 | System.out.println("Retrieved String Value: " + secretString); 67 | } 68 | 69 | private void createSecretFromFile() throws Exception { 70 | InputStream publicKeyStream = this.getClass().getClassLoader().getResourceAsStream("publicKeyFile"); 71 | byte[] targetArray = IOUtils.toByteArray(publicKeyStream); 72 | ByteBuffer secretBinaryByteBuffer = ByteBuffer.wrap(targetArray); 73 | 74 | CreateSecretRequest createSecretRequest = CreateSecretRequest.builder().name(BINARY_FILE_KEY_NAME).secretBinary(SdkBytes.fromByteBuffer(secretBinaryByteBuffer)).build(); 75 | client.createSecret(createSecretRequest); 76 | 77 | System.out.println("Stored Secret File"); 78 | } 79 | 80 | private void getSecretFileValue() throws Exception { 81 | GetSecretValueRequest getSecretValueRequest = GetSecretValueRequest.builder().secretId(BINARY_FILE_KEY_NAME).build(); 82 | GetSecretValueResponse secretValueResponse = client.getSecretValue(getSecretValueRequest); 83 | 84 | ByteBuffer secretBinaryByteBuffer = secretValueResponse.secretBinary().asByteBuffer(); 85 | 86 | byte[] bytes = new byte[secretBinaryByteBuffer.capacity()]; 87 | secretBinaryByteBuffer.get(bytes, 0, bytes.length); 88 | 89 | X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes); 90 | KeyFactory kf = KeyFactory.getInstance("RSA"); 91 | PublicKey binary = kf.generatePublic(spec); 92 | 93 | System.out.println("Retrieved Secret Binary:"); 94 | System.out.println(binary.toString()); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/wazcov/awsJavaSamples/V1SDK/RDS/RDS_Start.java: -------------------------------------------------------------------------------- 1 | package com.wazcov.awsJavaSamples.V1SDK.RDS; 2 | 3 | import com.wazcov.awsJavaSamples.AwsShared.AWSSharedUtils; 4 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 5 | import com.amazonaws.services.rds.AmazonRDS; 6 | import com.amazonaws.services.rds.AmazonRDSClientBuilder; 7 | import com.amazonaws.services.rds.model.CreateDBInstanceRequest; 8 | import com.amazonaws.services.rds.model.DBInstance; 9 | import com.amazonaws.services.rds.model.DescribeDBInstancesResult; 10 | import com.amazonaws.services.rds.model.Endpoint; 11 | 12 | import java.io.IOException; 13 | import java.sql.Connection; 14 | import java.sql.DriverManager; 15 | import java.sql.PreparedStatement; 16 | import java.sql.ResultSet; 17 | import java.sql.Statement; 18 | import java.util.List; 19 | import java.util.UUID; 20 | 21 | public class RDS_Start { 22 | 23 | /* 24 | To Use AWS com.waynecovell.awsJavaSamples.V1SDK.RDS, you need to ensure you have the following: 25 | 26 | - A user created in AWS IAM 27 | - Appropriate user, region, etc details updated in in AWSSharedUtils 28 | - AmazonRDSFullAccess Group assigned to that user in IAM 29 | */ 30 | 31 | private static AmazonRDS client; 32 | private static Statement statement; 33 | private static Connection connection; 34 | private static String jdbcUrl; 35 | 36 | public static void main(String[] args) throws IOException { 37 | try { 38 | DriverManager.registerDriver(new org.postgresql.Driver()); 39 | connectToAwsRds(); 40 | createDatabase(); 41 | 42 | /* 43 | If we run the following commands straight away, it returns a null database 44 | so we must run the create script, then the others a few minutes afterwards 45 | */ 46 | 47 | 48 | /* 49 | TODO You currently have to edit the default VPC to allow traffic from anywhere on all ports. 50 | There should be a way to do this programmatically 51 | */ 52 | 53 | /* listDatabases(); 54 | createDatabaseTable(); 55 | insertDatabaseData(); 56 | validateDatabaseData();*/ 57 | } catch (Exception e) { 58 | System.out.println("Problem managing database " + e.toString()); 59 | e.printStackTrace(); 60 | } 61 | } 62 | 63 | private static void connectToAwsRds() { 64 | client = AmazonRDSClientBuilder 65 | .standard() 66 | .withCredentials(new AWSStaticCredentialsProvider(AWSSharedUtils.creds)) 67 | .withRegion(AWSSharedUtils.region).build(); 68 | } 69 | 70 | private static void listDatabases() { 71 | //When listing, make sure you are using the region where you created the database, by editing it in AWSSharedUtils 72 | DescribeDBInstancesResult result = client.describeDBInstances(); 73 | List instances = result.getDBInstances(); 74 | DBInstance instance = instances.get(0); //If you have multiple databases, this just gets the first one 75 | // Information about each com.waynecovell.awsJavaSamples.V1SDK.RDS instance 76 | String identifier = instance.getDBInstanceIdentifier(); 77 | String engine = instance.getEngine(); 78 | String status = instance.getDBInstanceStatus(); 79 | Endpoint endpoint = instance.getEndpoint(); 80 | 81 | engine += engine == "postgres" ? "ql" : ""; //The JDBC connection string needs "postgresql" yet amazon just return "postgres" 82 | jdbcUrl = "jdbc:" + engine + "ql://" + endpoint.getAddress() + ":" + endpoint.getPort() + "/" + identifier; 83 | 84 | System.out.println("Database exists: " + jdbcUrl); 85 | } 86 | 87 | private static void validateDatabaseData() throws Exception { 88 | String sql = "SELECT count(*) as count FROM awstest"; 89 | ResultSet resultSet = statement.executeQuery(sql); 90 | while (resultSet.next()) { 91 | String count = resultSet.getString("count"); 92 | System.out.println("Total Records: " + count); 93 | } 94 | System.out.println("Validated database data"); 95 | } 96 | 97 | private static void insertDatabaseData() throws Exception { 98 | PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO awstest (content) VALUES (?)"); 99 | String content = "" + UUID.randomUUID(); 100 | preparedStatement.setString(1, content); 101 | preparedStatement.executeUpdate(); 102 | System.out.println("Inserted database data"); 103 | } 104 | 105 | private static void createDatabaseTable() throws Exception { 106 | connection = DriverManager.getConnection(jdbcUrl, "fred", "fredfred123"); 107 | statement = connection.createStatement(); 108 | String sql = "CREATE TABLE IF NOT EXISTS awstest (id SERIAL PRIMARY KEY, content VARCHAR(80))"; 109 | statement.executeUpdate(sql); 110 | System.out.println("Added db table"); 111 | } 112 | 113 | private static void createDatabase() { 114 | CreateDBInstanceRequest request = new CreateDBInstanceRequest(); 115 | request.setDBInstanceIdentifier("awsjava"); 116 | request.setDBInstanceClass("db.t2.micro"); 117 | request.setEngine("postgres"); 118 | request.setMultiAZ(false); 119 | request.setPort(5432); 120 | request.setMasterUsername("fred"); 121 | request.setMasterUserPassword("fredfred123"); 122 | request.setDBName("awsjava"); 123 | request.setStorageType("gp2"); 124 | request.setAllocatedStorage(10); 125 | 126 | client.createDBInstance(request); 127 | System.out.println("Created database"); 128 | } 129 | } 130 | --------------------------------------------------------------------------------