Example usage for com.amazonaws.services.s3 AmazonS3Client AmazonS3Client

List of usage examples for com.amazonaws.services.s3 AmazonS3Client AmazonS3Client

Introduction

In this page you can find the example usage for com.amazonaws.services.s3 AmazonS3Client AmazonS3Client.

Prototype

@SdkInternalApi
AmazonS3Client(AmazonS3ClientParams s3ClientParams) 

Source Link

Document

Constructs a new client to invoke service methods on S3 using the specified parameters.

Usage

From source file:metrocasas.projectsgt.MainActivity.java

public void upLoadFiles() {
    bandera = true;/*from  w  w w .  j  a  v  a 2 s  . c o m*/
    ImageView img = (ImageView) findViewById(R.id.image_load);
    assert img != null;
    img.setBackgroundResource(R.drawable.load_files);

    // Get the background, which has been compiled to an AnimationDrawable object.
    AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();

    // Start the animation (looped playback by default).
    frameAnimation.start();
    if (!title.getText().toString().equals("")) {
        q.setVisibility(View.GONE);
        p.setVisibility(View.VISIBLE);
        if (audioFile != null) {
            archivos.add(audioFile);
        } else {
            audio = "";
        }
        if (!archivos.isEmpty()) {
            try {
                for (File i : archivos) {
                    AmazonS3 s3Client = new AmazonS3Client(amazonCognito());
                    TransferUtility transferUtility = new TransferUtility(s3Client, this);
                    TransferObserver transferObserver = transferUtility.upload(BUCKET_NAME,
                            "projects/" + i.getName(), i);
                    transferObserver.setTransferListener(new TransferListener() {
                        @Override
                        public void onStateChanged(int id, TransferState state) {
                            if (state == TransferState.COMPLETED) {
                                if (bandera) {
                                    ingresarDatos();
                                    limpiarCampos();
                                    bandera = false;
                                }
                            }
                        }

                        @Override
                        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
                        }

                        @Override
                        public void onError(int id, Exception ex) {
                            Toast.makeText(MainActivity.this, ex.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } catch (Exception e) {
                ingresarDatos();
                limpiarCampos();
            }
        } else {
            ingresarDatos();
            limpiarCampos();
        }
    } else {
        Toast.makeText(this, "Debe ingresar por lo menos el ttulo", Toast.LENGTH_LONG).show();
        q.scrollTo(0, 0);
        title.setFocusableInTouchMode(true);
        title.setFocusable(true);
        title.requestFocus();
    }
}

From source file:modules.storage.AmazonS3Storage.java

License:Open Source License

@Inject
public AmazonS3Storage(Configuration configuration) {
    bucketName = configuration.getString("storage.s3.bucket", "thunderbit");

    String accessKey = configuration.getString("storage.s3.accesskey");
    String secretKey = configuration.getString("storage.s3.secretkey");
    credentials = new BasicAWSCredentials(accessKey, secretKey);

    AmazonS3 amazonS3 = new AmazonS3Client(credentials);

    if (configuration.getBoolean("storage.s3.createBucket", true)) {
        try {/*  ww  w.j  ava  2 s.  c  o  m*/
            if (!(amazonS3.doesBucketExist(bucketName))) {
                amazonS3.createBucket(new CreateBucketRequest(bucketName));
            }

            String bucketLocation = amazonS3.getBucketLocation(new GetBucketLocationRequest(bucketName));
            logger.info("Amazon S3 bucket created at " + bucketLocation);
        } catch (AmazonServiceException ase) {
            logAmazonServiceException(ase);
        } catch (AmazonClientException ace) {
            logAmazonClientException(ace);
        }
    }
}

From source file:modules.storage.AmazonS3Storage.java

License:Open Source License

@Override
public F.Promise<Result> getDownload(String key, String name) {
    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
    ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides();
    responseHeaders.setContentDisposition("attachment; filename=" + name);
    generatePresignedUrlRequest.setResponseHeaders(responseHeaders);

    AmazonS3 amazonS3 = new AmazonS3Client(credentials);

    try {//  www  . j  av  a2s  . c o  m
        URL url = amazonS3.generatePresignedUrl(generatePresignedUrlRequest);

        return F.Promise.pure(redirect(url.toString()));
    } catch (AmazonClientException ace) {
        logAmazonClientException(ace);
        return F.Promise.pure(internalServerError(error.render()));
    }
}

From source file:modules.storage.AmazonS3Storage.java

License:Open Source License

@Override
public F.Promise<Void> delete(String key, String name) {
    Promise<Void> promise = Futures.promise();

    AmazonS3 amazonS3 = new AmazonS3Client(credentials);
    DeleteObjectRequest request = new DeleteObjectRequest(bucketName, key);
    request.withGeneralProgressListener(progressEvent -> {
        if (progressEvent.getEventType().isTransferEvent()) {
            if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_COMPLETED_EVENT)) {
                promise.success(null);/*from   ww  w. java  2s. c  om*/
            } else if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_FAILED_EVENT)) {
                logger.error(progressEvent.toString());
                promise.failure(new Exception(progressEvent.toString()));
            }
        }
    });

    try {
        amazonS3.deleteObject(request);
    } catch (AmazonServiceException ase) {
        logAmazonServiceException(ase);
    } catch (AmazonClientException ace) {
        logAmazonClientException(ace);
    }

    return F.Promise.wrap(promise.future());
}

From source file:n3phele.agent.repohandlers.S3Large.java

License:Open Source License

private AmazonS3Client s3() {
    if (this.s3 == null) {
        this.s3 = new AmazonS3Client(this.credentials);
        this.s3.setEndpoint(source.toString());
    }//from  ww  w  .  j  a v  a 2 s . c om
    return this.s3;
}

From source file:n3phele.storage.s3.CloudStorageImpl.java

License:Open Source License

public boolean createBucket(Repository repo) throws ForbiddenException {
    Credential credential = repo.getCredential().decrypt();
    AmazonS3Client s3 = new AmazonS3Client(
            new BasicAWSCredentials(credential.getAccount(), credential.getSecret()));
    s3.setEndpoint(repo.getTarget().toString());
    try {//from   w w  w. j  a v a 2  s.c om
        try {
            s3.listObjects(new ListObjectsRequest(repo.getRoot(), null, null, null, 0));

            // it exists and the current account owns it
            return false;
        } catch (AmazonServiceException ase) {
            switch (ase.getStatusCode()) {
            case 403:
                /*
                 * A permissions error means the bucket exists, but is owned by
                 * another account.
                 */
                throw new ForbiddenException(
                        "Bucket " + repo.getRoot() + " has already been created by another user.");
            case 404:
                Bucket bucket = s3.createBucket(repo.getRoot());
                log.info("Bucket created " + bucket.getName());
                return true;
            default:
                throw ase;
            }
        }

    } catch (AmazonServiceException e) {
        log.log(Level.WARNING, "Service Error processing " + repo, e);

    } catch (AmazonClientException e) {
        log.log(Level.SEVERE, "Client Error processing " + repo, e);

    }
    return false;
}

From source file:n3phele.storage.s3.CloudStorageImpl.java

License:Open Source License

public FileNode getMetadata(Repository repo, String filename) {
    FileNode f = new FileNode();
    UriBuilder result = UriBuilder.fromUri(repo.getTarget());
    result.path(repo.getRoot()).path(filename);
    f.setName(result.build().toString());
    Credential credential = repo.getCredential().decrypt();

    log.info("Get info on " + repo.getRoot() + " " + filename);
    AmazonS3Client s3 = new AmazonS3Client(
            new BasicAWSCredentials(credential.getAccount(), credential.getSecret()));
    s3.setEndpoint(repo.getTarget().toString());
    try {//from  w  ww  .j a v  a 2 s .  c  o  m
        ObjectListing metadata = s3.listObjects(
                new ListObjectsRequest().withBucketName(repo.getRoot()).withPrefix(filename).withMaxKeys(1));
        List<S3ObjectSummary> metadataList = metadata.getObjectSummaries();
        if (metadataList == null || metadataList.size() != 1) {
            throw new NotFoundException(filename);
        }
        f.setModified(metadataList.get(0).getLastModified());
        f.setSize(metadataList.get(0).getSize());

        log.info(filename + " " + f.getModified() + " " + f.getSize());
    } catch (AmazonServiceException e) {
        log.log(Level.WARNING, "Service Error processing " + f + repo, e);
        throw new NotFoundException("Retrieve " + filename + " fails " + e.toString());
    } catch (AmazonClientException e) {
        log.log(Level.SEVERE, "Client Error processing " + f + repo, e);
        throw new NotFoundException("Retrieve " + filename + " fails " + e.toString());
    }
    return f;
}

From source file:n3phele.storage.s3.CloudStorageImpl.java

License:Open Source License

public boolean deleteFile(Repository repo, String filename) {
    boolean result = false;
    Credential credential = repo.getCredential().decrypt();

    AmazonS3Client s3 = new AmazonS3Client(
            new BasicAWSCredentials(credential.getAccount(), credential.getSecret()));
    s3.setEndpoint(repo.getTarget().toString());
    try {/*from  w  ww. j  a v a2  s .  co  m*/
        s3.deleteObject(repo.getRoot(), filename);
        result = true;
    } catch (AmazonServiceException e) {
        log.log(Level.WARNING, "Service Error processing " + repo, e);
    } catch (AmazonClientException e) {
        log.log(Level.SEVERE, "Client Error processing " + repo, e);
    }
    return result;
}

From source file:n3phele.storage.s3.CloudStorageImpl.java

License:Open Source License

public boolean deleteFolder(Repository repo, String filename) {
    boolean result = false;
    Credential credential = repo.getCredential().decrypt();
    int retry = 3;

    setPermissions(repo, filename, false);
    if (!filename.endsWith("/")) {
        filename += "/";
    }/*from   w ww  . ja  va 2s  .  c  o m*/

    AmazonS3Client s3 = new AmazonS3Client(
            new BasicAWSCredentials(credential.getAccount(), credential.getSecret()));
    s3.setEndpoint(repo.getTarget().toString());
    while (retry-- > 0) {
        try {
            ObjectListing objects = s3.listObjects(repo.getRoot(), filename);
            for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                log.info("Delete " + repo.getRoot() + ":" + objectSummary.getKey());
                s3.deleteObject(repo.getRoot(), objectSummary.getKey());
            }
            if (objects.isTruncated()) {
                retry++;
                log.info("Doing next portion");
                continue;
            }
            result = true;
            break;
        } catch (AmazonServiceException e) {
            log.log(Level.WARNING, "Service Error processing " + repo, e);
        } catch (AmazonClientException e) {
            log.log(Level.SEVERE, "Client Error processing " + repo, e);
        }
    }
    return result;
}

From source file:n3phele.storage.s3.CloudStorageImpl.java

License:Open Source License

public boolean setPermissions(Repository repo, String filename, boolean isPublic) {
    String bucket = repo.getRoot();
    Credential credential = repo.getCredential().decrypt();
    AmazonS3Client s3 = new AmazonS3Client(
            new BasicAWSCredentials(credential.getAccount(), credential.getSecret()));
    String key = new S3ObjectResource(bucket, filename).getId();
    boolean inserted = false;

    s3.setEndpoint(repo.getTarget().toString());
    try {//from  www.java  2  s  .c o  m
        List<Statement> statements = new ArrayList<Statement>();
        Policy policy = null;
        BucketPolicy bp = s3.getBucketPolicy(repo.getRoot());
        if (bp != null && bp.getPolicyText() != null) {
            log.info("Policy text " + bp.getPolicyText());
            policy = PolicyHelper.parse(bp.getPolicyText());
            log.info("Policy object is " + (policy == null ? null : policy.toJson()));

            if (policy != null) {
                if (policy.getStatements() != null) {
                    for (Statement statement : policy.getStatements()) {
                        if (statement.getId().equals("n3phele")) {
                            List<com.amazonaws.auth.policy.Resource> resources = statement.getResources();
                            List<com.amazonaws.auth.policy.Resource> update = new ArrayList<com.amazonaws.auth.policy.Resource>();
                            if (resources != null) {
                                for (com.amazonaws.auth.policy.Resource resource : resources) {
                                    String resourceName = resource.getId();
                                    if (resourceName.endsWith("*")) {
                                        resourceName = resourceName.substring(0, resourceName.length() - 1);
                                    }
                                    if (!(resourceName + "/").startsWith(key + "/")) {
                                        update.add(resource);
                                    } else {
                                        log.info("Removing " + resource.getId());
                                    }
                                }
                            }
                            if (isPublic && !inserted)
                                update.add(new S3ObjectResource(repo.getRoot(), filename + "*"));
                            if (update.size() > 0) {
                                statement.setResources(update);
                                statements.add(statement);
                            }
                            inserted = true;
                        } else {
                            statements.add(statement);
                        }
                    }
                }
                if (!inserted && isPublic) {
                    Statement statement = new Statement(Effect.Allow);
                    statement.setId("n3phele");
                    statement.setPrincipals(Arrays.asList(new Principal("*")));
                    statement.setActions(Arrays.asList((Action) S3Actions.GetObject));
                    statement.setResources(Arrays
                            .asList((com.amazonaws.auth.policy.Resource) new S3ObjectResource(repo.getRoot(),
                                    filename + "*")));
                    statements.add(statement);
                }
            }
        }
        if (policy == null && isPublic) {
            policy = new Policy("n3phele-" + repo.getRoot());
            Statement statement = new Statement(Effect.Allow);
            statement.setId("n3phele");
            statement.setPrincipals(Arrays.asList(new Principal("*")));
            statement.setActions(Arrays.asList((Action) S3Actions.GetObject));
            statement.setResources(Arrays.asList(
                    (com.amazonaws.auth.policy.Resource) new S3ObjectResource(repo.getRoot(), filename + "*")));
            statements.add(statement);
        }
        if (policy != null) {
            if (statements.size() != 0) {
                policy.setStatements(statements);
                s3.setBucketPolicy(repo.getRoot(), policy.toJson());
                log.info("Set policy " + policy.toJson());
            } else {
                s3.deleteBucketPolicy(repo.getRoot());
            }
        }
        return true;

    } catch (AmazonServiceException e) {
        log.log(Level.WARNING, "Service Error processing " + repo, e);
    } catch (AmazonClientException e) {
        log.log(Level.SEVERE, "Client Error processing " + repo, e);
    } catch (IllegalArgumentException e) {
        log.log(Level.SEVERE, "parse error ", e);
        log.log(Level.SEVERE, "cause", e.getCause());
    }
    return false;
}