Search in sources :

Example 46 with AmazonS3Client

use of com.talend.shaded.com.amazonaws.services.s3.AmazonS3Client in project herd by FINRAOS.

the class S3DaoImpl method generateGetObjectPresignedUrl.

@Override
public String generateGetObjectPresignedUrl(String bucketName, String key, Date expiration, S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto) {
    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);
    generatePresignedUrlRequest.setExpiration(expiration);
    AmazonS3Client s3 = getAmazonS3(s3FileTransferRequestParamsDto);
    try {
        return s3Operations.generatePresignedUrl(generatePresignedUrlRequest, s3).toString();
    } finally {
        s3.shutdown();
    }
}
Also used : AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) GeneratePresignedUrlRequest(com.amazonaws.services.s3.model.GeneratePresignedUrlRequest)

Example 47 with AmazonS3Client

use of com.talend.shaded.com.amazonaws.services.s3.AmazonS3Client in project herd by FINRAOS.

the class S3DaoImpl method deleteDirectory.

@Override
public void deleteDirectory(final S3FileTransferRequestParamsDto params) {
    LOGGER.info("Deleting keys/key versions from S3... s3KeyPrefix=\"{}\" s3BucketName=\"{}\"", params.getS3KeyPrefix(), params.getS3BucketName());
    Assert.isTrue(!isRootKeyPrefix(params.getS3KeyPrefix()), "Deleting from root directory is not allowed.");
    try {
        // List S3 versions.
        List<DeleteObjectsRequest.KeyVersion> keyVersions = listVersions(params);
        LOGGER.info("Found keys/key versions in S3 for deletion. s3KeyCount={} s3KeyPrefix=\"{}\" s3BucketName=\"{}\"", keyVersions.size(), params.getS3KeyPrefix(), params.getS3BucketName());
        // In order to avoid a MalformedXML AWS exception, we send delete request only when we have any key versions to delete.
        if (!keyVersions.isEmpty()) {
            // Create an S3 client.
            AmazonS3Client s3Client = getAmazonS3(params);
            try {
                // Delete the key versions.
                deleteKeyVersions(s3Client, params.getS3BucketName(), keyVersions);
            } finally {
                s3Client.shutdown();
            }
        }
    } catch (AmazonClientException e) {
        throw new IllegalStateException(String.format("Failed to delete keys/key versions with prefix \"%s\" from bucket \"%s\". Reason: %s", params.getS3KeyPrefix(), params.getS3BucketName(), e.getMessage()), e);
    }
}
Also used : AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) AmazonClientException(com.amazonaws.AmazonClientException)

Example 48 with AmazonS3Client

use of com.talend.shaded.com.amazonaws.services.s3.AmazonS3Client in project sandbox by irof.

the class S3MultipartUploadTest method 比較用の通常のputObject.

@Ignore
@Test
public void 比較用の通常のputObject() throws Exception {
    byte[] bytes = new byte[5 * Constants.MB + 1];
    ObjectMetadata meta = new ObjectMetadata();
    meta.setContentLength(bytes.length);
    PutObjectRequest putObjectRequest = new PutObjectRequest("irof-sandbox", "S3MultipartUpload/basic-5MB.dat", new ByteArrayInputStream(bytes), meta);
    PutObjectResult result = new AmazonS3Client().putObject(putObjectRequest);
    logger.info(result.getETag());
}
Also used : AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) ByteArrayInputStream(java.io.ByteArrayInputStream) PutObjectResult(com.amazonaws.services.s3.model.PutObjectResult) ObjectMetadata(com.amazonaws.services.s3.model.ObjectMetadata) PutObjectRequest(com.amazonaws.services.s3.model.PutObjectRequest) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 49 with AmazonS3Client

use of com.talend.shaded.com.amazonaws.services.s3.AmazonS3Client in project stocator by CODAIT.

the class COSAPIClient method initiate.

@Override
public void initiate(String scheme) throws IOException, ConfigurationParseException {
    mCachedSparkOriginated = new HashMap<String, Boolean>();
    mCachedSparkJobsStatus = new HashMap<String, Boolean>();
    schemaProvided = scheme;
    Properties props = ConfigurationHandler.initialize(filesystemURI, conf, scheme);
    // Set bucket name property
    int cacheSize = conf.getInt(CACHE_SIZE, GUAVA_CACHE_SIZE_DEFAULT);
    memoryCache = MemoryCache.getInstance(cacheSize);
    mBucket = props.getProperty(COS_BUCKET_PROPERTY);
    workingDir = new Path("/user", System.getProperty("user.name")).makeQualified(filesystemURI, getWorkingDirectory());
    LOG.trace("Working directory set to {}", workingDir);
    fModeAutomaticDelete = "true".equals(props.getProperty(FMODE_AUTOMATIC_DELETE_COS_PROPERTY, "false"));
    mIsV2Signer = "true".equals(props.getProperty(V2_SIGNER_TYPE_COS_PROPERTY, "false"));
    // Define COS client
    String accessKey = props.getProperty(ACCESS_KEY_COS_PROPERTY);
    String secretKey = props.getProperty(SECRET_KEY_COS_PROPERTY);
    if (accessKey == null) {
        throw new ConfigurationParseException("Access KEY is empty. Please provide valid access key");
    }
    if (secretKey == null) {
        throw new ConfigurationParseException("Secret KEY is empty. Please provide valid secret key");
    }
    BasicAWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey);
    ClientConfiguration clientConf = new ClientConfiguration();
    int maxThreads = Utils.getInt(conf, FS_COS, FS_ALT_KEYS, MAX_THREADS, DEFAULT_MAX_THREADS);
    if (maxThreads < 2) {
        LOG.warn(MAX_THREADS + " must be at least 2: forcing to 2.");
        maxThreads = 2;
    }
    int totalTasks = Utils.getInt(conf, FS_COS, FS_ALT_KEYS, MAX_TOTAL_TASKS, DEFAULT_MAX_TOTAL_TASKS);
    long keepAliveTime = Utils.getLong(conf, FS_COS, FS_ALT_KEYS, KEEPALIVE_TIME, DEFAULT_KEEPALIVE_TIME);
    threadPoolExecutor = BlockingThreadPoolExecutorService.newInstance(maxThreads, maxThreads + totalTasks, keepAliveTime, TimeUnit.SECONDS, "s3a-transfer-shared");
    unboundedThreadPool = new ThreadPoolExecutor(maxThreads, Integer.MAX_VALUE, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), BlockingThreadPoolExecutorService.newDaemonThreadFactory("s3a-transfer-unbounded"));
    boolean secureConnections = Utils.getBoolean(conf, FS_COS, FS_ALT_KEYS, SECURE_CONNECTIONS, DEFAULT_SECURE_CONNECTIONS);
    clientConf.setProtocol(secureConnections ? Protocol.HTTPS : Protocol.HTTP);
    String proxyHost = Utils.getTrimmed(conf, FS_COS, FS_ALT_KEYS, PROXY_HOST, "");
    int proxyPort = Utils.getInt(conf, FS_COS, FS_ALT_KEYS, PROXY_PORT, -1);
    if (!proxyHost.isEmpty()) {
        clientConf.setProxyHost(proxyHost);
        if (proxyPort >= 0) {
            clientConf.setProxyPort(proxyPort);
        } else {
            if (secureConnections) {
                LOG.warn("Proxy host set without port. Using HTTPS default 443");
                clientConf.setProxyPort(443);
            } else {
                LOG.warn("Proxy host set without port. Using HTTP default 80");
                clientConf.setProxyPort(80);
            }
        }
        String proxyUsername = Utils.getTrimmed(conf, FS_COS, FS_ALT_KEYS, PROXY_USERNAME);
        String proxyPassword = Utils.getTrimmed(conf, FS_COS, FS_ALT_KEYS, PROXY_PASSWORD);
        if ((proxyUsername == null) != (proxyPassword == null)) {
            String msg = "Proxy error: " + PROXY_USERNAME + " or " + PROXY_PASSWORD + " set without the other.";
            LOG.error(msg);
            throw new IllegalArgumentException(msg);
        }
        clientConf.setProxyUsername(proxyUsername);
        clientConf.setProxyPassword(proxyPassword);
        clientConf.setProxyDomain(Utils.getTrimmed(conf, FS_COS, FS_ALT_KEYS, PROXY_DOMAIN));
        clientConf.setProxyWorkstation(Utils.getTrimmed(conf, FS_COS, FS_ALT_KEYS, PROXY_WORKSTATION));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Using proxy server {}:{} as user {} on " + "domain {} as workstation {}", clientConf.getProxyHost(), clientConf.getProxyPort(), String.valueOf(clientConf.getProxyUsername()), clientConf.getProxyDomain(), clientConf.getProxyWorkstation());
        }
    } else if (proxyPort >= 0) {
        String msg = "Proxy error: " + PROXY_PORT + " set without " + PROXY_HOST;
        LOG.error(msg);
        throw new IllegalArgumentException(msg);
    }
    initConnectionSettings(conf, clientConf);
    if (mIsV2Signer) {
        clientConf.withSignerOverride("S3SignerType");
    }
    mClient = new AmazonS3Client(creds, clientConf);
    final String serviceUrl = props.getProperty(ENDPOINT_URL_COS_PROPERTY);
    if (serviceUrl != null && !serviceUrl.equals(amazonDefaultEndpoint)) {
        mClient.setEndpoint(serviceUrl);
    }
    mClient.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).build());
    // Set block size property
    String mBlockSizeString = props.getProperty(BLOCK_SIZE_COS_PROPERTY, "128");
    mBlockSize = Long.valueOf(mBlockSizeString).longValue() * 1024 * 1024L;
    bufferDirectory = Utils.getTrimmed(conf, FS_COS, FS_ALT_KEYS, BUFFER_DIR);
    bufferDirectoryKey = Utils.getConfigKey(conf, FS_COS, FS_ALT_KEYS, BUFFER_DIR);
    LOG.trace("Buffer directory is set to {} for the key {}", bufferDirectory, bufferDirectoryKey);
    boolean autoCreateBucket = "true".equalsIgnoreCase((props.getProperty(AUTO_BUCKET_CREATE_COS_PROPERTY, "false")));
    partSize = Utils.getLong(conf, FS_COS, FS_ALT_KEYS, MULTIPART_SIZE, DEFAULT_MULTIPART_SIZE);
    multiPartThreshold = Utils.getLong(conf, FS_COS, FS_ALT_KEYS, MIN_MULTIPART_THRESHOLD, DEFAULT_MIN_MULTIPART_THRESHOLD);
    readAhead = Utils.getLong(conf, FS_COS, FS_ALT_KEYS, READAHEAD_RANGE, DEFAULT_READAHEAD_RANGE);
    LOG.debug(READAHEAD_RANGE + ":" + readAhead);
    inputPolicy = COSInputPolicy.getPolicy(Utils.getTrimmed(conf, FS_COS, FS_ALT_KEYS, INPUT_FADVISE, INPUT_FADV_NORMAL));
    initTransferManager();
    maxKeys = Utils.getInt(conf, FS_COS, FS_ALT_KEYS, MAX_PAGING_KEYS, DEFAULT_MAX_PAGING_KEYS);
    flatListingFlag = Utils.getBoolean(conf, FS_COS, FS_ALT_KEYS, FLAT_LISTING, DEFAULT_FLAT_LISTING);
    if (autoCreateBucket) {
        try {
            boolean bucketExist = mClient.doesBucketExist(mBucket);
            if (bucketExist) {
                LOG.trace("Bucket {} exists", mBucket);
            } else {
                LOG.trace("Bucket {} doesn`t exists and autocreate", mBucket);
                String mRegion = props.getProperty(REGION_COS_PROPERTY);
                if (mRegion == null) {
                    mClient.createBucket(mBucket);
                } else {
                    LOG.trace("Creating bucket {} in region {}", mBucket, mRegion);
                    mClient.createBucket(mBucket, mRegion);
                }
            }
        } catch (AmazonServiceException ase) {
            /*
        *  we ignore the BucketAlreadyExists exception since multiple processes or threads
        *  might try to create the bucket in parrallel, therefore it is expected that
        *  some will fail to create the bucket
        */
            if (!ase.getErrorCode().equals("BucketAlreadyExists")) {
                LOG.error(ase.getMessage());
                throw (ase);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw (e);
        }
    }
    initMultipartUploads(conf);
    enableMultiObjectsDelete = Utils.getBoolean(conf, FS_COS, FS_ALT_KEYS, ENABLE_MULTI_DELETE, true);
    blockUploadEnabled = Utils.getBoolean(conf, FS_COS, FS_ALT_KEYS, FAST_UPLOAD, DEFAULT_FAST_UPLOAD);
    if (blockUploadEnabled) {
        blockOutputBuffer = Utils.getTrimmed(conf, FS_COS, FS_ALT_KEYS, FAST_UPLOAD_BUFFER, DEFAULT_FAST_UPLOAD_BUFFER);
        partSize = COSUtils.ensureOutputParameterInRange(MULTIPART_SIZE, partSize);
        blockFactory = COSDataBlocks.createFactory(this, blockOutputBuffer);
        blockOutputActiveBlocks = Utils.getInt(conf, FS_COS, FS_ALT_KEYS, FAST_UPLOAD_ACTIVE_BLOCKS, DEFAULT_FAST_UPLOAD_ACTIVE_BLOCKS);
        LOG.debug("Using COSBlockOutputStream with buffer = {}; block={};" + " queue limit={}", blockOutputBuffer, partSize, blockOutputActiveBlocks);
    } else {
        LOG.debug("Using COSOutputStream");
    }
}
Also used : StocatorPath(com.ibm.stocator.fs.common.StocatorPath) Path(org.apache.hadoop.fs.Path) ConfigurationParseException(com.ibm.stocator.fs.common.exception.ConfigurationParseException) Properties(java.util.Properties) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) BasicAWSCredentials(com.amazonaws.auth.BasicAWSCredentials) ConfigurationParseException(com.ibm.stocator.fs.common.exception.ConfigurationParseException) AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonClientException(com.amazonaws.AmazonClientException) InterruptedIOException(java.io.InterruptedIOException) AmazonS3Exception(com.amazonaws.services.s3.model.AmazonS3Exception) IOException(java.io.IOException) InvalidRequestException(org.apache.hadoop.fs.InvalidRequestException) FileNotFoundException(java.io.FileNotFoundException) COSUtils.translateException(com.ibm.stocator.fs.cos.COSUtils.translateException) AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) AmazonServiceException(com.amazonaws.AmazonServiceException) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ClientConfiguration(com.amazonaws.ClientConfiguration)

Example 50 with AmazonS3Client

use of com.talend.shaded.com.amazonaws.services.s3.AmazonS3Client in project acs-aem-commons by Adobe-Consulting-Services.

the class S3AssetIngestorTest method setup.

@Before
public void setup() throws PersistenceException {
    context.registerAdapter(ResourceResolver.class, AssetManager.class, new Function<ResourceResolver, AssetManager>() {

        @Nullable
        @Override
        public AssetManager apply(@Nullable ResourceResolver input) {
            return assetManager;
        }
    });
    context.create().resource("/content/dam", JcrConstants.JCR_PRIMARYTYPE, "sling:Folder");
    context.resourceResolver().commit();
    ingestor = new S3AssetIngestor(context.getService(MimeTypeService.class));
    ingestor.jcrBasePath = "/content/dam";
    ingestor.ignoreFileList = Collections.emptyList();
    ingestor.ignoreExtensionList = Collections.emptyList();
    ingestor.ignoreFolderList = Arrays.asList(".ds_store");
    ingestor.existingAssetAction = AssetIngestor.AssetAction.skip;
    int port = FreePortFinder.findFreeLocalPort();
    s3Mock = new S3Mock.Builder().withPort(port).withInMemoryBackend().build();
    s3Mock.start();
    S3ClientOptions options = S3ClientOptions.builder().setPathStyleAccess(true).build();
    s3Client = new AmazonS3Client(new AnonymousAWSCredentials());
    s3Client.setS3ClientOptions(options);
    s3Client.setEndpoint("http://localhost:" + port);
    ingestor.s3Client = s3Client;
    ingestor.bucket = TEST_BUCKET;
    s3Client.createBucket(TEST_BUCKET);
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            CheckedConsumer<ResourceResolver> method = (CheckedConsumer<ResourceResolver>) invocation.getArguments()[0];
            method.accept(context.resourceResolver());
            return null;
        }
    }).when(actionManager).deferredWithResolver(any(CheckedConsumer.class));
}
Also used : AssetManager(com.day.cq.dam.api.AssetManager) CheckedConsumer(com.adobe.acs.commons.functions.CheckedConsumer) AnonymousAWSCredentials(com.amazonaws.auth.AnonymousAWSCredentials) Answer(org.mockito.stubbing.Answer) AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) S3ClientOptions(com.amazonaws.services.s3.S3ClientOptions) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Nullable(javax.annotation.Nullable) Before(org.junit.Before)

Aggregations

AmazonS3Client (com.amazonaws.services.s3.AmazonS3Client)107 Test (org.junit.Test)23 BasicAWSCredentials (com.amazonaws.auth.BasicAWSCredentials)20 AmazonClientException (com.amazonaws.AmazonClientException)16 ClientConfiguration (com.amazonaws.ClientConfiguration)15 ArrayList (java.util.ArrayList)13 HashMap (java.util.HashMap)13 AmazonS3 (com.amazonaws.services.s3.AmazonS3)12 File (java.io.File)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)12 PutObjectResult (com.amazonaws.services.s3.model.PutObjectResult)11 UploadPartRequest (com.amazonaws.services.s3.model.UploadPartRequest)11 AWSCredentials (com.amazonaws.auth.AWSCredentials)10 AWSCredentialsProvider (com.amazonaws.auth.AWSCredentialsProvider)10 ObjectMetadata (com.amazonaws.services.s3.model.ObjectMetadata)10 AmazonServiceException (com.amazonaws.AmazonServiceException)9 AmazonS3Exception (com.amazonaws.services.s3.model.AmazonS3Exception)9 InternalEvent (com.nextdoor.bender.InternalEvent)9 TestContext (com.nextdoor.bender.aws.TestContext)9 IOException (java.io.IOException)9