com.atlassian.maven.plugins.aws.it.Downloader.kt Maven / Gradle / Ivy
package com.atlassian.maven.plugins.aws.it
import com.amazonaws.services.cloudformation.model.StackResourceSummary
import com.amazonaws.services.s3.AmazonS3
import com.amazonaws.services.s3.AmazonS3ClientBuilder
import org.apache.maven.plugin.logging.Log
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
class Downloader(
private val workingDirectory: File,
private val log: Log
) {
fun download(
s3Downloads: List,
stackInfo: StackInfo
) {
val s3 = AmazonS3ClientBuilder.standard()
.withRegion(stackInfo.awsRegion)
.build()
s3Downloads.forEach {
val bucket = stackInfo.findBucket(it.bucketLogicalId)
download(bucket, s3)
}
}
private fun download(
bucket: StackResourceSummary,
s3: AmazonS3
) {
val bucketName = bucket.physicalResourceId
s3
.listObjects(bucketName)
.objectSummaries
.map { it.key }
.forEach {
val target = workingDirectory
.toPath()
.resolve("s3")
.resolve(bucket.logicalResourceId)
.resolve(it)
ensureParentDirectory(target)
log.info("Downloading $it as $target")
s3.getObject(bucketName, it).objectContent.use {
Files.copy(it, target, StandardCopyOption.REPLACE_EXISTING)
}
}
}
private fun ensureParentDirectory(
path: Path
) {
val parent = path.parent.toFile()
if (!parent.isDirectory) {
val success = parent.mkdirs()
if (!success) {
throw RuntimeException("Failed to ensure that the parent of $path is a directory")
}
}
}
}