List of usage examples for com.amazonaws.services.s3 AmazonS3 putObject
public PutObjectResult putObject(PutObjectRequest putObjectRequest) throws SdkClientException, AmazonServiceException;
Uploads a new object to the specified Amazon S3 bucket.
From source file:net.smartcosmos.plugin.service.aws.storage.AwsS3StorageService.java
License:Apache License
@Override public StorageResponse store(StorageRequest request) throws IOException { final IFile requestFile = request.getFile(); AmazonS3 s3 = new AmazonS3Client(credentials, new ClientConfiguration().withProtocol(Protocol.HTTPS)); Map<String, String> fileMetadata = new HashMap<String, String>(); fileMetadata.put("accountUrn", request.getUser().getAccount().getUrn()); fileMetadata.put("userUrn", request.getUser().getUrn()); fileMetadata.put("fileUrn", requestFile.getUrn()); fileMetadata.put("entityReferenceType", requestFile.getEntityReferenceType().name()); fileMetadata.put("referenceUrn", requestFile.getReferenceUrn()); fileMetadata.put("recordedTimestamp", Long.toString(request.getFile().getTimestamp())); // fileMetadata.put("mimeType", request.getVfsObject().getMimeType()); ObjectMetadata metadata = new ObjectMetadata(); if (request.getContentLength() > 0) { LOG.debug("Including content length : " + request.getContentLength()); metadata.setContentLength(request.getContentLength()); }/*w w w . java2 s .c o m*/ // metadata.setContentMD5(streamMD5); metadata.setUserMetadata(fileMetadata); try { LOG.trace("Bucket name: " + getBucketName()); LOG.trace("File name: " + request.getFileName()); LOG.trace("inputStream == null? " + (request.getInputStream() == null)); HashingInputStream his = new HashingInputStream(request.getInputStream(), "SHA-256"); PutObjectResult putResult = s3 .putObject(new PutObjectRequest(getBucketName(), request.getFileName(), his, metadata)); String finalUrl = getUrl(request.getFileName()); LOG.trace("File URL: " + finalUrl); requestFile.setUrl(getUrl(request.getFileName())); byte[] signature = his.getSignature(); JSONObject jsonObject = HashUtil.signFile(requestFile, signature); LOG.info("File Signature\n\n{}\n\n", jsonObject.toString(3)); return new StorageResponse(requestFile, finalUrl, jsonObject.toString(3)); } catch (AmazonS3Exception e) { e.printStackTrace(); throw e; } catch (JSONException | NoSuchAlgorithmException e) { e.printStackTrace(); throw new IOException(e); } }
From source file:net.solarnetwork.node.backup.s3.SdkS3Client.java
License:Open Source License
@Override public S3ObjectReference putObject(String key, InputStream in, ObjectMetadata objectMetadata) throws IOException { AmazonS3 client = getClient(); try {/*www .j a va2 s. co m*/ PutObjectRequest req = new PutObjectRequest(bucketName, key, in, objectMetadata); client.putObject(req); return new S3ObjectReference(key, objectMetadata.getContentLength(), objectMetadata.getLastModified()); } catch (AmazonServiceException e) { log.warn("AWS error: {}; HTTP code {}; AWS code {}; type {}; request ID {}", e.getMessage(), e.getStatusCode(), e.getErrorCode(), e.getErrorType(), e.getRequestId()); throw new RemoteServiceException("Error putting S3 object at " + key, e); } catch (AmazonClientException e) { log.debug("Error communicating with AWS: {}", e.getMessage()); throw new IOException("Error communicating with AWS", e); } }
From source file:org.akvo.flow.deploy.Deploy.java
License:Open Source License
private static void uploadS3(String accessKey, String secretKey, String s3Path, File file) throws AmazonServiceException, AmazonClientException { BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); AmazonS3 s3 = new AmazonS3Client(credentials); PutObjectRequest putRequest = new PutObjectRequest(BUCKET_NAME, s3Path, file); ObjectMetadata metadata = new ObjectMetadata(); // set content type as android package file metadata.setContentType("application/vnd.android.package-archive"); // set content length to length of file metadata.setContentLength(file.length()); // set access to public putRequest.setMetadata(metadata);// www . j ava 2s . c o m putRequest.setCannedAcl(CannedAccessControlList.PublicRead); // try to put the apk in S3 PutObjectResult result = s3.putObject(putRequest); System.out.println("Apk uploaded successfully, with result ETag " + result.getETag()); }
From source file:org.alanwilliamson.amazon.s3.Write.java
License:Open Source License
private void writeData(AmazonKey amazonKey, String bucket, String key, Map<String, String> metadata, StorageClass storage, String mimetype, cfData data, int retry, int retryseconds, String acl, String aes256key, Map<String, String> customheaders) throws Exception { if (mimetype == null) { if (data.getDataType() == cfData.CFBINARYDATA) mimetype = "application/unknown"; else if (cfData.isSimpleValue(data)) mimetype = "text/plain"; else//from w w w.ja va 2 s . c om mimetype = "application/json"; // Check to see if the mime type is in the metadata if (metadata != null && metadata.containsKey("Content-Type")) mimetype = metadata.get("Content-Type"); } InputStream ios = null; long size = 0; if (data.getDataType() == cfData.CFSTRINGDATA) { ios = new java.io.ByteArrayInputStream(data.getString().getBytes()); size = data.getString().length(); } else if (data.getDataType() == cfData.CFBINARYDATA) { ios = new java.io.ByteArrayInputStream(((cfBinaryData) data).getByteArray()); size = ((cfBinaryData) data).getLength(); } else { serializejson json = new serializejson(); StringBuilder out = new StringBuilder(); json.encodeJSON(out, data, false, CaseType.MAINTAIN, DateType.LONG); size = out.length(); mimetype = "application/json"; ios = new java.io.ByteArrayInputStream(out.toString().getBytes()); } // Setup the object data ObjectMetadata omd = new ObjectMetadata(); if (metadata != null) omd.setUserMetadata(metadata); omd.setContentType(mimetype); omd.setContentLength(size); AmazonS3 s3Client = getAmazonS3(amazonKey); // Let us run around the number of attempts int attempts = 0; while (attempts < retry) { try { PutObjectRequest por = new PutObjectRequest(bucket, key, ios, omd); por.setStorageClass(storage); if (aes256key != null && !aes256key.isEmpty()) por.setSSECustomerKey(new SSECustomerKey(aes256key)); if (acl != null && !acl.isEmpty()) por.setCannedAcl(amazonKey.getAmazonCannedAcl(acl)); if (customheaders != null && !customheaders.isEmpty()) { Iterator<String> it = customheaders.keySet().iterator(); while (it.hasNext()) { String k = it.next(); por.putCustomRequestHeader(k, customheaders.get(k)); } } s3Client.putObject(por); break; } catch (Exception e) { cfEngine.log("Failed: AmazonS3Write(bucket=" + bucket + "; key=" + key + "; attempt=" + (attempts + 1) + "; exception=" + e.getMessage() + ")"); attempts++; if (attempts == retry) throw e; else Thread.sleep(retryseconds * 1000); } } }
From source file:org.alanwilliamson.amazon.s3.Write.java
License:Open Source License
private void writeFile(AmazonKey amazonKey, String bucket, String key, Map<String, String> metadata, StorageClass storage, String localpath, int retry, int retryseconds, boolean deletefile, boolean background, String callback, String callbackdata, String appname, String acl, String aes256key, Map<String, String> customheaders) throws Exception { File localFile = new File(localpath); if (!localFile.isFile()) throw new Exception("The file specified does not exist: " + localpath); // Push this to the background loader to handle and return immediately if (background) { BackgroundUploader.acceptFile(amazonKey, bucket, key, metadata, storage, localpath, retry, retryseconds, deletefile, callback, callbackdata, appname, acl, aes256key, customheaders); return;//from ww w .j a va2 s.c o m } // Setup the object data ObjectMetadata omd = new ObjectMetadata(); if (metadata != null) omd.setUserMetadata(metadata); AmazonS3 s3Client = getAmazonS3(amazonKey); // Let us run around the number of attempts int attempts = 0; while (attempts < retry) { try { PutObjectRequest por = new PutObjectRequest(bucket, key, localFile); por.setMetadata(omd); por.setStorageClass(storage); if (acl != null && !acl.isEmpty()) por.setCannedAcl(amazonKey.getAmazonCannedAcl(acl)); if (aes256key != null && !aes256key.isEmpty()) por.setSSECustomerKey(new SSECustomerKey(aes256key)); if (customheaders != null && !customheaders.isEmpty()) { Iterator<String> it = customheaders.keySet().iterator(); while (it.hasNext()) { String k = it.next(); por.putCustomRequestHeader(k, customheaders.get(k)); } } s3Client.putObject(por); break; } catch (Exception e) { cfEngine.log("Failed: AmazonS3Write(bucket=" + bucket + "key=" + key + "; file=" + localFile + "; attempt=" + (attempts + 1) + "; exception=" + e.getMessage() + ")"); attempts++; if (attempts == retry) throw e; else Thread.sleep(retryseconds * 1000); } } // delete the file now that it is a success if (deletefile) localFile.delete(); }
From source file:org.applicationMigrator.migrationclient.FileTransferClient.java
License:Apache License
private void uploadFile(AWSCredentials awsCredentials, String sourcePathString, String destinationPathString, boolean forceUpload) throws FileNotFoundException { // TODO Think about one file being used by many apps (e.g HP1.pdf read // through Adobe reader and OpenOffice) AmazonS3 s3client = new AmazonS3Client(awsCredentials); boolean fileIsPresentOnServer = checkIfFileIsPresentOnServer(s3client, BUCKET_NAME, destinationPathString); if (fileIsPresentOnServer && !forceUpload) return;/*from w ww . ja va 2 s .co m*/ try { File file = new File(sourcePathString); if (!file.exists()) throw new FileNotFoundException(); s3client.putObject(new PutObjectRequest(BUCKET_NAME, destinationPathString, file)); } catch (AmazonServiceException ase) { throw ase; } catch (AmazonClientException ace) { throw ace; } // TODO:verify completion of upload operation }
From source file:org.applicationMigrator.serverAgent.ServerAgentFileTransferClient.java
License:Apache License
private void uploadFile(AWSCredentials awsCredentials, String sourcePathString, String destinationPathString, boolean forceUpload) throws FileNotFoundException { // TODO Think about one file being used by many apps (e.g HP1.pdf read // through Adobe reader and OpenOffice) AmazonS3 s3client = new AmazonS3Client(awsCredentials); boolean fileIsPresentOnServer = checkIfFileIsPresentOnServer(s3client, BUCKET_NAME, destinationPathString); if (fileIsPresentOnServer && !forceUpload) return;/* w w w . jav a 2 s . c o m*/ try { File file = new File(sourcePathString); if (!file.exists()) throw new FileNotFoundException(); s3client.putObject(new PutObjectRequest(BUCKET_NAME, destinationPathString, file)); } 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()); throw ase; } 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()); throw ace; } // TODO:verify completion of upload operation }
From source file:org.benetech.secureapp.generator.AmazonS3Utils.java
License:Open Source License
static public void uploadToAmazonS3(HttpSession session, File fileToUpload) throws S3Exception { try {//from w ww . j a va 2 s. c om AmazonS3 s3client = getS3(); String bucketName = getDownloadS3Bucket(); if (!s3client.doesBucketExist(bucketName)) SagLogger.logError(session, "Does not exist? S3 Bucket :" + bucketName); AccessControlList acl = new AccessControlList(); acl.grantPermission(GroupGrantee.AllUsers, Permission.Read); s3client.putObject( new PutObjectRequest(bucketName, getAPKDownloadFilePathWithFile(fileToUpload.getName()), fileToUpload).withAccessControlList(acl)); SagLogger.logInfo(session, "Finished uploading to S3"); } catch (Exception e) { SagLogger.logException(session, e); throw new S3Exception(e); } }
From source file:org.boriken.s3fileuploader.S3SampleRefactored.java
License:Open Source License
public static void createFile(AmazonS3 s3, String bucketName, String key) throws IOException { /*/*w ww. j ava2s .com*/ * Upload an object to your bucket - You can easily upload a file to * S3, or upload directly an InputStream if you know the length of * the data in the stream. You can also specify your own metadata * when uploading to S3, which allows you set a variety of options * like content-type and content-encoding, plus additional metadata * specific to your applications. */ System.out.println("Uploading a new object to S3 from a file\n"); s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile())); }
From source file:org.clothocad.phagebook.adaptors.S3Adapter.java
public static void uploadProfilePicture(String clothoId, String filePath) { //String clothoId = pers.getId(); AWSCredentials credentials = new BasicAWSCredentials(S3Credentials.getUsername(), S3Credentials.getPassword()); System.out.println("Login Complete"); AmazonS3 s3client = new AmazonS3Client(credentials); String fileName = clothoId + "/" + "profilePicture.jpg"; s3client.putObject(new PutObjectRequest("phagebookaws", fileName, new File(filePath)) .withCannedAcl(CannedAccessControlList.PublicRead)); }