List of usage examples for com.amazonaws.services.s3.model ObjectMetadata setContentLength
public void setContentLength(long contentLength)
From source file:com.amazon.util.ImageUploader.java
public static void uploadImage(String imageURL, String imageName, String folderName, String bucketName) throws MalformedURLException, IOException { // credentials object identifying user for authentication AWSCredentials credentials = new BasicAWSCredentials(System.getenv("AWS_S3_ACCESS_KEY"), System.getenv("AWS_S3_SECRET_ACCESS_KEY")); // create a client connection based on credentials AmazonS3 s3client = new AmazonS3Client(credentials); try {/*from www . j a va 2 s.c om*/ if (!(s3client.doesBucketExist(bucketName))) { s3client.setRegion(Region.getRegion(Regions.US_EAST_1)); // Note that CreateBucketRequest does not specify region. So bucket is // created in the region specified in the client. s3client.createBucket(new CreateBucketRequest(bucketName)); } //Enabe CORS: // <?xml version="1.0" encoding="UTF-8"?> //<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> // <CORSRule> // <AllowedOrigin>http://ask-ifr-download.s3.amazonaws.com</AllowedOrigin> // <AllowedMethod>GET</AllowedMethod> // </CORSRule> //</CORSConfiguration> BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration(); CORSRule corsRule = new CORSRule() .withAllowedMethods( Arrays.asList(new CORSRule.AllowedMethods[] { CORSRule.AllowedMethods.GET })) .withAllowedOrigins(Arrays.asList(new String[] { "http://ask-ifr-download.s3.amazonaws.com" })); configuration.setRules(Arrays.asList(new CORSRule[] { corsRule })); s3client.setBucketCrossOriginConfiguration(bucketName, configuration); } 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()); } String fileName = folderName + SUFFIX + imageName + ".png"; URL url = new URL(imageURL); ObjectMetadata omd = new ObjectMetadata(); omd.setContentType("image/png"); omd.setContentLength(url.openConnection().getContentLength()); // upload file to folder and set it to public s3client.putObject(new PutObjectRequest(bucketName, fileName, url.openStream(), omd) .withCannedAcl(CannedAccessControlList.PublicRead)); }
From source file:com.amediamanager.dao.DynamoDbUserDaoImpl.java
License:Apache License
/** * Upload the profile pic to S3 and return it's URL * @param profilePic//from w ww . j a va2 s.c om * @return The fully-qualified URL of the photo in S3 * @throws IOException */ public String uploadFileToS3(CommonsMultipartFile profilePic) throws IOException { // Profile pic prefix String prefix = config.getProperty(ConfigProps.S3_PROFILE_PIC_PREFIX); // Date string String dateString = new SimpleDateFormat("ddMMyyyy").format(new java.util.Date()); String s3Key = prefix + "/" + dateString + "/" + UUID.randomUUID().toString() + "_" + profilePic.getOriginalFilename(); // Get bucket String s3bucket = config.getProperty(ConfigProps.S3_UPLOAD_BUCKET); // Create a ObjectMetadata instance to set the ACL, content type and length ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType(profilePic.getContentType()); metadata.setContentLength(profilePic.getSize()); // Create a PutRequest to upload the image PutObjectRequest putObject = new PutObjectRequest(s3bucket, s3Key, profilePic.getInputStream(), metadata); // Put the image into S3 s3Client.putObject(putObject); s3Client.setObjectAcl(s3bucket, s3Key, CannedAccessControlList.PublicRead); return "http://" + s3bucket + ".s3.amazonaws.com/" + s3Key; }
From source file:com.awscrud.aws.S3StorageManager.java
License:Open Source License
/** * Stores a given item on S3//ww w . ja va 2 s . c o m * @param obj the data to be stored * @param reducedRedundancy whether or not to use reduced redundancy storage * @param acl a canned access control list indicating what permissions to store this object with (can be null to leave it set to default) */ public void store(AwscrudStorageObject obj, boolean reducedRedundancy, CannedAccessControlList acl) { // Make sure the bucket exists before we try to use it checkForAndCreateBucket(obj.getBucketName()); ObjectMetadata omd = new ObjectMetadata(); omd.setContentType(obj.getMimeType()); omd.setContentLength(obj.getData().length); ByteArrayInputStream is = new ByteArrayInputStream(obj.getData()); PutObjectRequest request = new PutObjectRequest(obj.getBucketName(), obj.getStoragePath(), is, omd); // Check if reduced redundancy is enabled if (reducedRedundancy) { request.setStorageClass(StorageClass.ReducedRedundancy); } s3client.putObject(request); // If we have an ACL set access permissions for the the data on S3 if (acl != null) { s3client.setObjectAcl(obj.getBucketName(), obj.getStoragePath(), acl); } }
From source file:com.BoomPi.ImageResizeHandlerFromS3.java
License:Apache License
private String putResizedImageToS3(ImageProcess jpegImageProcess, String s3ObjectKey, int width, int height) throws IOException { ByteArrayOutputStream os = jpegImageProcess.resize(width, height).getOutPutStream(); try (InputStream is = new ByteArrayInputStream(os.toByteArray());) { ObjectMetadata meta = new ObjectMetadata(); meta.setContentLength(os.size()); meta.setContentType(jpegImageProcess.getImageMime()); String dstKey = String.join("_", "resized", s3ObjectKey); AmazonS3 s3Client = new AmazonS3Client(); System.out.println("Writing to: " + dstBucket + "/" + dstKey); s3Client.putObject(dstBucket, dstKey, is, meta); }/*from ww w. ja va 2 s.com*/ return "Ok"; }
From source file:com.casadocodigo.ecommerce.infra.AmazonFileSaver.java
public String write(String baseFolder, Part multipartFile) throws IOException { String fileName = extractFilename(multipartFile.getHeader(CONTENT_DISPOSITION)); String path = baseFolder + File.separator + fileName; AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider()); ObjectMetadata metaData = new ObjectMetadata(); byte[] bytes = IOUtils.toByteArray(multipartFile.getInputStream()); metaData.setContentLength(bytes.length); /*ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, byteArrayInputStream, metadata); client.putObject(putObjectRequest);*/ s3client.putObject(new PutObjectRequest(BUCKET_NAME, path, multipartFile.getInputStream(), metaData) .withCannedAcl(CannedAccessControlList.PublicRead)); /*s3client.putObject(BUCKET_NAME,fileName, multipartFile.getInputStream(), metaData);*/ return END_POINT + File.separator + BUCKET_NAME + File.separator + path; }
From source file:com.cirrus.server.osgi.service.amazon.s3.AmazonS3StorageService.java
License:Apache License
@Override public CirrusFolderData createDirectory(final String path) throws ServiceRequestFailedException { final ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(0); final InputStream emptyContent = new ByteArrayInputStream(new byte[0]); final String key = path + SEPARATOR; final PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, emptyContent, metadata); // Send request to S3 to create folder this.amazonS3Client.putObject(putObjectRequest); return new CirrusFolderData(key); }
From source file:com.cirrus.server.osgi.service.amazon.s3.AmazonS3StorageService.java
License:Apache License
@Override public CirrusFileData transferFile(final String filePath, final long fileSize, final InputStream inputStream) throws ServiceRequestFailedException { final ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(fileSize); this.amazonS3Client.putObject(BUCKET_NAME, filePath, inputStream, metadata); return new CirrusFileData(SEPARATOR + filePath, fileSize); }
From source file:com.clicktravel.infrastructure.persistence.aws.s3.S3FileStore.java
License:Apache License
@Override public void write(final FilePath filePath, final FileItem fileItem) { checkInitialization();/* w w w.ja v a 2s .co m*/ final ObjectMetadata metadata = new ObjectMetadata(); metadata.addUserMetadata(USER_METADATA_FILENAME, fileItem.filename()); metadata.addUserMetadata(USER_METADATA_LAST_UPDATED_TIME, formatter.print(fileItem.lastUpdatedTime())); metadata.setContentLength(fileItem.getBytes().length); final InputStream is = new ByteArrayInputStream(fileItem.getBytes()); final String bucketName = bucketNameForFilePath(filePath); if (!amazonS3Client.doesBucketExist(bucketName)) { createBucket(bucketName); } final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath.filename(), is, metadata); amazonS3Client.putObject(putObjectRequest); }
From source file:com.cloud.utils.S3Utils.java
License:Apache License
public static boolean canReadWriteBucket(final ClientOptions clientOptions, final String bucketName) { assert clientOptions != null; assert isNotBlank(bucketName); try {//from w w w .j av a 2 s .c o m final AmazonS3 client = acquireClient(clientOptions); final String fileContent = "testing put and delete"; final InputStream inputStream = new ByteArrayInputStream(fileContent.getBytes()); final String key = UUID.randomUUID().toString() + ".txt"; final ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(fileContent.length()); client.putObject(bucketName, key, inputStream, metadata); client.deleteObject(bucketName, key); return true; } catch (AmazonClientException e) { return false; } }
From source file:com.cloudbees.demo.beesshop.web.ProductController.java
License:Apache License
/** * @param id id of the product/*from w ww .ja va 2 s. c om*/ * @param photo to associate with the product * @return redirection to display product */ @RequestMapping(value = "/product/{id}/photo", method = RequestMethod.POST) @Transactional public String updatePhoto(@PathVariable long id, @RequestParam("photo") MultipartFile photo) { if (photo.getSize() == 0) { logger.info("Empty uploaded file"); } else { try { String contentType = fileStorageService.findContentType(photo.getOriginalFilename()); if (contentType == null) { logger.warn("Skip file with unsupported extension '{}'", photo.getName()); } else { InputStream photoInputStream = photo.getInputStream(); long photoSize = photo.getSize(); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(photoSize); objectMetadata.setContentType(contentType); objectMetadata .setCacheControl("public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS)); String photoUrl = fileStorageService.storeFile(photoInputStream, objectMetadata); Product product = productRepository.get(id); logger.info("Saved {}", photoUrl); product.setPhotoUrl(photoUrl); productRepository.update(product); } } catch (IOException e) { throw Throwables.propagate(e); } } return "redirect:/product/" + id; }