Java Code Examples for com.amazonaws.services.s3.model.ObjectMetadata.setContentType()

The following are Jave code examples for showing how to use setContentType() of the com.amazonaws.services.s3.model.ObjectMetadata class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: s3-proxy-chunk-upload   File: AssetsS3.java   View Source Code Vote up 11 votes
/**
 * Upload a file which is in the assets bucket.
 * 
 * @param fileName File name
 * @param file File
 * @param contentType Content type for file
 * @return
 */
public static boolean uploadFile(String fileName, File file, String contentType) {
    try {
        if (S3Module.amazonS3 != null) {
            String bucket = S3Module.s3Bucket;
            ObjectMetadata metaData = new ObjectMetadata();
            if (contentType != null) {
                metaData.setContentType(contentType);
            }
            PutObjectRequest putObj = new PutObjectRequest(bucket,
                    fileName, file);
            putObj.setMetadata(metaData);
            putObj.withCannedAcl(CannedAccessControlList.PublicRead);
            S3Module.amazonS3.putObject(putObj);
            return true;
        } else {
            Logger.error("Could not save because amazonS3 was null");
            return false;
        }
    } catch (Exception e) {
        Logger.error("S3 Upload -" + e.getMessage());
        return false;
    }
}
 
Example 2
Project: gradle-s3-build-cache   File: AwsS3BuildCacheService.java   View Source Code Vote up 6 votes
@Override
public void store(BuildCacheKey key, BuildCacheEntryWriter writer) {
  logger.info("Start storing cache entry '{}' in S3 bucket", key.getHashCode());
  ObjectMetadata meta = new ObjectMetadata();
  meta.setContentType(BUILD_CACHE_CONTENT_TYPE);

  try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
    writer.writeTo(os);
    meta.setContentLength(os.size());
    try (InputStream is = new ByteArrayInputStream(os.toByteArray())) {
        PutObjectRequest request = getPutObjectRequest(key, meta, is);
        if(this.reducedRedundancy) {
          request.withStorageClass(StorageClass.ReducedRedundancy);
        }
        s3.putObject(request);
    }
  } catch (IOException e) {
    throw new BuildCacheException("Error while storing cache object in S3 bucket", e);
  }
}
 
Example 3
Project: urlshortner   File: UrlShortnerService.java   View Source Code 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) {

	logger.info("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.setContentType("text/html");
	metadata.addUserMetadata("url", url);
	metadata.setContentLength(fileContentBytes.length);
	PutObjectRequest putObjectRequest = new PutObjectRequest(this.bucket, code, fileInputStream, metadata)
			.withCannedAcl(CannedAccessControlList.PublicRead);
	this.s3Client.putObject(putObjectRequest);
	createDummyRecord(url, code);
	return new ShortUrl(url, code);
}
 
Example 4
Project: ibm-cos-sdk-java   File: AmazonS3Client.java   View Source Code Vote up 6 votes
@Override
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();
    metadata.setContentType("text/plain");
    metadata.setContentLength(contentBytes.length);

    return putObject(new PutObjectRequest(bucketName, key, is, metadata));
}
 
Example 5
Project: mm-system-2017   File: ClientUploadFile.java   View Source Code Vote up 5 votes
/**
 * Use UploadFile.BucketName
 * @param keyName
 * @param filePathToUpload
 * @param BUCKET_NAME
 */
public static void uploadFile(String keyName,File fileToUpload,String BUCKET_NAME,String contentType) {
	
	

       AmazonS3 s3Client = s3client(); 

       System.out.println(s3Client);
       
       try {
       	System.out.println("Uploading a new object to S3 from a file\n");
           File file = fileToUpload;
           PutObjectRequest objectToPut = new PutObjectRequest(BUCKET_NAME, keyName, file);
           ObjectMetadata meta = new ObjectMetadata();
           meta.setContentType(contentType);
           objectToPut.setMetadata(meta);
           s3Client.putObject(objectToPut);

        } catch (AmazonServiceException ase) {
           System.out.println("Caught an AmazonServiceException, which " +
           		"means your request made it " +
                   "to Amazon S3, but was rejected with an error response" +
                   " for some reason.");
           System.out.println("Error Message:    " + ase.getMessage());
           System.out.println("HTTP Status Code: " + ase.getStatusCode());
           System.out.println("AWS Error Code:   " + ase.getErrorCode());
           System.out.println("Error Type:       " + ase.getErrorType());
           System.out.println("Request ID:       " + ase.getRequestId());
       } catch (AmazonClientException ace) {
           System.out.println("Caught an AmazonClientException, which " +
           		"means the client encountered " +
                   "an internal error while trying to " +
                   "communicate with S3, " +
                   "such as not being able to access the network.");
           System.out.println("Error Message: " + ace.getMessage());
       }  

	
	
}
 
Example 6
Project: yass-android   File: YassBroadcastReceiver.java   View Source Code Vote up 5 votes
@Override
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 &&
              activeNetwork.isConnectedOrConnecting();
    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 = {
                "serial",
                "file_uri",
                "file_name",
                "file_size"
        };
        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 {
            cursor.close();
        }
    } finally {
        db.close();
    }

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

    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(fileSize);
    metadata.setContentType(context.getContentResolver().getType(uri));
    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 7
Project: urlshortner   File: UrlShortnerService.java   View Source Code 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();
	metadata.setContentType("text/html");
	metadata.setContentLength(dummyFileContentBytes.length);
	PutObjectRequest putObjectRequest = new PutObjectRequest(this.bucket + "-dummy", code
			+ Base64.encodeBase64String(url.getBytes()), fileInputStream, metadata);
	this.s3Client.putObject(putObjectRequest);
}
 
Example 8
Project: aws-photosharing-example   File: UploadThread.java   View Source Code Vote up 5 votes
@Override
public void run() {
    ObjectMetadata meta_data = new ObjectMetadata();
    if (p_content_type != null)
        meta_data.setContentType(p_content_type);

    meta_data.setContentLength(p_size);

    PutObjectRequest putObjectRequest = new PutObjectRequest(p_bucket_name, p_s3_key, p_file_stream, meta_data);
    putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
    PutObjectResult res = s3Client.putObject(putObjectRequest);       
}
 
Example 9
Project: github-bucket   File: RepositoryS3.java   View Source Code Vote up 5 votes
private boolean walk(Iterator<S3ObjectSummary> iter, ObjectId file, String path) throws IOException {
    byte[] content;
    byte[] newHash;
    LOG.debug("Start processing file: {}", path);
    try (DigestInputStream is = new DigestInputStream(repository.open(file).openStream(), DigestUtils.getMd5Digest())) {
        // Get content
        content = IOUtils.toByteArray(is);
        // Get hash
        newHash = is.getMessageDigest().digest();
    }
    if (isUploadFile(iter, path, Hex.encodeHexString(newHash))) {
        LOG.info("Uploading file: {}", path);
        ObjectMetadata bucketMetadata = new ObjectMetadata();
        bucketMetadata.setContentMD5(Base64.encodeAsString(newHash));
        bucketMetadata.setContentLength(content.length);
        // Give Tika a few hints for the content detection
        Metadata tikaMetadata = new Metadata();
        tikaMetadata.set(Metadata.RESOURCE_NAME_KEY, FilenameUtils.getName(FilenameUtils.normalize(path)));
        // Fire!
        try (InputStream bis = TikaInputStream.get(content, tikaMetadata)) {
            bucketMetadata.setContentType(TIKA_DETECTOR.detect(bis, tikaMetadata).toString());
            s3.putObject(bucket.getName(), path, bis, bucketMetadata);
            return true;
        }
    }
    LOG.info("Skipping file (same checksum): {}", path);
    return false;
}
 
Example 10
Project: tdl-auth   File: PageUploader.java   View Source Code Vote up 5 votes
public String uploadPage(String pageContents) {
    String directory = generateDirectory();
    String path = directory + "/index.html";

    InputStream stream = new ByteArrayInputStream(pageContents.getBytes(StandardCharsets.UTF_8));
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentType("text/html");
    metadata.setContentDisposition("inline; filename=\"index.html\"");
    PutObjectRequest request = new PutObjectRequest(bucket, path, stream, metadata)
            .withMetadata(metadata);
    s3client.putObject(request);
    return s3client.getUrl(bucket, path).toString();
}
 
Example 11
Project: pprxmtr   File: GifGeneratorHandler.java   View Source Code Vote up 4 votes
@Override
public ApiGatewayResponse handleRequest(SNSEvent input, Context context) {
	LOG.info("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();
				LOG.info("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)) {
				LOG.info("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();
				metadata.setContentLength(gif.length);
				metadata.setContentType("image/gif");

				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);
				}

				LOG.info("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();
}