Java Code Examples for

The following are Jave code examples for showing how to use setContentLength() of the class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: qpp-conversion-tool   File:   Source Code and License Vote up 6 votes
 * Stores the {@link InputStream} as an object in the S3 bucket.
 * @param keyName The requested key name for the object.
 * @param inStream The {@link InputStream} to write out to an object in S3.
 * @param size The size of the {@link InputStream}.
 * @return A {@link CompletableFuture} that will eventually contain the S3 object key.
public CompletableFuture<String> store(String keyName, InputStream inStream, long size) {
	final String bucketName = environment.getProperty(Constants.BUCKET_NAME_ENV_VARIABLE);
	final String kmsKey = environment.getProperty(Constants.KMS_KEY_ENV_VARIABLE);
	if (Strings.isNullOrEmpty(bucketName) || Strings.isNullOrEmpty(kmsKey)) {
		API_LOG.warn("No bucket name is specified or no KMS key specified.");
		return CompletableFuture.completedFuture("");

	ObjectMetadata s3ObjectMetadata = new ObjectMetadata();

	PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inStream, s3ObjectMetadata)
		.withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams(kmsKey));"Writing object {} to S3 bucket {}", keyName, bucketName);
	return actOnItem(putObjectRequest);
Example 2
Project: urlshortner   File:   Source Code and License Vote up 6 votes
 * The method creates a short URL code for the given url
 * @param url
 * @return
public ShortUrl createShortUrl(String url, String code) {"storing the url {} in the bucket {}", url, this.bucket);
	// Create the link for the short code
	if (code == null) {
		code = getObjectCode();
	String loadFile = redirectFile.replace("REPLACE", url);
	byte[] fileContentBytes = loadFile.getBytes(StandardCharsets.UTF_8);
	InputStream fileInputStream = new ByteArrayInputStream(fileContentBytes);
	ObjectMetadata metadata = new ObjectMetadata();
	metadata.addUserMetadata("url", url);
	PutObjectRequest putObjectRequest = new PutObjectRequest(this.bucket, code, fileInputStream, metadata)
	createDummyRecord(url, code);
	return new ShortUrl(url, code);
Example 3
Project: S3Mock   File:   Source Code and License Vote up 6 votes
 * Tests if Object can be uploaded with wrong KMS Key
public void shouldNotUploadStreamingWithWrongEncryptionKey() {
  final byte[] bytes = UPLOAD_FILE_NAME.getBytes();
  final InputStream stream = new ByteArrayInputStream(bytes);
  final String objectKey = UUID.randomUUID().toString();
  final ObjectMetadata metadata = new ObjectMetadata();
  final PutObjectRequest putObjectRequest =
      new PutObjectRequest(BUCKET_NAME, objectKey, stream, metadata);
  putObjectRequest.setSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams(TEST_WRONG_KEYREF));

  thrown.expectMessage(containsString("Status Code: 400; Error Code: KMS.NotFoundException"));
Example 4
Project: hadoop   File:   Source Code and License Vote up 6 votes
private void createEmptyObject(final String bucketName, final String objectName)
    throws AmazonClientException, AmazonServiceException {
  final InputStream im = new InputStream() {
    public int read() throws IOException {
      return -1;

  final ObjectMetadata om = new ObjectMetadata();
  if (StringUtils.isNotBlank(serverSideEncryptionAlgorithm)) {
  PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, im, om);
Example 5
Project: ibm-cos-sdk-java   File:   Source Code and License Vote up 6 votes
public PutObjectResult putObject(String bucketName, String key, String content)
        throws AmazonServiceException, SdkClientException {

    rejectNull(bucketName, "Bucket name must be provided");
    rejectNull(key, "Object key must be provided");
    rejectNull(content, "String content must be provided");

    byte[] contentBytes = content.getBytes(StringUtils.UTF8);

    InputStream is = new ByteArrayInputStream(contentBytes);
    ObjectMetadata metadata = new ObjectMetadata();

    return putObject(new PutObjectRequest(bucketName, key, is, metadata));
Example 6
Project: Reer   File:   Source Code and License Vote up 5 votes
public void put(InputStream inputStream, Long contentLength, URI destination) {
    try {
        S3RegionalResource s3RegionalResource = new S3RegionalResource(destination);
        String bucketName = s3RegionalResource.getBucketName();
        String s3BucketKey = s3RegionalResource.getKey();

        ObjectMetadata objectMetadata = new ObjectMetadata();

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, s3BucketKey, inputStream, objectMetadata);
        LOGGER.debug("Attempting to put resource:[{}] into s3 bucket [{}]", s3BucketKey, bucketName);

    } catch (AmazonClientException e) {
        throw ResourceExceptions.putFailed(destination, e);
Example 7
Project: s3-inventory-usage-examples   File:   Source Code and License Vote up 5 votes
 * Write a new inventory report to S3 and returns a locator which includes this inventory report's information
 * @return Locator which includes the information of this new report
 * @throws IOException thrown when GZIPOutputStream not created successfully or csvMapper.write() fails
public InventoryManifest.Locator writeCsvFile(List<InventoryReportLine> inventoryReportLine) throws IOException{
    CsvMapper csvMapper = new CsvMapper();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
    byte[] zipByteArray = byteArrayOutputStream.toByteArray();

    InputStream zipInputStream = new ByteArrayInputStream(zipByteArray);
    ObjectMetadata metaData = new ObjectMetadata();
    PutObjectRequest request = new PutObjectRequest(bucketName, outputInventoryReportKey, zipInputStream, metaData);

    return this.buildLocator(zipByteArray);
Example 8
Project: circus-train   File:   Source Code and License Vote up 5 votes
private S3UploadDescriptor describeUpload(FileStatus sourceFileStatus, Path targetPath) throws IOException {
  URI targetUri = targetPath.toUri();
  String bucketName = PathUtil.toBucketName(targetUri);
  String key = PathUtil.toBucketKey(targetUri);

  Path sourcePath = sourceFileStatus.getPath();

  ObjectMetadata metadata = new ObjectMetadata();
  if (conf.getBoolean(ConfigurationVariable.S3_SERVER_SIDE_ENCRYPTION)) {
  return new S3UploadDescriptor(sourcePath, bucketName, key, metadata);
Example 9
Project: yass-android   File:   Source Code and License Vote up 5 votes
public Long doInBackground(Void... unused) {
    Log.d(TAG, "Upload Blob Task:");

    MainActivity.YassPreferences preferences = new MainActivity.YassPreferences(context);

    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null &&
    if (!isConnected) {
        Log.d(TAG, "Skipping camera upload because network is disconnected");
        return null;
    if (preferences.cameraUploadOnlyOnWifi && activeNetwork.getType() != ConnectivityManager.TYPE_WIFI) {
        Log.d(TAG, "Skipping camera upload because Wifi is disconnected");
        return null;

    long serial;
    Uri uri;
    String fileName;
    long fileSize;
    SQLiteDatabase db = new YassDbHelper(context).getReadableDatabase();
    try {
        String[] projection = {
        String selection = null;
        String[] selectionArgs = null;
        String groupBy = null;
        String having = null;
        String orderBy = "serial ASC";
        String limit = "1";
        Cursor cursor = db.query("camera_uploads", projection, selection, selectionArgs,
                groupBy, having, orderBy, limit);
        try {
            if (!cursor.moveToNext()) {
                Log.d(TAG, "Did not find image to upload");
                return null;
            serial = cursor.getLong(cursor.getColumnIndexOrThrow("serial"));
            uri = Uri.parse(cursor.getString(cursor.getColumnIndexOrThrow("file_uri")));
            fileName = cursor.getString(cursor.getColumnIndexOrThrow("file_name"));
            fileSize = cursor.getLong(cursor.getColumnIndexOrThrow("file_size"));
        } finally {
    } finally {

    Log.d(TAG, "Found image to upload: " + fileName);

    ObjectMetadata metadata = new ObjectMetadata();
    PutObjectResult result;
    try (InputStream is = context.getContentResolver().openInputStream(uri)) {
        // TODO: limited to 5 GB
        result = MainActivity.getS3Client(preferences).putObject(preferences.bucketName,
                "Camera Uploads/" + fileName, is, metadata);
    } catch (AmazonClientException | IOException e) {
        Log.e(TAG, "Could not upload file: " + e.getMessage());
        return null;
    return serial;
Example 10
Project: rxjava2-aws   File:   Source Code and License Vote up 5 votes
public static String sendToQueueUsingS3(AmazonSQS sqs, String queueUrl, AmazonS3 s3, String bucketName,
        Map<String, String> headers, byte[] message, Callable<String> s3IdFactory) {
    String s3Id;
    try {
        s3Id =;
    } catch (final Exception e1) {
        throw new RuntimeException(e1);
    final ObjectMetadata metadata = new ObjectMetadata();
    for (final Entry<String, String> header : headers.entrySet()) {
        metadata.setHeader(header.getKey(), header.getValue());
    s3.putObject(bucketName, s3Id, new ByteArrayInputStream(message), metadata);
    try {
        sqs.sendMessage(queueUrl, s3Id);
    } catch (final RuntimeException e) {
        try {
            s3.deleteObject(bucketName, s3Id);
            throw e;
        } catch (final RuntimeException e2) {
            throw new io.reactivex.exceptions.CompositeException(e, e2);
    return s3Id;
Example 11
Project: urlshortner   File:   Source Code and License Vote up 5 votes
private void createDummyRecord(String url, String code) {
	// Add a dummy object for pointer
	byte[] dummyFileContentBytes = new String(code).getBytes(StandardCharsets.UTF_8);
	InputStream fileInputStream = new ByteArrayInputStream(dummyFileContentBytes);
	ObjectMetadata metadata = new ObjectMetadata();
	PutObjectRequest putObjectRequest = new PutObjectRequest(this.bucket + "-dummy", code
			+ Base64.encodeBase64String(url.getBytes()), fileInputStream, metadata);
Example 12
Project: aws-photosharing-example   File:   Source Code and License Vote up 5 votes
public void run() {
    ObjectMetadata meta_data = new ObjectMetadata();
    if (p_content_type != null)


    PutObjectRequest putObjectRequest = new PutObjectRequest(p_bucket_name, p_s3_key, p_file_stream, meta_data);
    PutObjectResult res = s3Client.putObject(putObjectRequest);       
Example 13
Project: nexus-blobstore-s3   File:   Source Code and License Vote up 5 votes
public void store() throws IOException {
  log.debug("Storing: {}/{}", bucket, key);

  ByteArrayOutputStream bufferStream = new ByteArrayOutputStream();
  store(bufferStream, null);
  byte[] buffer = bufferStream.toByteArray();

  ObjectMetadata metadata = new ObjectMetadata();
  s3.putObject(bucket, key, new ByteArrayInputStream(buffer), metadata);
Example 14
Project: s3-channels   File:   Source Code and License Vote up 5 votes
static void initMock() {
    ObjectMetadata meta = new ObjectMetadata();
    when(amazonS3.getObjectMetadata(anyString(), anyString()))
Example 15
Project: hadoop   File:   Source Code and License Vote up 5 votes
private void putObject() throws IOException {
  if (LOG.isDebugEnabled()) {
    LOG.debug("Executing regular upload for bucket '{}' key '{}'", bucket,
  final ObjectMetadata om = createDefaultMetadata();
  final PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key,
      new ByteArrayInputStream(buffer.toByteArray()), om);
  ListenableFuture<PutObjectResult> putObjectResult =
      executorService.submit(new Callable<PutObjectResult>() {
        public PutObjectResult call() throws Exception {
          return client.putObject(putObjectRequest);
  //wait for completion
  try {
  } catch (InterruptedException ie) {
    LOG.warn("Interrupted object upload:" + ie, ie);
  } catch (ExecutionException ee) {
    throw new IOException("Regular upload failed", ee.getCause());
Example 16
Project: ibm-cos-sdk-java   File:   Source Code and License Vote up 5 votes
protected final PutObjectRequest createInstructionPutRequest(
        String bucketName, String key, ContentCryptoMaterial cekMaterial) {
    byte[] bytes = cekMaterial.toJsonString(cryptoConfig.getCryptoMode())
    InputStream is = new ByteArrayInputStream(bytes);
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.addUserMetadata(Headers.CRYPTO_INSTRUCTION_FILE, "");
    InstructionFileId ifileId = new S3ObjectId(bucketName, key)
    return new PutObjectRequest(ifileId.getBucket(), ifileId.getKey(),
        is, metadata);
Example 17
Project: S3Mock   File:   Source Code and License Vote up 5 votes
 * Stores a file in a previously created bucket. Downloads the file again and compares checksums
 * @throws Exception if FileStreams can not be read
public void shouldUploadAndDownloadStream() throws Exception {
  final String resourceId = UUID.randomUUID().toString();

  final byte[] resource = new byte[] {1, 2, 3, 4, 5};
  final ByteArrayInputStream bais = new ByteArrayInputStream(resource);

  final ObjectMetadata objectMetadata = new ObjectMetadata();
  final PutObjectRequest putObjectRequest =
      new PutObjectRequest(BUCKET_NAME, resourceId, bais, objectMetadata);

  final TransferManager tm = createDefaultTransferManager();
  final Upload upload = tm.upload(putObjectRequest);


  final S3Object s3Object = s3Client.getObject(BUCKET_NAME, resourceId);

  final String uploadHash = HashUtil.getDigest(new ByteArrayInputStream(resource));
  final String downloadedHash = HashUtil.getDigest(s3Object.getObjectContent());

  assertThat("Up- and downloaded Files should have equal Hashes", uploadHash,
Example 18
Project: pprxmtr   File:   Source Code and License Vote up 4 votes
public ApiGatewayResponse handleRequest(SNSEvent input, Context context) {"Loading Gif Generator Java Lambda handler.");

	ObjectMapper mapper = new ObjectMapper();

	if (CollectionUtils.isNotEmpty(input.getRecords())) {
		try {
			JsonNode json = mapper.readTree(input.getRecords().get(0).getSNS().getMessage());
			byte[] gif = ArrayUtils.EMPTY_BYTE_ARRAY;

			if (json.has("emojiUrl")) {
				HttpClient client = HttpClientBuilder.create().build();
				String emojiUrl = json.get("emojiUrl").asText();
				HttpGet getImageRequest = new HttpGet(emojiUrl);
				HttpResponse getImageResponse = client.execute(getImageRequest);
				int getImageStatus = getImageResponse.getStatusLine().getStatusCode();"Get image status: {}.", getImageStatus);

				if (StringUtils.contains(getImageResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue(), "image")) {
					byte[] imageFile = IOUtils.toByteArray(getImageResponse.getEntity().getContent());
					gif = GifGenerator.generateGif(imageFile);
				} else {
					LOG.error("Given image URL did not return an image according to mime type!");

			if (ArrayUtils.isNotEmpty(gif)) {"Gif created successfully, storing in S3.");
				String emoji = json.get("text").asText();
				String emojiName = StringUtils.removeEnd(StringUtils.removeStart(StringUtils.strip(emoji), ":"), ":");
				emojiName = emojiName.replaceAll("ä", "a").replaceAll("ö", "o").replaceAll("å", "o");

				InputStream is = new ByteArrayInputStream(gif);
				ObjectMetadata metadata = new ObjectMetadata();

				if (UrlValidator.getInstance().isValid(emojiName)) {
					emojiName = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('0', '9'))
							.retainFrom(StringUtils.substringAfterLast(emojiName, "/"));

				String filenamePrefix = emojiName + "_approximated_";
				if (!S3.fileExistsInBucket(filenamePrefix)) {
					S3.storeFileInBucket(filenamePrefix + System.currentTimeMillis() + ".gif", is, metadata);
				}"Image stored in S3, publishing to topic s3-file-ready");
				SNS.publish("s3-file-ready", mapper.writeValueAsString(json)).get();
			} else {
				LOG.error("Gif generator returned an empty byte array, sending error response");
				SNS.publish("gif-generator-error", mapper.writeValueAsString(json)).get();
		} catch (IOException | InterruptedException | ExecutionException e) {
			LOG.error("Exception occured when creating GIF.", e);

	Response responseBody = new Response("pprxmtr-gif-generator called.", new HashMap<>());
	return ApiGatewayResponse.builder().setStatusCode(200).setObjectBody(responseBody).build();
Example 19
Project: StubbornJava   File:   Source Code and License Vote up 4 votes
public void putBytes(String bucket, String key, byte[] bytes) {
    ObjectMetadata md = new ObjectMetadata();
    PutObjectRequest request = new PutObjectRequest(bucket, key, new ByteArrayInputStream(bytes), md);
Example 20
Project: bayou   File:   Source Code and License Vote up 4 votes
 * Performs an S3 Put Object operation storing the UTF-8 bytes of logMsg under the given key
 * using construction provided AWS credentials.
 * @param objectKey the S3 object key. may not be null or whitespace only.
 * @param logMsg the message to store
 * @throws IllegalArgumentException if objectKey is whitespace only.
void putToS3(String objectKey, String logMsg)
    if(objectKey == null)
        throw new NullPointerException("objectKey");

    if(objectKey.trim().length() == 0)
        throw new IllegalArgumentException("objectKey may not be only whitespace.");

     * Make the client used to send the log msg to S3.
    AmazonS3 client;
        Regions regions = Regions.US_EAST_1;
        if(_credentials == null)
            client = AmazonS3ClientBuilder.standard() // get creds from environment
            client =  AmazonS3ClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(_credentials))

     * Store the log msg in S3.
    byte[] logMsgBytes = logMsg.getBytes(StandardCharsets.UTF_8);

    ObjectMetadata metadata = new ObjectMetadata();

    client.putObject(_bucketName, objectKey, new ByteArrayInputStream(logMsgBytes), metadata);