Search in sources :

Example 46 with GetObjectRequest

use of software.amazon.awssdk.services.s3.model.GetObjectRequest in project photon-model by vmware.

the class AWSCostStatsService method downloadParseAndCreateStats.

private void downloadParseAndCreateStats(AWSCostStatsCreationContext statsData, String awsBucketName) throws IOException {
    try {
        // Creating a working directory for downloading and processing the bill
        final Path workingDirPath = Paths.get(System.getProperty(TEMP_DIR_LOCATION), UUID.randomUUID().toString());
        Files.createDirectories(workingDirPath);
        AWSCsvBillParser parser = new AWSCsvBillParser();
        final String csvBillZipFileName = parser.getCsvBillFileName(statsData.billMonthToDownload, statsData.accountId, true);
        Path csvBillZipFilePath = Paths.get(workingDirPath.toString(), csvBillZipFileName);
        ProgressListener listener = new ProgressListener() {

            @Override
            public void progressChanged(ProgressEvent progressEvent) {
                try {
                    ProgressEventType eventType = progressEvent.getEventType();
                    if (ProgressEventType.TRANSFER_COMPLETED_EVENT.equals(eventType)) {
                        OperationContext.restoreOperationContext(statsData.opContext);
                        LocalDate billMonth = new LocalDate(statsData.billMonthToDownload.getYear(), statsData.billMonthToDownload.getMonthOfYear(), 1);
                        logWithContext(statsData, Level.INFO, () -> String.format("Processing" + " bill for the month: %s.", billMonth));
                        parser.parseDetailedCsvBill(statsData.ignorableInvoiceCharge, csvBillZipFilePath, statsData.awsAccountIdToComputeStates.keySet(), getHourlyStatsConsumer(billMonth, statsData), getMonthlyStatsConsumer(billMonth, statsData));
                        deleteTempFiles();
                        // Continue downloading and processing the bills for past and current months' bills
                        statsData.billMonthToDownload = statsData.billMonthToDownload.plusMonths(1);
                        handleCostStatsCreationRequest(statsData);
                    } else if (ProgressEventType.TRANSFER_FAILED_EVENT.equals(eventType)) {
                        deleteTempFiles();
                        billDownloadFailureHandler(statsData, awsBucketName, new IOException("Download of AWS CSV Bill '" + csvBillZipFileName + "' failed."));
                    }
                } catch (Exception exception) {
                    deleteTempFiles();
                    billDownloadFailureHandler(statsData, awsBucketName, exception);
                }
            }

            private void deleteTempFiles() {
                try {
                    Files.deleteIfExists(csvBillZipFilePath);
                    Files.deleteIfExists(workingDirPath);
                } catch (IOException e) {
                // Ignore IO exception while cleaning files.
                }
            }
        };
        GetObjectRequest getObjectRequest = new GetObjectRequest(awsBucketName, csvBillZipFileName).withGeneralProgressListener(listener);
        statsData.s3Client.download(getObjectRequest, csvBillZipFilePath.toFile());
    } catch (AmazonS3Exception s3Exception) {
        billDownloadFailureHandler(statsData, awsBucketName, s3Exception);
    }
}
Also used : Path(java.nio.file.Path) ProgressEventType(com.amazonaws.event.ProgressEventType) ProgressListener(com.amazonaws.event.ProgressListener) AWSCsvBillParser(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSCsvBillParser) IOException(java.io.IOException) AmazonS3Exception(com.amazonaws.services.s3.model.AmazonS3Exception) ProgressEvent(com.amazonaws.event.ProgressEvent) LocalDate(org.joda.time.LocalDate) GetObjectRequest(com.amazonaws.services.s3.model.GetObjectRequest) AmazonS3Exception(com.amazonaws.services.s3.model.AmazonS3Exception) IOException(java.io.IOException)

Example 47 with GetObjectRequest

use of software.amazon.awssdk.services.s3.model.GetObjectRequest in project airpal by airbnb.

the class S3FilesResource method getFile.

@GET
@Path("/{filename}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile(@PathParam("filename") String filename) {
    val outputKey = getOutputKey(filename);
    val getRequest = new GetObjectRequest(outputBucket, outputKey);
    final val object = s3Client.getObject(getRequest);
    if (object == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    } else {
        ObjectMetadata objectMetadata = object.getObjectMetadata();
        Response.ResponseBuilder builder = Response.ok().type(objectMetadata.getContentType());
        if (objectMetadata.getContentEncoding() != null) {
            // gzip
            builder = builder.encoding(objectMetadata.getContentEncoding());
        }
        return builder.entity(new StreamingOutput() {

            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                try (InputStream objectData = object.getObjectContent()) {
                    ByteStreams.copy(objectData, output);
                } finally {
                    output.close();
                }
            }
        }).build();
    }
}
Also used : lombok.val(lombok.val) Response(javax.ws.rs.core.Response) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) StreamingOutput(javax.ws.rs.core.StreamingOutput) GetObjectRequest(com.amazonaws.services.s3.model.GetObjectRequest) ObjectMetadata(com.amazonaws.services.s3.model.ObjectMetadata) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 48 with GetObjectRequest

use of software.amazon.awssdk.services.s3.model.GetObjectRequest in project XRTB by benmfaul.

the class AwsCommander method load.

/**
 * Load the file or s3 object.
 * @param parts String[]. An array of tokens.
 * @return String. The message returned from the load command.
 * @throws Exception on I/O errirs.
 */
String load(String[] parts) throws Exception {
    String otype = null;
    String symbolName = null;
    String name;
    // file or S3
    String type = parts[1];
    // }
    if (type.equalsIgnoreCase("S3")) {
        // bloom, cache, cuckoo.
        otype = parts[2];
        name = parts[4];
        // name of the object
        symbolName = parts[3];
        if (!symbolName.startsWith("$"))
            symbolName = "$" + symbolName;
    } else
        // file name
        name = parts[2];
    if (type.equals("file")) {
        return Configuration.getInstance().readData(parts[2]);
    }
    S3Object object = Configuration.s3.getObject(new GetObjectRequest(Configuration.s3_bucket, name));
    long size = Configuration.s3.getObjectMetadata(Configuration.s3_bucket, name).getContentLength();
    return Configuration.getInstance().readData(otype, symbolName, object, size);
}
Also used : S3Object(com.amazonaws.services.s3.model.S3Object) GetObjectRequest(com.amazonaws.services.s3.model.GetObjectRequest)

Example 49 with GetObjectRequest

use of software.amazon.awssdk.services.s3.model.GetObjectRequest in project aws-doc-sdk-examples by awsdocs.

the class DetectPPE method getObjectBytes.

public static byte[] getObjectBytes(S3Client s3, String bucketName, String keyName) {
    try {
        GetObjectRequest objectRequest = GetObjectRequest.builder().key(keyName).bucket(bucketName).build();
        ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
        byte[] data = objectBytes.asByteArray();
        return data;
    } catch (S3Exception e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    return null;
}
Also used : GetObjectResponse(software.amazon.awssdk.services.s3.model.GetObjectResponse) S3Exception(software.amazon.awssdk.services.s3.model.S3Exception) GetObjectRequest(software.amazon.awssdk.services.s3.model.GetObjectRequest)

Example 50 with GetObjectRequest

use of software.amazon.awssdk.services.s3.model.GetObjectRequest in project aws-doc-sdk-examples by awsdocs.

the class MovieLensDatasetProvider method getObjectBytes.

// Checks to see if the dataset is already uploaded to s3.
public static boolean getObjectBytes(S3Client s3Client, String bucketName, String keyName) {
    try {
        GetObjectRequest objectRequest = GetObjectRequest.builder().key(keyName).bucket(bucketName).build();
        ResponseBytes<GetObjectResponse> objectBytes = s3Client.getObjectAsBytes(objectRequest);
        byte[] data = objectBytes.asByteArray();
        return data.length > 0;
    } catch (NoSuchKeyException | NoSuchBucketException ex) {
        return false;
    } catch (S3Exception s3Exception) {
        System.err.println(s3Exception.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    return false;
}
Also used : NoSuchKeyException(software.amazon.awssdk.services.s3.model.NoSuchKeyException) GetObjectResponse(software.amazon.awssdk.services.s3.model.GetObjectResponse) S3Exception(software.amazon.awssdk.services.s3.model.S3Exception) NoSuchBucketException(software.amazon.awssdk.services.s3.model.NoSuchBucketException) GetObjectRequest(software.amazon.awssdk.services.s3.model.GetObjectRequest)

Aggregations

GetObjectRequest (com.amazonaws.services.s3.model.GetObjectRequest)40 IOException (java.io.IOException)24 S3Object (com.amazonaws.services.s3.model.S3Object)23 GetObjectRequest (software.amazon.awssdk.services.s3.model.GetObjectRequest)17 S3Exception (software.amazon.awssdk.services.s3.model.S3Exception)14 GetObjectResponse (software.amazon.awssdk.services.s3.model.GetObjectResponse)13 AmazonClientException (com.amazonaws.AmazonClientException)10 InputStream (java.io.InputStream)9 File (java.io.File)8 ObjectMetadata (com.amazonaws.services.s3.model.ObjectMetadata)5 FileOutputStream (java.io.FileOutputStream)5 OutputStream (java.io.OutputStream)5 AmazonS3 (com.amazonaws.services.s3.AmazonS3)4 AmazonS3Exception (com.amazonaws.services.s3.model.AmazonS3Exception)4 Date (java.util.Date)4 S3Client (software.amazon.awssdk.services.s3.S3Client)4 AmazonServiceException (com.amazonaws.AmazonServiceException)3 Test (org.junit.jupiter.api.Test)3 SelfServiceConfig (uk.gov.ida.hub.config.configuration.SelfServiceConfig)3 RemoteConfigCollection (uk.gov.ida.hub.config.domain.remoteconfig.RemoteConfigCollection)3