Search in sources :

Example 6 with Transfer

use of com.amazonaws.services.s3.transfer.Transfer in project aws-doc-sdk-examples by awsdocs.

the class XferMgrProgress method uploadFileWithListener.

public static void uploadFileWithListener(String file_path, String bucket_name, String key_prefix, boolean pause) {
    System.out.println("file: " + file_path + (pause ? " (pause)" : ""));
    String key_name = null;
    if (key_prefix != null) {
        key_name = key_prefix + '/' + file_path;
    } else {
        key_name = file_path;
    }
    File f = new File(file_path);
    TransferManager xfer_mgr = new TransferManager();
    try {
        Upload u = xfer_mgr.upload(bucket_name, key_name, f);
        // print an empty progress bar...
        printProgressBar(0.0);
        u.addProgressListener(new ProgressListener() {

            public void progressChanged(ProgressEvent e) {
                double pct = e.getBytesTransferred() * 100.0 / e.getBytes();
                eraseProgressBar();
                printProgressBar(pct);
            }
        });
        // block with Transfer.waitForCompletion()
        XferMgrProgress.waitForCompletion(u);
        // print the final state of the transfer.
        TransferState xfer_state = u.getState();
        System.out.println(": " + xfer_state);
    } catch (AmazonServiceException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    }
    xfer_mgr.shutdownNow();
}
Also used : TransferManager(com.amazonaws.services.s3.transfer.TransferManager) ProgressListener(com.amazonaws.event.ProgressListener) AmazonServiceException(com.amazonaws.AmazonServiceException) Upload(com.amazonaws.services.s3.transfer.Upload) MultipleFileUpload(com.amazonaws.services.s3.transfer.MultipleFileUpload) ProgressEvent(com.amazonaws.event.ProgressEvent) File(java.io.File) TransferState(com.amazonaws.services.s3.transfer.Transfer.TransferState)

Example 7 with Transfer

use of com.amazonaws.services.s3.transfer.Transfer in project aws-doc-sdk-examples by awsdocs.

the class XferMgrProgress method showMultiUploadProgress.

// Prints progress of a multiple file upload while waiting for it to finish.
public static void showMultiUploadProgress(MultipleFileUpload multi_upload) {
    // print the upload's human-readable description
    System.out.println(multi_upload.getDescription());
    Collection<? extends Upload> sub_xfers = new ArrayList<Upload>();
    sub_xfers = multi_upload.getSubTransfers();
    do {
        System.out.println("\nSubtransfer progress:\n");
        for (Upload u : sub_xfers) {
            System.out.println("  " + u.getDescription());
            if (u.isDone()) {
                TransferState xfer_state = u.getState();
                System.out.println("  " + xfer_state);
            } else {
                TransferProgress progress = u.getProgress();
                double pct = progress.getPercentTransferred();
                printProgressBar(pct);
                System.out.println();
            }
        }
        // wait a bit before the next update.
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            return;
        }
    } while (multi_upload.isDone() == false);
    // print the final state of the transfer.
    TransferState xfer_state = multi_upload.getState();
    System.out.println("\nMultipleFileUpload " + xfer_state);
}
Also used : ArrayList(java.util.ArrayList) Upload(com.amazonaws.services.s3.transfer.Upload) MultipleFileUpload(com.amazonaws.services.s3.transfer.MultipleFileUpload) TransferState(com.amazonaws.services.s3.transfer.Transfer.TransferState) TransferProgress(com.amazonaws.services.s3.transfer.TransferProgress)

Example 8 with Transfer

use of com.amazonaws.services.s3.transfer.Transfer in project opentest by mcdcorp.

the class GetS3Object method run.

@Override
public void run() {
    super.run();
    String awsCredentialsProfile = this.readStringArgument("awsProfile", "default");
    String bucket = this.readStringArgument("bucket");
    String objectKey = this.readStringArgument("objectKey");
    String targetFilePath = this.readStringArgument("targetFile");
    Boolean overwrite = this.readBooleanArgument("overwrite", false);
    AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider(awsCredentialsProfile));
    S3Object object = s3Client.getObject(new GetObjectRequest(bucket, objectKey));
    InputStream objectDataStream = object.getObjectContent();
    if (targetFilePath != null) {
        File targetFile = new File(targetFilePath);
        if (!targetFile.isAbsolute()) {
            targetFile = Paths.get(this.getActor().getTempDir().getAbsolutePath(), targetFilePath).toFile();
        }
        targetFile.getParentFile().mkdirs();
        try {
            if (overwrite) {
                Files.copy(objectDataStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } else {
                Files.copy(objectDataStream, targetFile.toPath());
            }
        } catch (Exception ex) {
            throw new RuntimeException(String.format("Failed to transfer data from the input stream into file %s", targetFilePath), ex);
        }
        this.writeArgument("targetFile", targetFile.getAbsolutePath());
    } else {
    // TODO: Make targetFile arg optional so this branch can execute.
    // Read data in memory and write it to an output value
    }
}
Also used : AmazonS3(com.amazonaws.services.s3.AmazonS3) AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) InputStream(java.io.InputStream) ProfileCredentialsProvider(com.amazonaws.auth.profile.ProfileCredentialsProvider) S3Object(com.amazonaws.services.s3.model.S3Object) GetObjectRequest(com.amazonaws.services.s3.model.GetObjectRequest) File(java.io.File)

Example 9 with Transfer

use of com.amazonaws.services.s3.transfer.Transfer in project jackrabbit-oak by apache.

the class S3Backend method init.

public void init() throws DataStoreException {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        startTime = new Date();
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        LOG.debug("init");
        s3ReqDecorator = new S3RequestDecorator(properties);
        s3service = Utils.openService(properties);
        if (bucket == null || "".equals(bucket.trim())) {
            bucket = properties.getProperty(S3Constants.S3_BUCKET);
            // Alternately check if the 'container' property is set
            if (Strings.isNullOrEmpty(bucket)) {
                bucket = properties.getProperty(S3Constants.S3_CONTAINER);
            }
        }
        String region = properties.getProperty(S3Constants.S3_REGION);
        Region s3Region;
        if (StringUtils.isNullOrEmpty(region)) {
            com.amazonaws.regions.Region ec2Region = Regions.getCurrentRegion();
            if (ec2Region != null) {
                s3Region = Region.fromValue(ec2Region.getName());
            } else {
                throw new AmazonClientException("parameter [" + S3Constants.S3_REGION + "] not configured and cannot be derived from environment");
            }
        } else {
            if (Utils.DEFAULT_AWS_BUCKET_REGION.equals(region)) {
                s3Region = Region.US_Standard;
            } else if (Region.EU_Ireland.toString().equals(region)) {
                s3Region = Region.EU_Ireland;
            } else {
                s3Region = Region.fromValue(region);
            }
        }
        if (!s3service.doesBucketExist(bucket)) {
            s3service.createBucket(bucket, s3Region);
            LOG.info("Created bucket [{}] in [{}] ", bucket, region);
        } else {
            LOG.info("Using bucket [{}] in [{}] ", bucket, region);
        }
        int writeThreads = 10;
        String writeThreadsStr = properties.getProperty(S3Constants.S3_WRITE_THREADS);
        if (writeThreadsStr != null) {
            writeThreads = Integer.parseInt(writeThreadsStr);
        }
        LOG.info("Using thread pool of [{}] threads in S3 transfer manager.", writeThreads);
        tmx = new TransferManager(s3service, Executors.newFixedThreadPool(writeThreads, new NamedThreadFactory("s3-transfer-manager-worker")));
        String renameKeyProp = properties.getProperty(S3Constants.S3_RENAME_KEYS);
        boolean renameKeyBool = (renameKeyProp == null || "".equals(renameKeyProp)) ? false : Boolean.parseBoolean(renameKeyProp);
        LOG.info("Rename keys [{}]", renameKeyBool);
        if (renameKeyBool) {
            renameKeys();
        }
        LOG.debug("S3 Backend initialized in [{}] ms", +(System.currentTimeMillis() - startTime.getTime()));
    } catch (Exception e) {
        LOG.error("Error ", e);
        Map<String, Object> filteredMap = Maps.newHashMap();
        if (properties != null) {
            filteredMap = Maps.filterKeys(Utils.asMap(properties), new Predicate<String>() {

                @Override
                public boolean apply(String input) {
                    return !input.equals(S3Constants.ACCESS_KEY) && !input.equals(S3Constants.SECRET_KEY);
                }
            });
        }
        throw new DataStoreException("Could not initialize S3 from " + filteredMap, e);
    } finally {
        if (contextClassLoader != null) {
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        }
    }
}
Also used : TransferManager(com.amazonaws.services.s3.transfer.TransferManager) DataStoreException(org.apache.jackrabbit.core.data.DataStoreException) NamedThreadFactory(org.apache.jackrabbit.core.data.util.NamedThreadFactory) AmazonClientException(com.amazonaws.AmazonClientException) Date(java.util.Date) AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonClientException(com.amazonaws.AmazonClientException) DataStoreException(org.apache.jackrabbit.core.data.DataStoreException) IOException(java.io.IOException) Region(com.amazonaws.services.s3.model.Region) Map(java.util.Map)

Example 10 with Transfer

use of com.amazonaws.services.s3.transfer.Transfer in project herd by FINRAOS.

the class BusinessObjectDataInitiateRestoreHelperServiceImplTest method testExecuteS3SpecificSteps.

@Test
public void testExecuteS3SpecificSteps() {
    // Create a business object data key.
    BusinessObjectDataKey businessObjectDataKey = new BusinessObjectDataKey(BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, PARTITION_VALUE, SUBPARTITION_VALUES, DATA_VERSION);
    // Create a list of storage files to be passed as an input.
    List<StorageFile> storageFiles = Arrays.asList(new StorageFile(S3_KEY, FILE_SIZE, ROW_COUNT));
    // Create a DTO for business object data restore parameters.
    BusinessObjectDataRestoreDto businessObjectDataRestoreDto = new BusinessObjectDataRestoreDto(businessObjectDataKey, STORAGE_NAME, S3_ENDPOINT, S3_BUCKET_NAME, S3_KEY_PREFIX, NO_STORAGE_UNIT_STATUS, NO_STORAGE_UNIT_STATUS, storageFiles, NO_EXCEPTION);
    // Create an S3 file transfer parameters DTO to access the S3 bucket.
    S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
    // Create an updated version of the S3 file transfer request parameters DTO.
    S3FileTransferRequestParamsDto updatedS3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
    updatedS3FileTransferRequestParamsDto.setS3BucketName(S3_BUCKET_NAME);
    updatedS3FileTransferRequestParamsDto.setS3Endpoint(S3_ENDPOINT);
    updatedS3FileTransferRequestParamsDto.setS3KeyPrefix(S3_KEY_PREFIX + "/");
    // Create a mock S3 object summary for S3 object that does not belong to Glacier storage class.
    S3ObjectSummary glacierS3ObjectSummary = mock(S3ObjectSummary.class);
    when(glacierS3ObjectSummary.getStorageClass()).thenReturn(StorageClass.Glacier.toString());
    // Create a mock S3 object summary for S3 object that does not belong to Glacier storage class.
    S3ObjectSummary standardS3ObjectSummary = mock(S3ObjectSummary.class);
    when(standardS3ObjectSummary.getStorageClass()).thenReturn(StorageClass.Standard.toString());
    // Create a list of S3 files.
    List<S3ObjectSummary> s3Files = Arrays.asList(glacierS3ObjectSummary, standardS3ObjectSummary);
    // Create a list of S3 objects that belong to Glacier storage class.
    List<S3ObjectSummary> glacierS3Files = Arrays.asList(glacierS3ObjectSummary);
    // Create a list of storage files that represent S3 objects of Glacier storage class.
    List<StorageFile> glacierStorageFiles = Arrays.asList(new StorageFile(S3_KEY, FILE_SIZE, ROW_COUNT));
    // Create a list of storage files selected for S3 object tagging.
    List<File> filesSelectedForRestore = Arrays.asList(new File(S3_KEY));
    // Create a final version of DTO for business object data restore parameters.
    S3FileTransferRequestParamsDto finalS3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
    finalS3FileTransferRequestParamsDto.setS3BucketName(S3_BUCKET_NAME);
    finalS3FileTransferRequestParamsDto.setS3Endpoint(S3_ENDPOINT);
    finalS3FileTransferRequestParamsDto.setS3KeyPrefix(S3_KEY_PREFIX + "/");
    finalS3FileTransferRequestParamsDto.setFiles(filesSelectedForRestore);
    // Mock the external calls.
    when(storageHelper.getS3FileTransferRequestParamsDto()).thenReturn(s3FileTransferRequestParamsDto);
    when(s3Service.listDirectory(updatedS3FileTransferRequestParamsDto, true)).thenReturn(s3Files);
    when(storageFileHelper.createStorageFilesFromS3ObjectSummaries(glacierS3Files)).thenReturn(glacierStorageFiles);
    when(storageFileHelper.getFiles(glacierStorageFiles)).thenReturn(filesSelectedForRestore);
    // Call the method under test.
    businessObjectDataInitiateRestoreHelperServiceImpl.executeS3SpecificSteps(businessObjectDataRestoreDto);
    // Verify the external calls.
    verify(storageHelper).getS3FileTransferRequestParamsDto();
    verify(s3Service).listDirectory(any(S3FileTransferRequestParamsDto.class), eq(true));
    verify(storageFileHelper).validateRegisteredS3Files(storageFiles, s3Files, STORAGE_NAME, businessObjectDataKey);
    verify(storageFileHelper).createStorageFilesFromS3ObjectSummaries(glacierS3Files);
    verify(storageFileHelper).getFiles(glacierStorageFiles);
    verify(s3Service).restoreObjects(finalS3FileTransferRequestParamsDto, 36135);
    verifyNoMoreInteractionsHelper();
}
Also used : S3FileTransferRequestParamsDto(org.finra.herd.model.dto.S3FileTransferRequestParamsDto) StorageFile(org.finra.herd.model.api.xml.StorageFile) S3ObjectSummary(com.amazonaws.services.s3.model.S3ObjectSummary) BusinessObjectDataKey(org.finra.herd.model.api.xml.BusinessObjectDataKey) BusinessObjectDataRestoreDto(org.finra.herd.model.dto.BusinessObjectDataRestoreDto) File(java.io.File) StorageFile(org.finra.herd.model.api.xml.StorageFile) AbstractServiceTest(org.finra.herd.service.AbstractServiceTest) Test(org.junit.Test)

Aggregations

S3FileTransferRequestParamsDto (org.finra.herd.model.dto.S3FileTransferRequestParamsDto)18 File (java.io.File)17 S3ObjectSummary (com.amazonaws.services.s3.model.S3ObjectSummary)14 Test (org.junit.Test)14 TransferManager (com.amazonaws.services.s3.transfer.TransferManager)13 AmazonClientException (com.amazonaws.AmazonClientException)11 AmazonServiceException (com.amazonaws.AmazonServiceException)8 Tag (com.amazonaws.services.s3.model.Tag)8 Transfer (com.amazonaws.services.s3.transfer.Transfer)8 IOException (java.io.IOException)8 AmazonS3Client (com.amazonaws.services.s3.AmazonS3Client)7 ObjectMetadata (com.amazonaws.services.s3.model.ObjectMetadata)7 S3FileTransferResultsDto (org.finra.herd.model.dto.S3FileTransferResultsDto)7 PutObjectRequest (com.amazonaws.services.s3.model.PutObjectRequest)5 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)5 BusinessObjectDataKey (org.finra.herd.model.api.xml.BusinessObjectDataKey)5 StorageFile (org.finra.herd.model.api.xml.StorageFile)5 TransferState (com.amazonaws.services.s3.transfer.Transfer.TransferState)4 ArrayList (java.util.ArrayList)4 AbstractDaoTest (org.finra.herd.dao.AbstractDaoTest)4