Last active
April 11, 2019 09:08
-
-
Save JamesZoft/afa3f59801012c7dde94832bc9007e9f to your computer and use it in GitHub Desktop.
Uploads screenshots to a specified S3 bucket.
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 com.amazonaws.AmazonServiceException; | |
import com.amazonaws.SdkClientException; | |
import com.amazonaws.auth.AWSStaticCredentialsProvider; | |
import com.amazonaws.auth.BasicAWSCredentials; | |
import com.amazonaws.regions.Regions; | |
import com.amazonaws.services.s3.AmazonS3; | |
import com.amazonaws.services.s3.AmazonS3ClientBuilder; | |
import com.amazonaws.services.s3.model.ObjectMetadata; | |
import com.amazonaws.services.s3.model.PutObjectRequest; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import java.io.ByteArrayInputStream; | |
import java.io.IOException; | |
import java.util.Calendar; | |
import java.util.Date; | |
class SeleniumScreenshotUploader { | |
private static final Logger LOGGER = LoggerFactory.getLogger(SeleniumScreenshotUploader.class); | |
String uploadSeleniumScreenshot(byte[] screenshotBytes) throws SdkClientException { | |
String filename = new Date().getTime() + ".png"; | |
ByteArrayInputStream is = new ByteArrayInputStream(screenshotBytes); | |
AmazonS3 s3Client = getClient(); | |
ObjectMetadata metaData = new ObjectMetadata(); | |
metaData.setContentLength(screenshotBytes.length); | |
metaData.setContentDisposition("attachment; filename=" + filename); | |
PutObjectRequest request = new PutObjectRequest("my-bucket-name", filename, is, metaData); | |
try { | |
s3Client.putObject(request); | |
} catch (AmazonServiceException e) { | |
LOGGER.error(e.getErrorMessage() + " || Code: " + e.getErrorCode(), e); | |
} | |
try { | |
is.close(); | |
} catch (IOException e) { | |
LOGGER.error("IOException trying to close stream", e); | |
} | |
Calendar calendar = Calendar.getInstance(); | |
calendar.add(Calendar.DAY_OF_YEAR, 7); | |
return s3Client.generatePresignedUrl("my-bucket-name", filename, calendar.getTime()) | |
.toString(); | |
} | |
private AmazonS3 getClient() { | |
return AmazonS3ClientBuilder.standard() | |
.withCredentials(new AWSStaticCredentialsProvider( | |
new BasicAWSCredentials("access-key", "my-secret"))) | |
.withRegion(Regions.EU_WEST_1) | |
.build(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment