JAVA-11240 Moved spring-cloud to spring-cloud-modules
This commit is contained in:
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.spring.cloud.aws;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.baeldung.spring.cloud.aws.s3.SpringCloudS3Service;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan("com.baeldung.spring.cloud.aws.s3")
|
||||
public class InstanceProfileAwsApplication {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(InstanceProfileAwsApplication.class);
|
||||
private static final String applicationConfig = "spring.config.name:application-instance-profile";
|
||||
|
||||
private static String bucketName;
|
||||
private static String fileName = "sample-file.txt";
|
||||
|
||||
private static void setupResources() {
|
||||
bucketName = "baeldung-test-" + UUID.randomUUID()
|
||||
.toString();
|
||||
try {
|
||||
Files.write(Paths.get(fileName), "Hello World!".getBytes());
|
||||
} catch (IOException e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
setupResources();
|
||||
if (!new File(fileName).exists()) {
|
||||
logger.warn("Not able to create {} file. Check your folder permissions.", fileName);
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
SpringApplication application = new SpringApplicationBuilder(InstanceProfileAwsApplication.class).properties(applicationConfig)
|
||||
.build();
|
||||
ConfigurableApplicationContext context = application.run(args);
|
||||
SpringCloudS3Service service = context.getBean(SpringCloudS3Service.class);
|
||||
|
||||
// S3 bucket operations
|
||||
service.createBucket(bucketName);
|
||||
service.uploadObject(bucketName, fileName);
|
||||
service.downloadObject(bucketName, fileName);
|
||||
service.deleteBucket(bucketName);
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.spring.cloud.aws;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
|
||||
@SpringBootApplication
|
||||
@ImportResource("classpath:aws-config.xml")
|
||||
public class SpringCloudAwsApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringCloudAwsApplication.class, args);
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.spring.cloud.aws.config;
|
||||
|
||||
import com.amazonaws.services.sns.AmazonSNS;
|
||||
import com.amazonaws.services.sqs.AmazonSQSAsync;
|
||||
import org.springframework.cloud.aws.messaging.core.NotificationMessagingTemplate;
|
||||
import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class SpringCloudAwsConfig {
|
||||
|
||||
@Bean
|
||||
public QueueMessagingTemplate queueMessagingTemplate(AmazonSQSAsync amazonSQSAsync) {
|
||||
return new QueueMessagingTemplate(amazonSQSAsync);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public NotificationMessagingTemplate notificationMessagingTemplate(AmazonSNS amazonSNS) {
|
||||
return new NotificationMessagingTemplate(amazonSNS);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.spring.cloud.aws.ec2;
|
||||
|
||||
import org.springframework.cloud.aws.context.config.annotation.EnableContextInstanceData;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@EnableContextInstanceData
|
||||
public class EC2EnableMetadata {
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.spring.cloud.aws.ec2;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Lazy
|
||||
@Component
|
||||
public class EC2Metadata {
|
||||
|
||||
@Value("${ami-id:N/A}")
|
||||
private String amiId;
|
||||
|
||||
@Value("${hostname:N/A}")
|
||||
private String hostname;
|
||||
|
||||
@Value("${instance-type:N/A}")
|
||||
private String instanceType;
|
||||
|
||||
@Value("${services/domain:N/A}")
|
||||
private String serviceDomain;
|
||||
|
||||
@Value("#{instanceData['Name'] ?: 'N/A'}")
|
||||
private String name;
|
||||
|
||||
public String getAmiId() {
|
||||
return amiId;
|
||||
}
|
||||
|
||||
public String getHostname() {
|
||||
return hostname;
|
||||
}
|
||||
|
||||
public String getInstanceType() {
|
||||
return instanceType;
|
||||
}
|
||||
|
||||
public String getServiceDomain() {
|
||||
return serviceDomain;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("EC2Metadata [amiId=");
|
||||
builder.append(amiId);
|
||||
builder.append(", hostname=");
|
||||
builder.append(hostname);
|
||||
builder.append(", instanceType=");
|
||||
builder.append(instanceType);
|
||||
builder.append(", serviceDomain=");
|
||||
builder.append(serviceDomain);
|
||||
builder.append(", name=");
|
||||
builder.append(name);
|
||||
builder.append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.spring.cloud.aws.s3;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.aws.core.io.s3.PathMatchingSimpleStorageResourcePatternResolver;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.ResourceLoader;
|
||||
import org.springframework.core.io.WritableResource;
|
||||
import org.springframework.core.io.support.ResourcePatternResolver;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
|
||||
@Component
|
||||
public class SpringCloudS3 {
|
||||
|
||||
@Autowired
|
||||
ResourceLoader resourceLoader;
|
||||
|
||||
private ResourcePatternResolver resourcePatternResolver;
|
||||
|
||||
@Autowired
|
||||
public void setupResolver(ApplicationContext applicationContext, AmazonS3 amazonS3) {
|
||||
this.resourcePatternResolver = new PathMatchingSimpleStorageResourcePatternResolver(amazonS3, applicationContext);
|
||||
}
|
||||
|
||||
public void downloadS3Object(String s3Url) throws IOException {
|
||||
Resource resource = resourceLoader.getResource(s3Url);
|
||||
File downloadedS3Object = new File(resource.getFilename());
|
||||
try (InputStream inputStream = resource.getInputStream()) {
|
||||
Files.copy(inputStream, downloadedS3Object.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
|
||||
public void uploadFileToS3(File file, String s3Url) throws IOException {
|
||||
WritableResource resource = (WritableResource) resourceLoader.getResource(s3Url);
|
||||
try (OutputStream outputStream = resource.getOutputStream()) {
|
||||
Files.copy(file.toPath(), outputStream);
|
||||
}
|
||||
}
|
||||
|
||||
public void downloadMultipleS3Objects(String s3UrlPattern) throws IOException {
|
||||
Resource[] allFileMatchingPatten = this.resourcePatternResolver.getResources(s3UrlPattern);
|
||||
for (Resource resource : allFileMatchingPatten) {
|
||||
String fileName = resource.getFilename();
|
||||
fileName = fileName.substring(0, fileName.lastIndexOf("/") + 1);
|
||||
File downloadedS3Object = new File(fileName);
|
||||
try (InputStream inputStream = resource.getInputStream()) {
|
||||
Files.copy(inputStream, downloadedS3Object.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.spring.cloud.aws.s3;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.model.ListObjectsV2Result;
|
||||
import com.amazonaws.services.s3.model.S3ObjectSummary;
|
||||
|
||||
@Component
|
||||
public class SpringCloudS3Service {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SpringCloudS3Service.class);
|
||||
|
||||
@Autowired
|
||||
AmazonS3 amazonS3;
|
||||
|
||||
@Autowired
|
||||
SpringCloudS3 springCloudS3;
|
||||
|
||||
public void createBucket(String bucketName) {
|
||||
logger.debug("Creating S3 bucket: {}", bucketName);
|
||||
amazonS3.createBucket(bucketName);
|
||||
logger.info("{} bucket created successfully", bucketName);
|
||||
}
|
||||
|
||||
public void downloadObject(String bucketName, String objectName) {
|
||||
String s3Url = "s3://" + bucketName + "/" + objectName;
|
||||
try {
|
||||
springCloudS3.downloadS3Object(s3Url);
|
||||
logger.info("{} file download result: {}", objectName, new File(objectName).exists());
|
||||
} catch (IOException e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void uploadObject(String bucketName, String objectName) {
|
||||
String s3Url = "s3://" + bucketName + "/" + objectName;
|
||||
File file = new File(objectName);
|
||||
try {
|
||||
springCloudS3.uploadFileToS3(file, s3Url);
|
||||
logger.info("{} file uploaded to S3", objectName);
|
||||
} catch (IOException e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteBucket(String bucketName) {
|
||||
logger.trace("Deleting S3 objects under {} bucket...", bucketName);
|
||||
ListObjectsV2Result listObjectsV2Result = amazonS3.listObjectsV2(bucketName);
|
||||
for (S3ObjectSummary objectSummary : listObjectsV2Result.getObjectSummaries()) {
|
||||
logger.info("Deleting S3 object: {}", objectSummary.getKey());
|
||||
amazonS3.deleteObject(bucketName, objectSummary.getKey());
|
||||
}
|
||||
logger.info("Deleting S3 bucket: {}", bucketName);
|
||||
amazonS3.deleteBucket(bucketName);
|
||||
}
|
||||
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.spring.cloud.aws.sns;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.aws.messaging.config.annotation.NotificationMessage;
|
||||
import org.springframework.cloud.aws.messaging.config.annotation.NotificationSubject;
|
||||
import org.springframework.cloud.aws.messaging.endpoint.NotificationStatus;
|
||||
import org.springframework.cloud.aws.messaging.endpoint.annotation.NotificationMessageMapping;
|
||||
import org.springframework.cloud.aws.messaging.endpoint.annotation.NotificationSubscriptionMapping;
|
||||
import org.springframework.cloud.aws.messaging.endpoint.annotation.NotificationUnsubscribeConfirmationMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/topic-subscriber")
|
||||
public class SNSEndpointController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SNSEndpointController.class);
|
||||
|
||||
@NotificationMessageMapping
|
||||
public void receiveNotification(@NotificationMessage String message, @NotificationSubject String subject) {
|
||||
logger.info("Received message: {}, having subject: {}", message, subject);
|
||||
}
|
||||
|
||||
@NotificationUnsubscribeConfirmationMapping
|
||||
public void confirmSubscriptionMessage(NotificationStatus notificationStatus) {
|
||||
logger.info("Unsubscribed from Topic");
|
||||
notificationStatus.confirmSubscription();
|
||||
}
|
||||
|
||||
@NotificationSubscriptionMapping
|
||||
public void confirmUnsubscribeMessage(NotificationStatus notificationStatus) {
|
||||
logger.info("Subscribed to Topic");
|
||||
notificationStatus.confirmSubscription();
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.spring.cloud.aws.sns;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.aws.messaging.core.NotificationMessagingTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SNSMessageSender {
|
||||
|
||||
@Autowired
|
||||
NotificationMessagingTemplate notificationMessagingTemplate;
|
||||
|
||||
public void send(String topicName, Object message, String subject) {
|
||||
notificationMessagingTemplate.sendNotification(topicName, message, subject);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.spring.cloud.aws.sqs;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate;
|
||||
import org.springframework.cloud.aws.messaging.listener.annotation.SqsListener;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.messaging.handler.annotation.Header;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
@Component
|
||||
@Lazy
|
||||
public class SpringCloudSQS {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SpringCloudSQS.class);
|
||||
|
||||
static final String QUEUE_NAME = "spring-cloud-test-queue";
|
||||
|
||||
/*
|
||||
* CountDownLatch is added to wait for messages
|
||||
* during integration test
|
||||
*/
|
||||
CountDownLatch countDownLatch;
|
||||
|
||||
public void setCountDownLatch(CountDownLatch countDownLatch) {
|
||||
this.countDownLatch = countDownLatch;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
QueueMessagingTemplate queueMessagingTemplate;
|
||||
|
||||
@SqsListener(QUEUE_NAME)
|
||||
public void receiveMessage(String message, @Header("SenderId") String senderId) {
|
||||
logger.info("Received message: {}, having SenderId: {}", message, senderId);
|
||||
if (countDownLatch != null) {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
public void send(String queueName, Object message) {
|
||||
queueMessagingTemplate.convertAndSend(queueName, message);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
AWSTemplateFormatVersion: 2010-09-09
|
||||
Metadata:
|
||||
'AWS::CloudFormation::Designer':
|
||||
157e7d5f-5cb3-4a23-a50c-97e7f6c57173:
|
||||
size:
|
||||
width: 60
|
||||
height: 60
|
||||
position:
|
||||
x: 450
|
||||
'y': 90
|
||||
z: 0
|
||||
embeds: []
|
||||
9bbaaa55-9cba-4555-a7c6-fb6ac248fd3a:
|
||||
size:
|
||||
width: 60
|
||||
height: 60
|
||||
position:
|
||||
x: 260
|
||||
'y': 90
|
||||
z: 0
|
||||
embeds: []
|
||||
isassociatedwith:
|
||||
- 157e7d5f-5cb3-4a23-a50c-97e7f6c57173
|
||||
a7348729-a594-4dca-9b0a-e1c8d777dc3b:
|
||||
size:
|
||||
width: 60
|
||||
height: 60
|
||||
position:
|
||||
x: 70
|
||||
'y': 90
|
||||
z: 0
|
||||
embeds: []
|
||||
Resources:
|
||||
IAMRoleBaeldung:
|
||||
Type: 'AWS::IAM::Role'
|
||||
Properties:
|
||||
AssumeRolePolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
- Effect: Allow
|
||||
Principal:
|
||||
Service:
|
||||
- ec2.amazonaws.com
|
||||
Action:
|
||||
- 'sts:AssumeRole'
|
||||
ManagedPolicyArns:
|
||||
- 'arn:aws:iam::aws:policy/AmazonS3FullAccess'
|
||||
Metadata:
|
||||
'AWS::CloudFormation::Designer':
|
||||
id: 157e7d5f-5cb3-4a23-a50c-97e7f6c57173
|
||||
InstanceProfileBaeldung:
|
||||
Type: 'AWS::IAM::InstanceProfile'
|
||||
Properties:
|
||||
Roles:
|
||||
- !Ref IAMRoleBaeldung
|
||||
Metadata:
|
||||
'AWS::CloudFormation::Designer':
|
||||
id: 9bbaaa55-9cba-4555-a7c6-fb6ac248fd3a
|
||||
EC2Instance:
|
||||
Type: 'AWS::EC2::Instance'
|
||||
Properties:
|
||||
ImageId: ami-2581aa40
|
||||
InstanceType: t2.micro
|
||||
IamInstanceProfile: !Ref InstanceProfileBaeldung
|
||||
KeyName: Satish-Ohio
|
||||
UserData: !Base64
|
||||
'Fn::Join':
|
||||
- ''
|
||||
- - |
|
||||
#!/bin/bash
|
||||
- |
|
||||
apt -y install openjdk-8-jre-headless
|
||||
Metadata:
|
||||
'AWS::CloudFormation::Designer':
|
||||
id: a7348729-a594-4dca-9b0a-e1c8d777dc3b
|
||||
DependsOn:
|
||||
- InstanceProfileBaeldung
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
# Don't try to create DataSouce when running tests which don't need a DataSource
|
||||
spring.autoconfigure.exclude=\
|
||||
org.springframework.cloud.aws.autoconfigure.jdbc.AmazonRdsDatabaseAutoConfiguration,\
|
||||
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
|
||||
cloud.aws.region.auto=true
|
||||
|
||||
# Load instance profile credentials
|
||||
cloud.aws.credentials.instanceProfile=true
|
||||
|
||||
# Disable auto cloud formation
|
||||
cloud.aws.stack.auto=false
|
||||
|
||||
# Disable web environment
|
||||
spring.main.web-environment=false
|
||||
@@ -0,0 +1,13 @@
|
||||
cloud.aws.credentials.accessKey=YourAccessKey
|
||||
cloud.aws.credentials.secretKey=YourSecretKey
|
||||
cloud.aws.region.static=us-east-1
|
||||
|
||||
cloud.aws.rds.spring-cloud-test-db.password=se3retpass
|
||||
|
||||
# These 3 properties are optional
|
||||
cloud.aws.rds.spring-cloud-test-db.username=testuser
|
||||
cloud.aws.rds.spring-cloud-test-db.readReplicaSupport=true
|
||||
cloud.aws.rds.spring-cloud-test-db.databaseName=test
|
||||
|
||||
# Disable auto cloudformation
|
||||
cloud.aws.stack.auto=false
|
||||
@@ -0,0 +1,11 @@
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:aws-context="http://www.springframework.org/schema/cloud/aws/context"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/cloud/aws/context
|
||||
http://www.springframework.org/schema/cloud/aws/context/spring-cloud-aws-context.xsd">
|
||||
|
||||
<aws-context:context-instance-data user-tags-map="instanceData" />
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user