List of usage examples for com.amazonaws AmazonServiceException getErrorType
public ErrorType getErrorType()
From source file:com.hussi.aws.dynamoDB.AmazonDynamoDBSample.java
License:Open Source License
public static void main(String[] args) throws Exception { init();//from ww w . j a va 2 s . c o m try { String tableName = "hussi_first_dynamo_table"; // Create a table with a primary hash key named 'name', which holds a string CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) .withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH)) .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name") .withAttributeType(ScalarAttributeType.S)) .withProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L)); // Create table if it does not exist yet TableUtils.createTableIfNotExists(dynamoDB, createTableRequest); // wait for the table to move into ACTIVE state TableUtils.waitUntilActive(dynamoDB, tableName); // Describe our new table DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName); TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable(); System.out.println("Table Description: " + tableDescription); // Add an item Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James", "Sara"); PutItemRequest putItemRequest = new PutItemRequest(tableName, item); PutItemResult putItemResult = dynamoDB.putItem(putItemRequest); System.out.println("Result: " + putItemResult); // Add another item item = newItem("Airplane", 1980, "*****", "James", "Billy Bob"); putItemRequest = new PutItemRequest(tableName, item); putItemResult = dynamoDB.putItem(putItemRequest); System.out.println("Result: " + putItemResult); // Scan items for movies with a year attribute greater than 1985 HashMap<String, Condition> scanFilter = new HashMap<String, Condition>(); Condition condition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString()) .withAttributeValueList(new AttributeValue().withN("1985")); scanFilter.put("year", condition); ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter); ScanResult scanResult = dynamoDB.scan(scanRequest); System.out.println("Result: " + scanResult); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS, 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 " + "a serious internal problem while trying to communicate with AWS, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:com.imos.sample.S3SampleCheck.java
License:Open Source License
public static void main(String[] args) throws IOException { /*//w w w . j a v a2 s. com * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (/home/alok/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default").getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (/home/alok/.aws/credentials), and is in valid format.", e); } AmazonS3 s3 = new AmazonS3Client(credentials); // Region usWest2 = Region.getRegion(Regions.US_WEST_2); Region usWest2 = Region.getRegion(Regions.AP_SOUTHEAST_1); s3.setRegion(usWest2); String bucketName = "alok-test"; String key = "sample.json"; System.out.println("==========================================="); System.out.println("Getting Started with Amazon S3"); System.out.println("===========================================\n"); try { /* * Create a new S3 bucket - Amazon S3 bucket names are globally unique, * so once a bucket name has been taken by any user, you can't create * another bucket with that same name. * * You can optionally specify a location for your bucket if you want to * keep your data closer to your applications or users. */ // System.out.println("Creating bucket " + bucketName + "\n"); // s3.createBucket(bucketName); /* * List the buckets in your account */ // System.out.println("Listing buckets"); // for (Bucket bucket : s3.listBuckets()) { // System.out.println(" - " + bucket.getName()); // } System.out.println(); /* * 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())); s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile())); /* * Download an object - When you download an object, you get all of * the object's metadata and a stream from which to read the contents. * It's important to read the contents of the stream as quickly as * possibly since the data is streamed directly from Amazon S3 and your * network connection will remain open until you read all the data or * close the input stream. * * GetObjectRequest also supports several other options, including * conditional downloading of objects based on modification times, * ETags, and selectively downloading a range of an object. */ System.out.println("Downloading an object"); // S3Object object = s3.getObject(new GetObjectRequest(bucketName, key)); S3Object object = s3.getObject(new GetObjectRequest("alok-test", key)); System.out.println("Content-Type: " + object.getObjectMetadata().getContentType()); displayTextInputStream(object.getObjectContent()); /* * List objects in your bucket by prefix - There are many options for * listing the objects in your bucket. Keep in mind that buckets with * many objects might truncate their results when listing their objects, * so be sure to check if the returned object listing is truncated, and * use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve * additional results. */ System.out.println("Listing objects"); ObjectListing objectListing = s3.listObjects(new ListObjectsRequest() // .withBucketName(bucketName) .withBucketName("alok-test")); // .withPrefix("My")); objectListing.getObjectSummaries().forEach((objectSummary) -> { System.out.println( " - " + objectSummary.getKey() + " " + "(size = " + objectSummary.getSize() + ")"); }); System.out.println(); /* * Delete an object - Unless versioning has been turned on for your bucket, * there is no way to undelete an object, so use caution when deleting objects. */ // System.out.println("Deleting an object\n"); // s3.deleteObject(bucketName, key); /* * Delete a bucket - A bucket must be completely empty before it can be * deleted, so remember to delete any objects from your buckets before * you try to delete them. */ // System.out.println("Deleting bucket " + bucketName + "\n"); // s3.deleteBucket(bucketName); } 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 " + "a serious internal problem while trying to communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:com.intuit.s3encrypt.S3Encrypt.java
License:Open Source License
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // create Options object Options options = new Options(); options.addOption(create_bucket);/*w ww .j a v a2 s . co m*/ options.addOption(create_key); options.addOption(delete_bucket); options.addOption(get); options.addOption(help); options.addOption(inspect); options.addOption(keyfile); options.addOption(list_buckets); options.addOption(list_objects); options.addOption(put); options.addOption(remove); options.addOption(rotate); options.addOption(rotateall); options.addOption(rotateKey); // CommandLineParser parser = new GnuParser(); // Changed from above GnuParser to below PosixParser because I found code which allows for multiple arguments PosixParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); Logger.getRootLogger().setLevel(Level.OFF); if (cmd.hasOption("help")) { HelpFormatter help = new HelpFormatter(); System.out.println(); help.printHelp("S3Encrypt", options); System.out.println(); System.exit(1); } else if (cmd.hasOption("create_key")) { keyname = cmd.getOptionValue("keyfile"); createKeyFile(keyname); key = new File(keyname); } else { if (cmd.hasOption("keyfile")) { keyname = cmd.getOptionValue("keyfile"); } key = new File(keyname); } if (!(key.exists())) { System.out.println("Key does not exist or not provided"); System.exit(1); } // AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider()); ClasspathPropertiesFileCredentialsProvider credentials = new ClasspathPropertiesFileCredentialsProvider( ".s3encrypt"); EncryptionMaterials encryptionMaterials = new EncryptionMaterials(getKeyFile(keyname)); AmazonS3EncryptionClient s3 = new AmazonS3EncryptionClient(credentials.getCredentials(), encryptionMaterials); // Region usWest2 = Region.getRegion(Regions.US_WEST_2); // s3.setRegion(usWest2); if (cmd.hasOption("create_bucket")) { String bucket = cmd.getOptionValue("create_bucket"); System.out.println("Creating bucket " + bucket + "\n"); s3.createBucket(bucket); } else if (cmd.hasOption("delete_bucket")) { String bucket = cmd.getOptionValue("delete_bucket"); System.out.println("Deleting bucket " + bucket + "\n"); s3.deleteBucket(bucket); } else if (cmd.hasOption("get")) { String[] searchArgs = cmd.getOptionValues("get"); String bucket = searchArgs[0]; String filename = searchArgs[1]; getS3Object(cmd, s3, bucket, filename); } else if (cmd.hasOption("inspect")) { String[] searchArgs = cmd.getOptionValues("inspect"); String bucket = searchArgs[0]; String filename = searchArgs[1]; String keyname = "encryption_key"; String metadata = inspectS3Object(cmd, s3, bucket, filename, keyname); System.out.println(metadata); } else if (cmd.hasOption("list_buckets")) { System.out.println("Listing buckets"); for (Bucket bucket : s3.listBuckets()) { System.out.println(bucket.getName()); } System.out.println(); } else if (cmd.hasOption("list_objects")) { String bucket = cmd.getOptionValue("list_objects"); System.out.println("Listing objects"); ObjectListing objectListing = s3.listObjects(new ListObjectsRequest().withBucketName(bucket)); for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) { System.out.println(objectSummary.getKey() + " " + "(size = " + objectSummary.getSize() + ")"); } System.out.println(); } else if (cmd.hasOption("put")) { String[] searchArgs = cmd.getOptionValues("put"); String bucket = searchArgs[0]; String filename = searchArgs[1]; String metadataKeyname = "encryption_key"; String key = keyname; putS3Object(cmd, s3, bucket, filename, metadataKeyname, key); } else if (cmd.hasOption("remove")) { String[] searchArgs = cmd.getOptionValues("remove"); String bucket = searchArgs[0]; String filename = searchArgs[1]; System.out.println("Removing object in S3 from BUCKET = " + bucket + " FILENAME = " + filename); s3.deleteObject(new DeleteObjectRequest(bucket, filename)); System.out.println(); } else if (cmd.hasOption("rotate")) { String[] searchArgs = cmd.getOptionValues("rotate"); String bucket = searchArgs[0]; String filename = searchArgs[1]; String key1 = cmd.getOptionValue("keyfile"); String key2 = cmd.getOptionValue("rotateKey"); String metadataKeyname = "encryption_key"; System.out.println("Supposed to get object from here OPTION VALUE = " + bucket + " FILENAME = " + filename + " KEY1 = " + key1 + " KEY2 = " + key2); EncryptionMaterials rotateEncryptionMaterials = new EncryptionMaterials(getKeyFile(key2)); AmazonS3EncryptionClient rotateS3 = new AmazonS3EncryptionClient(credentials.getCredentials(), rotateEncryptionMaterials); getS3Object(cmd, s3, bucket, filename); putS3Object(cmd, rotateS3, bucket, filename, metadataKeyname, key2); } else if (cmd.hasOption("rotateall")) { String[] searchArgs = cmd.getOptionValues("rotateall"); String bucket = searchArgs[0]; String key1 = searchArgs[1]; String key2 = searchArgs[2]; System.out.println("Supposed to rotateall here for BUCKET NAME = " + bucket + " KEY1 = " + key1 + " KEY2 = " + key2); } else { System.out.println("Something went wrong... "); System.exit(1); } } catch (ParseException e) { e.printStackTrace(); } 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()); } }
From source file:com.jfixby.scarabei.red.aws.test.S3Sample.java
License:Open Source License
public static void main(final String[] args) throws IOException { /*//from w ww . j a v a 2 s . com * The ProfileCredentialsProvider will return your [default] credential profile by reading from the credentials file located * at (C:\\Users\\JCode\\.aws\\credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default").getCredentials(); } catch (final Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (C:\\Users\\%USERNAME%\\.aws\\credentials), and is in valid format.", e); } final AmazonS3 s3 = new AmazonS3Client(credentials); final Region usWest2 = Region.getRegion(Regions.US_WEST_2); s3.setRegion(usWest2); final String bucketName = "my-first-s3-bucket-" + UUID.randomUUID(); final String key = "MyObjectKey"; System.out.println("==========================================="); System.out.println("Getting Started with Amazon S3"); System.out.println("===========================================\n"); try { /* * Create a new S3 bucket - Amazon S3 bucket names are globally unique, so once a bucket name has been taken by any user, * you can't create another bucket with that same name. * * You can optionally specify a location for your bucket if you want to keep your data closer to your applications or * users. */ System.out.println("Creating bucket " + bucketName + "\n"); s3.createBucket(bucketName); /* * List the buckets in your account */ System.out.println("Listing buckets"); for (final Bucket bucket : s3.listBuckets()) { System.out.println(" - " + bucket.getName()); } System.out.println(); /* * 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())); /* * Download an object - When you download an object, you get all of the object's metadata and a stream from which to read * the contents. It's important to read the contents of the stream as quickly as possibly since the data is streamed * directly from Amazon S3 and your network connection will remain open until you read all the data or close the input * stream. * * GetObjectRequest also supports several other options, including conditional downloading of objects based on * modification times, ETags, and selectively downloading a range of an object. */ System.out.println("Downloading an object"); final S3Object object = s3.getObject(new GetObjectRequest(bucketName, key)); System.out.println("Content-Type: " + object.getObjectMetadata().getContentType()); displayTextInputStream(object.getObjectContent()); /* * List objects in your bucket by prefix - There are many options for listing the objects in your bucket. Keep in mind * that buckets with many objects might truncate their results when listing their objects, so be sure to check if the * returned object listing is truncated, and use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve * additional results. */ System.out.println("Listing objects"); final ObjectListing objectListing = s3 .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My")); for (final S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) { System.out.println( " - " + objectSummary.getKey() + " " + "(size = " + objectSummary.getSize() + ")"); } System.out.println(); /* * Delete an object - Unless versioning has been turned on for your bucket, there is no way to undelete an object, so use * caution when deleting objects. */ System.out.println("Deleting an object\n"); s3.deleteObject(bucketName, key); /* * Delete a bucket - A bucket must be completely empty before it can be deleted, so remember to delete any objects from * your buckets before you try to delete them. */ System.out.println("Deleting bucket " + bucketName + "\n"); s3.deleteBucket(bucketName); } catch (final 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 (final AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:com.kirana.utils.GeneratePresignedUrlAndUploadObject.java
public static void main(String[] args) throws IOException { System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true"); System.setProperty(SDKGlobalConfiguration.ACCESS_KEY_ENV_VAR, "AKIAJ666LALJZHA6THGQ"); System.setProperty(SDKGlobalConfiguration.SECRET_KEY_ENV_VAR, "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"); // AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider("kirana")); ProfilesConfigFile profile = new ProfilesConfigFile("AwsCredentials.properties"); AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider()); s3client.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1)); try {/*from ww w . ja v a 2 s.co m*/ System.out.println("Generating pre-signed URL."); java.util.Date expiration = new java.util.Date(); long milliSeconds = expiration.getTime(); milliSeconds += 1000 * 60 * 60; // Add 1 hour. expiration.setTime(milliSeconds); GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectKey); generatePresignedUrlRequest.setMethod(HttpMethod.PUT); generatePresignedUrlRequest.setExpiration(expiration); // s3client.putObject(bucketName, objectKey, null); URL url = s3client.generatePresignedUrl(generatePresignedUrlRequest); UploadObject(url); System.out.println("Pre-Signed URL = " + url.toString()); } catch (AmazonServiceException exception) { 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: " + exception.getMessage()); System.out.println("HTTP Code: " + exception.getStatusCode()); System.out.println("AWS Error Code:" + exception.getErrorCode()); System.out.println("Error Type: " + exception.getErrorType()); System.out.println("Request ID: " + exception.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()); } }
From source file:com.kiribuki.queueservice.QueueService.java
License:Open Source License
public boolean SendMessage(String message) { if (swok == true) { try {/*from w w w.j a v a 2s .com*/ sqs.sendMessage(new SendMessageRequest(myQueueUrl, message)); swok = true; } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon SQS, 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()); swok = false; } } return swok; }
From source file:com.liferay.portal.store.s3.S3Store.java
License:Open Source License
protected SystemException transform(AmazonClientException amazonClientException) { if (amazonClientException instanceof AmazonServiceException) { AmazonServiceException amazonServiceException = (AmazonServiceException) amazonClientException; StringBundler sb = new StringBundler(11); sb.append("{errorCode="); String errorCode = amazonServiceException.getErrorCode(); sb.append(errorCode);/*from ww w. j a va 2 s. c o m*/ sb.append(", errorType="); sb.append(amazonServiceException.getErrorType()); sb.append(", message="); sb.append(amazonServiceException.getMessage()); sb.append(", requestId="); sb.append(amazonServiceException.getRequestId()); sb.append(", statusCode="); sb.append(amazonServiceException.getStatusCode()); sb.append("}"); if (errorCode.equals("AccessDenied")) { return new AccessDeniedException(sb.toString()); } return new SystemException(sb.toString()); } else { return new SystemException(amazonClientException.getMessage(), amazonClientException); } }
From source file:com.maya.portAuthority.util.ImageUploader.java
public static void uploadImage(String imageURL, String imageName, String bucketName) throws MalformedURLException, IOException { // credentials object identifying user for authentication AWSCredentials credentials = new BasicAWSCredentials("AKIAJBFSMHRTIQQ7BKYA", "AdHgeP4dyWInWwPn9YlfxFCm3qP1lHjdxOxeJqDa"); // create a client connection based on credentials AmazonS3 s3client = new AmazonS3Client(credentials); String folderName = "image"; //folder name // String bucketName = "ppas-image-upload"; //must be unique try {//from ww w .j a v a 2 s. c o m 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.mycompany.mytubeaws.DownloadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//ww w . j av a 2s .c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String result = ""; String downloadLink = ""; String inputKey = request.getParameter("downloadKey"); if (inputKey == null) result += "inputKey is null; "; else if (inputKey.length() == 0) result += "inputKey is blank; "; else { result += "Downloading an object; "; try { // S3Object object = s3.getObject(new GetObjectRequest(bucketName, inputKey)); // S3ObjectInputStream objectContent = object.getObjectContent(); // // File f = File.createTempFile("aws-java-sdk-download", ""); // FileOutputStream fos = new FileOutputStream(f); // IOUtils.copy(objectContent, fos); // fos.close(); // // result += "Content-Type: '" + object.getObjectMetadata().getContentType() + "'; "; // result += "Mime '" + new MimetypesFileTypeMap().getContentType(f) + "'; "; // // response.setContentType(new MimetypesFileTypeMap().getContentType(f)); // response.setHeader("Content-Disposition","attachment;filename="+inputKey); // // ServletOutputStream out = response.getOutputStream(); // // // f.delete(); GeneratePresignedUrlRequest requestUrl = new GeneratePresignedUrlRequest(bucketName, inputKey); downloadLink = s3.generatePresignedUrl(requestUrl).toString(); System.out.println(downloadLink); //result += downloadLink + " ; "; } 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()); result += "AmazonServiceException thrown; "; } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); result += "AmazonClientException thrown; "; } } System.out.println(result); request.setAttribute("resultText", result); request.setAttribute("downloadLink", downloadLink); request.getRequestDispatcher("/DownloadResult.jsp").forward(request, response); //response.sendRedirect("UploadResult.jsp"); }
From source file:com.mycompany.mytubeaws.UploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w ww . j av a 2 s . c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String result = ""; String fileName = null; boolean uploaded = false; // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(1024 * 1024 * 3); // 3mb factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // sets temporary location to store files ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(1024 * 1024 * 40); // sets maximum size of upload file upload.setSizeMax(1024 * 1024 * 50); // sets maximum size of request (include file + form data) try { List<FileItem> formItems = upload.parseRequest(request); // parses the request's content to extract file data if (formItems != null && formItems.size() > 0) // iterates over form's fields { for (FileItem item : formItems) // processes only fields that are not form fields { if (!item.isFormField()) { fileName = item.getName(); UUID id = UUID.randomUUID(); fileName = FilenameUtils.getBaseName(fileName) + "_ID-" + id.toString() + "." + FilenameUtils.getExtension(fileName); File file = File.createTempFile("aws-java-sdk-upload", ""); item.write(file); // write form item to file (?) if (file.length() == 0) throw new RuntimeException("No file selected or empty file uploaded."); try { s3.putObject(new PutObjectRequest(bucketName, fileName, file)); result += "File uploaded successfully; "; uploaded = true; } 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()); result += "AmazonServiceException thrown; "; } catch (AmazonClientException ace) { System.out .println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); result += "AmazonClientException thrown; "; } file.delete(); } } } } catch (Exception ex) { result += "Generic exception: '" + ex.getMessage() + "'; "; ex.printStackTrace(); } if (fileName != null && uploaded) result += "Generated file ID: " + fileName; System.out.println(result); request.setAttribute("resultText", result); request.getRequestDispatcher("/UploadResult.jsp").forward(request, response); }