Example usage for com.amazonaws.services.s3.model ObjectMetadata setContentLength

List of usage examples for com.amazonaws.services.s3.model ObjectMetadata setContentLength

Introduction

In this page you can find the example usage for com.amazonaws.services.s3.model ObjectMetadata setContentLength.

Prototype

public void setContentLength(long contentLength) 

Source Link

Document

<p> Sets the Content-Length HTTP header indicating the size of the associated object in bytes.

Usage

From source file:org.cm.podd.report.service.DataSubmitService.java

License:Apache License

private boolean uploadToS3(String guid, String filePath, Bitmap thumbnail) {
    TransferManager transferManager = new TransferManager(
            new BasicAWSCredentials(sharedPrefUtil.getAwsSecretKey(), sharedPrefUtil.getAwsAccessKey()));

    // upload thumbnail
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 80, bos);
    byte[] bitmapData = bos.toByteArray();
    ByteArrayInputStream bs = new ByteArrayInputStream(bitmapData);
    ObjectMetadata meta = new ObjectMetadata();
    meta.setContentLength(bitmapData.length);
    meta.setContentType("image/jpeg");

    Upload upload1 = transferManager.upload(BuildConfig.BUCKET_NAME, // bucket
            guid + "-thumbnail", // name
            bs, meta);//from  ww  w . j av  a 2s  .c  om

    // upload image
    File imageFile = new File(filePath);
    Upload upload2 = transferManager.upload(BuildConfig.BUCKET_NAME, guid, imageFile);

    try {
        upload1.waitForUploadResult();
        upload2.waitForUploadResult();

    } catch (InterruptedException e) {
        e.printStackTrace();
        Log.d(TAG, "upload to s3 error", e);
        return false;
    }

    return true;

}

From source file:org.dspace.globus.S3Client.java

License:Open Source License

public String createObject(String metadata) {
    UUID key = UUID.randomUUID();
    try {/*from w  w  w.  j a  v  a  2s. c o  m*/
        byte[] metadataBytes = metadata.getBytes("UTF-8");
        InputStream stream = new ByteArrayInputStream(metadataBytes);
        ObjectMetadata s3ObjectMeta = new ObjectMetadata();
        s3ObjectMeta.setContentLength(metadataBytes.length);
        s3Client.putObject(new PutObjectRequest(bucketName, key.toString(), stream, s3ObjectMeta));
        return key.toString();
    } catch (AmazonServiceException ase) {
        logger.error("AmazonServiceException: " + ase.getMessage());
    } catch (AmazonClientException ace) {
        logger.error("AmazonClientException: " + ace.getMessage());
    } catch (Exception e) {
        logger.error("Exception: " + e.getMessage());
    }
    return null;
}

From source file:org.duracloud.s3storage.S3StorageProvider.java

License:Apache License

/**
 * {@inheritDoc}/*from w  ww  . jav  a2s .co m*/
 */
public String addContent(String spaceId, String contentId, String contentMimeType,
        Map<String, String> userProperties, long contentSize, String contentChecksum, InputStream content) {
    log.debug("addContent(" + spaceId + ", " + contentId + ", " + contentMimeType + ", " + contentSize + ", "
            + contentChecksum + ")");

    // Will throw if bucket does not exist
    String bucketName = getBucketName(spaceId);

    // Wrap the content in order to be able to retrieve a checksum
    ChecksumInputStream wrappedContent = new ChecksumInputStream(content, contentChecksum);

    String contentEncoding = removeContentEncoding(userProperties);

    userProperties = removeCalculatedProperties(userProperties);

    if (contentMimeType == null || contentMimeType.equals("")) {
        contentMimeType = DEFAULT_MIMETYPE;
    }

    ObjectMetadata objMetadata = new ObjectMetadata();
    objMetadata.setContentType(contentMimeType);
    if (contentSize > 0) {
        objMetadata.setContentLength(contentSize);
    }
    if (null != contentChecksum && !contentChecksum.isEmpty()) {
        String encodedChecksum = ChecksumUtil.convertToBase64Encoding(contentChecksum);
        objMetadata.setContentMD5(encodedChecksum);
    }

    if (contentEncoding != null) {
        objMetadata.setContentEncoding(contentEncoding);
    }

    if (userProperties != null) {
        for (String key : userProperties.keySet()) {
            String value = userProperties.get(key);

            if (log.isDebugEnabled()) {
                log.debug("[" + key + "|" + value + "]");
            }

            objMetadata.addUserMetadata(getSpaceFree(encodeHeaderKey(key)), encodeHeaderValue(value));
        }
    }

    PutObjectRequest putRequest = new PutObjectRequest(bucketName, contentId, wrappedContent, objMetadata);
    putRequest.setStorageClass(DEFAULT_STORAGE_CLASS);
    putRequest.setCannedAcl(CannedAccessControlList.Private);

    // Add the object
    String etag;
    try {
        PutObjectResult putResult = s3Client.putObject(putRequest);
        etag = putResult.getETag();
    } catch (AmazonClientException e) {
        if (e instanceof AmazonS3Exception) {
            AmazonS3Exception s3Ex = (AmazonS3Exception) e;
            String errorCode = s3Ex.getErrorCode();
            Integer statusCode = s3Ex.getStatusCode();
            String message = MessageFormat.format(
                    "exception putting object {0} into {1}: errorCode={2},"
                            + "  statusCode={3}, errorMessage={4}",
                    contentId, bucketName, errorCode, statusCode, e.getMessage());

            if (errorCode.equals("InvalidDigest") || errorCode.equals("BadDigest")) {
                log.error(message, e);

                String err = "Checksum mismatch detected attempting to add " + "content " + contentId
                        + " to S3 bucket " + bucketName + ". Content was not added.";
                throw new ChecksumMismatchException(err, e, NO_RETRY);
            } else if (errorCode.equals("IncompleteBody")) {
                log.error(message, e);
                throw new StorageException("The content body was incomplete for " + contentId + " to S3 bucket "
                        + bucketName + ". Content was not added.", e, NO_RETRY);
            } else if (!statusCode.equals(HttpStatus.SC_SERVICE_UNAVAILABLE)
                    && !statusCode.equals(HttpStatus.SC_NOT_FOUND)) {
                log.error(message, e);
            } else {
                log.warn(message, e);
            }
        } else {
            String err = MessageFormat.format("exception putting object {0} into {1}: {2}", contentId,
                    bucketName, e.getMessage());
            log.error(err, e);
        }

        // Check to see if file landed successfully in S3, despite the exception
        etag = doesContentExistWithExpectedChecksum(bucketName, contentId, contentChecksum);
        if (null == etag) {
            String err = "Could not add content " + contentId + " with type " + contentMimeType + " and size "
                    + contentSize + " to S3 bucket " + bucketName + " due to error: " + e.getMessage();
            throw new StorageException(err, e, NO_RETRY);
        }
    }

    // Compare checksum
    String providerChecksum = getETagValue(etag);
    String checksum = wrappedContent.getMD5();
    StorageProviderUtil.compareChecksum(providerChecksum, spaceId, contentId, checksum);
    return providerChecksum;
}

From source file:org.eclipse.hawkbit.artifact.repository.S3Repository.java

License:Open Source License

private ObjectMetadata createObjectMetadata(final String mdMD5Hash16, final String contentType,
        final File file) {
    final ObjectMetadata objectMetadata = new ObjectMetadata();
    final String mdMD5Hash64 = BaseEncoding.base64()
            .encode(BaseEncoding.base16().lowerCase().decode(mdMD5Hash16));
    objectMetadata.setContentMD5(mdMD5Hash64);
    objectMetadata.setContentType(contentType);
    objectMetadata.setContentLength(file.length());
    objectMetadata.setHeader("x-amz-meta-md5chksum", mdMD5Hash64);
    if (s3Properties.isServerSideEncryption()) {
        objectMetadata.setHeader(Headers.SERVER_SIDE_ENCRYPTION,
                s3Properties.getServerSideEncryptionAlgorithm());
    }/*from www. j  a va2s  . co  m*/
    return objectMetadata;
}

From source file:org.elasticsearch.cloud.aws.blobstore.DefaultS3OutputStream.java

License:Apache License

protected void doUpload(S3BlobStore blobStore, String bucketName, String blobName, InputStream is, int length,
        boolean serverSideEncryption) throws AmazonS3Exception {
    ObjectMetadata md = new ObjectMetadata();
    if (serverSideEncryption) {
        md.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
    }/*from w  w  w  .  jav  a 2s  .  c o  m*/
    md.setContentLength(length);
    blobStore.client().putObject(bucketName, blobName, is, md);
}

From source file:org.elasticsearch.cloud.aws.blobstore.S3ImmutableBlobContainer.java

License:Apache License

@Override
public void writeBlob(final String blobName, final InputStream is, final long sizeInBytes,
        final WriterListener listener) {
    blobStore.executor().execute(new Runnable() {
        @Override/*from w w  w.  ja v  a  2s .  co  m*/
        public void run() {
            try {
                ObjectMetadata md = new ObjectMetadata();
                if (blobStore.serverSideEncryption()) {
                    md.setServerSideEncryption(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
                }
                md.setContentLength(sizeInBytes);
                PutObjectResult objectResult = blobStore.client().putObject(blobStore.bucket(),
                        buildKey(blobName), is, md);
                listener.onCompleted();
            } catch (Exception e) {
                listener.onFailure(e);
            }
        }
    });
}

From source file:org.elasticsearch.repositories.s3.DefaultS3OutputStream.java

License:Apache License

protected void doUpload(S3BlobStore blobStore, String bucketName, String blobName, InputStream is, int length,
        boolean serverSideEncryption) throws AmazonS3Exception {
    ObjectMetadata md = new ObjectMetadata();
    if (serverSideEncryption) {
        md.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
    }//from  ww  w . j  a  va2s .c  om
    md.setContentLength(length);

    PutObjectRequest putRequest = new PutObjectRequest(bucketName, blobName, is, md)
            .withStorageClass(blobStore.getStorageClass()).withCannedAcl(blobStore.getCannedACL());
    blobStore.client().putObject(putRequest);

}

From source file:org.entando.entando.plugins.jps3awsclient.aps.system.services.storage.AmazonS3StorageManager.java

License:Open Source License

public void store(IStorageObject obj, boolean reducedRedundancy, CannedAccessControlList acl)
        throws ApsSystemException {
    try {/*from  w ww . j  a  va2s . c  om*/
        AmazonS3Client client = this.getS3Client();
        String bucketName = obj.getBucketName().toLowerCase();
        this.checkForAndCreateBucket(bucketName, client);
        ObjectMetadata omd = new ObjectMetadata();
        omd.setContentType(obj.getContentType());
        omd.setContentLength(obj.getContentLength());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, obj.getStoragePath(),
                obj.getInputStream(), omd);
        // Check if reduced redundancy is enabled
        if (reducedRedundancy) {
            putObjectRequest.setStorageClass(StorageClass.ReducedRedundancy);
        }
        if (null != obj.getUserMetadata()) {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            putObjectRequest.setMetadata(objectMetadata);
            Iterator<String> iter = obj.getUserMetadata().keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                objectMetadata.addUserMetadata(key, obj.getUserMetadata().get(key));
            }
        }
        client.putObject(putObjectRequest);
        // If we have an ACL set access permissions for the the data on S3
        if (acl != null) {
            client.setObjectAcl(bucketName, obj.getStoragePath(), acl);
        }
    } catch (Throwable t) {
        _logger.error("Error storing object", t);
        throw new ApsSystemException("Error storing object", t);
    }
}

From source file:org.exem.flamingo.web.filesystem.s3.S3BrowserServiceImpl.java

License:Apache License

@Override
public void createFolder(String bucketName, String key) {
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(0L);

    if (!StringUtils.endsWith(key, S3Constansts.DELIMITER)) {
        key = key.concat(S3Constansts.DELIMITER);
    }//from   ww w . ja v a2s.c om

    this.s3.putObject(bucketName, key, new ByteArrayInputStream(new byte[0]), metadata);
}

From source file:org.exem.flamingo.web.filesystem.s3.S3BrowserServiceImpl.java

License:Apache License

@Override
public void upload(String bucketName, String key, MultipartFile file) throws IOException {
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(file.getSize());
    PutObjectRequest request = new PutObjectRequest(bucketName, key, file.getInputStream(), metadata);
    this.s3.putObject(request);

}