Created
March 13, 2023 17:18
-
-
Save iamcrypticcoder/c498b4a3858cd816b2665ebfb355c97b to your computer and use it in GitHub Desktop.
Spring Boot Services for AWS Java SDK v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.After | |
import org.junit.Before | |
import org.junit.Test | |
import org.junit.runner.RunWith | |
import org.springframework.beans.factory.annotation.Autowired | |
import org.springframework.boot.test.context.SpringBootTest | |
import org.springframework.test.context.ActiveProfiles | |
import org.springframework.test.context.junit4.SpringRunner | |
@RunWith(SpringRunner::class) | |
@SpringBootTest | |
@ActiveProfiles("test") | |
class AmazonCloudFrontServiceTests { | |
@Autowired | |
lateinit var amazonCloudFrontService: AmazonCloudFrontService | |
@Before | |
fun beforeTest() { | |
println("Before test") | |
} | |
@After | |
fun afterTest() { | |
println("After test") | |
} | |
@Test | |
fun should_Get_Signed_Url_When_Parameters_Are_Valid() { | |
try { | |
val s3ObjectKey = "profile_pictures/62dd772c31174bb14f3c7a80/62dd772c31174bb14f3c7a80_1658682931547.jpeg" | |
val signedUrl = amazonCloudFrontService.getSignedUrl(s3ObjectKey) | |
println("Cloudfront signed url = $signedUrl") | |
} catch (ex: RuntimeException) { | |
ex.printStackTrace() | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import okhttp3.MediaType.Companion.toMediaType | |
import okhttp3.OkHttpClient | |
import okhttp3.Request | |
import okhttp3.RequestBody.Companion.asRequestBody | |
import org.apache.tika.Tika | |
import org.assertj.core.api.Assertions | |
import org.hibernate.service.spi.ServiceException | |
import org.junit.After | |
import org.junit.Assert | |
import org.junit.Before | |
import org.junit.Test | |
import org.junit.runner.RunWith | |
import org.slf4j.LoggerFactory | |
import org.springframework.beans.factory.annotation.Autowired | |
import org.springframework.boot.test.context.SpringBootTest | |
import org.springframework.core.io.FileSystemResource | |
import org.springframework.http.HttpEntity | |
import org.springframework.http.HttpHeaders | |
import org.springframework.http.HttpStatus | |
import org.springframework.http.HttpStatusCode | |
import org.springframework.http.MediaType | |
import org.springframework.http.client.MultipartBodyBuilder | |
import org.springframework.mock.web.MockMultipartFile | |
import org.springframework.test.context.ActiveProfiles | |
import org.springframework.test.context.junit4.SpringRunner | |
import org.springframework.util.LinkedMultiValueMap | |
import org.springframework.web.client.RestTemplate | |
import org.springframework.web.reactive.function.BodyInserters | |
import org.springframework.web.reactive.function.client.WebClient | |
import reactor.core.publisher.Mono | |
import software.amazon.awssdk.core.exception.SdkClientException | |
import java.io.FileInputStream | |
import java.io.IOException | |
import java.io.OutputStreamWriter | |
import java.net.HttpURLConnection | |
import java.net.URL | |
import java.nio.file.FileSystems | |
import java.nio.file.Path | |
@RunWith(SpringRunner::class) | |
@SpringBootTest | |
@ActiveProfiles("test") | |
class AmazonS3ServiceTests { | |
@Autowired | |
lateinit var awsS3Service: AmazonS3Service | |
val logger = LoggerFactory.getLogger(AmazonS3ServiceTests::class.java) | |
@Before | |
fun beforeTest() { | |
logger.info("Before test") | |
} | |
@After | |
fun afterTest() { | |
logger.info("After test") | |
} | |
@Test | |
fun should_Throw_SdkClientException_When_Network_Is_Unavailable() { | |
try { | |
awsS3Service.createBucket(TEST_BUCKET_NAME) | |
awsS3Service.deleteBucket(TEST_BUCKET_NAME) | |
} catch (ex: SdkClientException) { | |
ex.printStackTrace() | |
Assertions.assertThatExceptionOfType(SdkClientException::class.java) | |
} | |
} | |
@Test | |
fun should_Create_Bucket_When_Bucket_Name_Is_Valid() { | |
try { | |
// At first deleting if exist | |
awsS3Service.deleteObjectsInBucket(TEST_BUCKET_NAME) | |
awsS3Service.deleteBucket(TEST_BUCKET_NAME) | |
val success = awsS3Service.createBucket(TEST_BUCKET_NAME) | |
Assert.assertTrue(success) | |
val list = awsS3Service.getBucketList() | |
assert(list.contains(TEST_BUCKET_NAME)) | |
// At end deleting again | |
awsS3Service.deleteObjectsInBucket(TEST_BUCKET_NAME) | |
awsS3Service.deleteBucket(TEST_BUCKET_NAME) | |
} catch (ex: Exception) { | |
ex.printStackTrace() | |
assert(false) | |
} | |
} | |
@Test | |
fun should_Bucket_Creation_Fail_When_Bucket_Name_Is_Invalid() { | |
try { | |
awsS3Service.createBucket(TEST_BUCKET_NAME) | |
} catch (ex: IllegalArgumentException) { | |
ex.printStackTrace() | |
Assertions.assertThatExceptionOfType(IllegalArgumentException::class.java) | |
} | |
} | |
@Test | |
fun should_Get_Bucket_List_When_No_Condition() { | |
try { | |
val list = awsS3Service.getBucketList() | |
println("Bucket Count = ${list.size}") | |
list.forEach(System.out::println) | |
} catch (ex: RuntimeException) { | |
ex.printStackTrace() | |
} | |
} | |
@Test | |
fun should_Delete_Bucket_When_No_Condition() { | |
try { | |
awsS3Service.deleteBucket(TEST_BUCKET_NAME) | |
} catch (ex: RuntimeException) { | |
ex.printStackTrace() | |
} | |
} | |
@Test | |
fun should_Put_Object_Pass_When_File_Path_Is_Valid() { | |
// Create bucket | |
awsS3Service.createBucket(TEST_BUCKET_NAME) | |
// Put object | |
val path: Path = FileSystems.getDefault().getPath("sample_image_1.png") | |
println(path.toFile().absolutePath) | |
awsS3Service.putObject(TEST_BUCKET_NAME, path.toFile().name, path.toFile().absolutePath) | |
// Delete all object in bucket | |
awsS3Service.deleteObjectsInBucket(TEST_BUCKET_NAME) | |
// Delete bucket | |
awsS3Service.deleteBucket(TEST_BUCKET_NAME) | |
} | |
@Test | |
fun should_Put_Object_Throw_NoSuchFileException_When_File_Path_Is_Invalid() { | |
try { | |
// Create bucket | |
awsS3Service.createBucket(TEST_BUCKET_NAME) | |
// Put object | |
val path: Path = FileSystems.getDefault().getPath("sample_image_.png") | |
println(path.toFile().absolutePath) | |
awsS3Service.putObject(TEST_BUCKET_NAME, path.toFile().name, path.toFile().absolutePath) | |
// Delete all object in bucket | |
awsS3Service.deleteObjectsInBucket(TEST_BUCKET_NAME) | |
// Delete bucket | |
awsS3Service.deleteBucket(TEST_BUCKET_NAME) | |
} catch (ex: RuntimeException) { | |
ex.printStackTrace() | |
Assertions.assertThatExceptionOfType(NoSuchFileException::class.java) | |
} | |
} | |
@Test | |
fun should_Get_Object_List_When_Bucket_Name_Is_Given() { | |
try { | |
// Create bucket | |
awsS3Service.createBucket(TEST_BUCKET_NAME) | |
// Put object | |
val path: Path = FileSystems.getDefault().getPath("sample_image_1.png") | |
println(path.toFile().absolutePath) | |
awsS3Service.putObject(TEST_BUCKET_NAME, path.toFile().name, path.toFile().absolutePath) | |
val list = awsS3Service.getObjectList(TEST_BUCKET_NAME) | |
list.forEach { | |
println("The name of the key is " + it.key()); | |
println("The object is " + it.size()/1024 + " KBs"); | |
println("The owner is " + it.owner()); | |
} | |
Assert.assertEquals("sample_image_1.png", list[0].key()) | |
// Delete all object in bucket | |
awsS3Service.deleteObjectsInBucket(TEST_BUCKET_NAME) | |
// Delete bucket | |
awsS3Service.deleteBucket(TEST_BUCKET_NAME) | |
} catch (ex: RuntimeException) { | |
ex.printStackTrace() | |
} | |
} | |
@Test | |
fun should_Get_PreSigned_Put_Url_When_All_Valid() { | |
try { | |
// Create bucket | |
awsS3Service.createBucket(TEST_BUCKET_NAME) | |
// Get presigned url | |
val preSignedUrl = awsS3Service.getPreSignedPutUrl(TEST_BUCKET_NAME, "sample_image_1.png", "image/png") | |
logger.info("preSignedUrl = $preSignedUrl") | |
Assert.assertNotEquals("", preSignedUrl) | |
// Delete all object in bucket | |
//awsS3Service.deleteObjectsInBucket(TEST_BUCKET_NAME) | |
// Delete bucket | |
//awsS3Service.deleteBucket(TEST_BUCKET_NAME) | |
} catch(ex: RuntimeException) { | |
ex.printStackTrace() | |
} | |
} | |
@Test | |
fun should_Get_Presigned_Get_Url_When_All_Valid() { | |
try { | |
// Create bucket | |
awsS3Service.createBucket(TEST_BUCKET_NAME) | |
// Put object | |
val path: Path = FileSystems.getDefault().getPath("sample_image_1.png") | |
println(path.toFile().absolutePath) | |
awsS3Service.putObject(TEST_BUCKET_NAME, path.toFile().name, path.toFile().absolutePath) | |
// Get presigned put url | |
val presignedUrl = awsS3Service.getPreSignedGetUrl(TEST_BUCKET_NAME, "sample_image_1.png") | |
Assert.assertNotEquals("", presignedUrl) | |
// Delete bucket | |
//awsS3Service.deleteBucket(TEST_BUCKET_NAME) | |
} catch(ex: RuntimeException) { | |
ex.printStackTrace() | |
} | |
} | |
@Test | |
fun test_upload() { | |
// Get presigned url | |
val preSignedUrl = awsS3Service.getPreSignedPutUrl(TEST_BUCKET_NAME, "sample.txt", "text/plain") | |
// Upload content to the Amazon S3 bucket by using this URL. | |
// Upload content to the Amazon S3 bucket by using this URL. | |
val url: URL = URL(preSignedUrl) | |
// Create the connection and use it to upload the new object. | |
// Create the connection and use it to upload the new object. | |
val connection: HttpURLConnection = url.openConnection() as HttpURLConnection | |
connection.doOutput = true | |
connection.setRequestProperty("Content-Type", "text/plain") | |
connection.setRequestProperty("x-amz-meta-author", "Mary Doe") | |
connection.setRequestProperty("x-amz-meta-version", "1.0.0.0") | |
connection.requestMethod = "PUT" | |
val out = OutputStreamWriter(connection.outputStream) | |
out.write("This text was uploaded as an object by using a presigned URL.") | |
out.close() | |
println("HTTP response code is " + connection.responseCode) | |
println(connection.responseMessage) | |
} | |
@Test | |
fun test_File_Upload_With_Presigned_Url() { | |
// Create bucket | |
awsS3Service.createBucket(TEST_BUCKET_NAME) | |
val filePath = FileSystems.getDefault().getPath("profile_picture_1.jpg") | |
val file = filePath.toFile() | |
val mimeType = Tika().detect(file) | |
val objectKey = "profile_picture_1.jpg" | |
val preSignedUrl = awsS3Service.getPreSignedPutUrl(TEST_BUCKET_NAME, objectKey, mimeType) | |
logger.info("preSignedUrl = $preSignedUrl") | |
Assert.assertNotEquals("", preSignedUrl) | |
val client = OkHttpClient() | |
val request = Request.Builder() | |
.url(preSignedUrl) | |
.put(file.asRequestBody(mimeType.toMediaType())) | |
.build() | |
client.newCall(request).execute().use { response -> | |
if (!response.isSuccessful) throw IOException("Unexpected code $response") | |
logger.info("Status Code = ${response.code}") | |
} | |
val headResponse = awsS3Service.headObject(TEST_BUCKET_NAME, objectKey) | |
Assert.assertNotNull(headResponse) | |
logger.info("Content Type = ${headResponse?.contentType()}") | |
logger.info("Content Length = ${headResponse?.contentLength()}") | |
logger.info("Meta Data = ${headResponse?.metadata()}") | |
// Delete bucket | |
awsS3Service.deleteObjectsInBucket(TEST_BUCKET_NAME) | |
val success = awsS3Service.deleteBucket(TEST_BUCKET_NAME) | |
Assert.assertTrue(success) | |
} | |
companion object { | |
const val TEST_BUCKET_NAME = "spring-boot-test-bucket-1" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.After | |
import org.junit.Before | |
import org.junit.Test | |
import org.junit.runner.RunWith | |
import org.springframework.beans.factory.annotation.Autowired | |
import org.springframework.boot.test.context.SpringBootTest | |
import org.springframework.test.context.ActiveProfiles | |
import org.springframework.test.context.junit4.SpringRunner | |
import software.amazon.awssdk.services.sesv2.model.SesV2Exception | |
@RunWith(SpringRunner::class) | |
@SpringBootTest | |
@ActiveProfiles("test") | |
class AmazonSESServiceTests { | |
@Autowired | |
lateinit var amazonSesService: AmazonSESService | |
@Before | |
fun beforeTest() { | |
println("Before test") | |
} | |
@After | |
fun afterTest() { | |
println("After test") | |
} | |
@Test | |
fun should_Send_Text_Email_When_Parameters_Are_Correct() { | |
try { | |
val success = amazonSesService.sendTextEmail( | |
SENDER_EMAIL, | |
DESTINATION_EMAILS, | |
listOf(), | |
"This is subject", | |
"This is body" | |
) | |
assert(success) | |
} catch (ex: SesV2Exception) { | |
ex.printStackTrace() | |
} | |
} | |
@Test | |
fun should_Send_Templated_Email_When_Parameter_Are_Correct() { | |
try { | |
amazonSesService.sendTemplatedEmail( | |
SENDER_EMAIL, | |
DESTINATION_EMAILS, | |
listOf(), | |
"Account_Activation_Email", | |
mapOf( | |
Pair("userDisplayName", "userDisplayName"), | |
Pair("applicationName", "applicationName"), | |
Pair("companyAddress", "companyAddress"), | |
Pair("activationLink", "activationLink")) | |
) | |
} catch (ex: RuntimeException) { | |
ex.printStackTrace() | |
} | |
} | |
companion object { | |
const val SENDER_EMAIL = "[email protected]" | |
val DESTINATION_EMAILS = listOf( | |
"[email protected]", | |
"[email protected]") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.After | |
import org.junit.Assert | |
import org.junit.Before | |
import org.junit.Test | |
import org.junit.runner.RunWith | |
import org.springframework.beans.factory.annotation.Autowired | |
import org.springframework.boot.test.context.SpringBootTest | |
import org.springframework.test.context.ActiveProfiles | |
import org.springframework.test.context.junit4.SpringRunner | |
import org.springframework.web.reactive.function.client.WebClient | |
@RunWith(SpringRunner::class) | |
@SpringBootTest | |
@ActiveProfiles("test") | |
class AmazonSQSServiceTests { | |
@Autowired | |
lateinit var sqsService: AmazonSQSService | |
@Autowired | |
lateinit var webClient: WebClient | |
@Before | |
fun beforeTest() { | |
println("Before test") | |
} | |
@After | |
fun afterTest() { | |
println("After test") | |
} | |
@Test | |
fun test_Create_Queue() { | |
val queueUrl = sqsService.createQueue(TEST_QUEUE_NAME) | |
Assert.assertNotEquals("", queueUrl) | |
} | |
@Test | |
fun test_List_Queue() { | |
val list = sqsService.listQueues("") | |
println(list) | |
} | |
@Test | |
fun test_getQueueUrl() { | |
val queueUrl = sqsService.createQueue(TEST_QUEUE_NAME) | |
val url = sqsService.getQueueUrl(TEST_QUEUE_NAME) | |
Assert.assertNotEquals("", url) | |
} | |
@Test | |
fun test_deleteQueue() { | |
val queueUrl = sqsService.createQueue(TEST_QUEUE_NAME) | |
sqsService.deleteQueue(TEST_QUEUE_NAME) | |
} | |
@Test | |
fun test_sendMessage() { | |
val response = sqsService.sendMessage(TEST_QUEUE_URL, "Kazi Mahbubur Rahman") | |
Assert.assertTrue(response.isPresent) | |
println(response.get()) | |
} | |
@Test | |
fun test_sendMultipleMessage() { | |
val list = listOf("Message 1", "Message 2", "Message 3") | |
sqsService.sendMultipleMessage(TEST_QUEUE_URL, list) | |
} | |
@Test | |
fun test_receiveMessage() { | |
val list = sqsService.receiveMessages(TEST_QUEUE_URL) | |
println("Total message count = ${list.size}") | |
list.forEach { | |
println(it) | |
} | |
} | |
@Test | |
fun test_deleteMessages() { | |
val list = sqsService.receiveMessages(TEST_QUEUE_URL) | |
println("Total message count = ${list.size}") | |
list.forEach { | |
println(it) | |
} | |
val response = sqsService.deleteMessages(TEST_QUEUE_URL, list) | |
} | |
companion object { | |
val TEST_QUEUE_NAME = "spring_boot_test_queue_1" | |
val TEST_QUEUE_URL = "https://sqs.ap-southeast-1.amazonaws.com/703871/spring_boot_test_queue_1" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment