List of usage examples for com.amazonaws.services.s3.model PutObjectRequest PutObjectRequest
public PutObjectRequest(String bucketName, String key, String redirectLocation)
From source file:com.tvarit.plugin.TvaritTomcatDeployerMojo.java
License:Open Source License
@Override public void execute() throws MojoExecutionException, MojoFailureException { final MavenProject project = (MavenProject) this.getPluginContext().getOrDefault("project", null); if (templateUrl == null) try {//from w w w .j a v a 2 s. c o m templateUrl = new TemplateUrlMaker().makeUrl(project, "newinstance.template").toString(); } catch (MalformedURLException e) { throw new MojoExecutionException( "Could not create default url for templates. Please open an issue on github.", e); } final BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); AmazonS3Client s3Client = new AmazonS3Client(awsCredentials); final File warFile = project.getArtifact().getFile(); final String key = "deployables/" + project.getGroupId() + "/" + project.getArtifactId() + "/" + project.getVersion() + "/" + warFile.getName(); final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, warFile); final ObjectMetadata metadata = new ObjectMetadata(); final HashMap<String, String> userMetadata = new HashMap<>(); userMetadata.put("project_name", projectName); userMetadata.put("stack_template_url", templateUrl); userMetadata.put("private_key_name", sshKeyName); metadata.setUserMetadata(userMetadata); putObjectRequest.withMetadata(metadata); final PutObjectResult putObjectResult = s3Client.putObject(putObjectRequest); /* AmazonCloudFormationClient amazonCloudFormationClient = new AmazonCloudFormationClient(awsCredentials); final com.amazonaws.services.cloudformation.model.Parameter projectNameParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("projectName").withParameterValue(this.projectName); final com.amazonaws.services.cloudformation.model.Parameter publicSubnetsParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("publicSubnets").withParameterValue(commaSeparatedSubnetIds); final com.amazonaws.services.cloudformation.model.Parameter tvaritRoleParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("tvaritRole").withParameterValue(tvaritRole); final com.amazonaws.services.cloudformation.model.Parameter tvaritInstanceProfileParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("tvaritInstanceProfile").withParameterValue(this.tvaritInstanceProfile); final com.amazonaws.services.cloudformation.model.Parameter tvaritBucketNameParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("bucketName").withParameterValue(this.bucketName); final com.amazonaws.services.cloudformation.model.Parameter instanceSecurityGroupIdParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("sgId").withParameterValue(this.instanceSecurityGroupId); final com.amazonaws.services.cloudformation.model.Parameter sshKeyNameParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("keyName").withParameterValue(this.sshKeyName); final String warFileUrl = s3Client.getUrl(bucketName, key).toString(); final com.amazonaws.services.cloudformation.model.Parameter warFileUrlParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("warFileUrl").withParameterValue(warFileUrl); final CreateStackRequest createStackRequest = new CreateStackRequest(); if (templateUrl == null) { try { templateUrl = new TemplateUrlMaker().makeUrl(project, "newinstance.template").toString(); } catch (MalformedURLException e) { throw new MojoExecutionException("Could not create default url for templates. Please open an issue on github.", e); } } createStackRequest. withStackName(projectName + "-instance-" + project.getVersion().replace(".", "-")). withParameters( projectNameParameter, publicSubnetsParameter, tvaritInstanceProfileParameter, tvaritRoleParameter, tvaritBucketNameParameter, instanceSecurityGroupIdParameter, warFileUrlParameter, sshKeyNameParameter ). withDisableRollback(true). withTemplateURL(templateUrl); createStackRequest.withDisableRollback(true); final Stack stack = new StackMaker().makeStack(createStackRequest, amazonCloudFormationClient, getLog()); AmazonAutoScalingClient amazonAutoScalingClient = new AmazonAutoScalingClient(awsCredentials); final AttachInstancesRequest attachInstancesRequest = new AttachInstancesRequest(); attachInstancesRequest.withInstanceIds(stack.getOutputs().get(0).getOutputValue(), stack.getOutputs().get(1).getOutputValue()).withAutoScalingGroupName(autoScalingGroupName); amazonAutoScalingClient.attachInstances(attachInstancesRequest); */ }
From source file:com.ub.ml.S3Sample.java
License:Open Source License
public static void main(String[] args) throws IOException { /*//from w w w.j ava2 s .c o m * Create your credentials file at ~/.aws/credentials (C:\Users\USER_NAME\.aws\credentials for Windows users) * and save the following lines after replacing the underlined values with your own. * * [default] * aws_access_key_id = YOUR_ACCESS_KEY_ID * aws_secret_access_key = YOUR_SECRET_ACCESS_KEY */ AmazonS3 s3 = new AmazonS3Client(); Region usWest2 = Region.getRegion(Regions.US_EAST_1); s3.setRegion(usWest2); String bucketName = "my-first-s3-bucket-" + UUID.randomUUID(); 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 (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"); 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"); ObjectListing objectListing = s3 .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My")); for (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 (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.uiintl.backup.agent.AwsBackupAgent.java
License:Open Source License
public BackupResponse uploadFiles(final String backupPath, final String bucketName) { File[] files = this.readFiles(backupPath); BackupState backupState = BackupState.NO_FILE; BackupResponse.BackupResponseBuilder builder = BackupResponse.BackupResponseBuilder.builder(); if (files != null && files.length > 0) { logger.info("Detected {} files, begin uploading to S3.", files.length); long start = System.currentTimeMillis(); logger.info("Started at: {}", new Date()); int failCount = 0; for (File file : files) { try { long fileStart = System.currentTimeMillis(); logger.info("Uploading: {}", file.getAbsolutePath()); s3.putObject(new PutObjectRequest(bucketName, file.getName(), file)); logger.info("Successful. Took {} milliseconds", (System.currentTimeMillis() - fileStart)); } catch (AmazonClientException e) { logger.error("Error occurred: {}", e.getMessage(), e); handleAwsException(e);//from w w w. ja va 2 s. co m failCount++; } } long duration = System.currentTimeMillis() - start; logger.info("Finished at: {}", new Date()); logger.info("Total time spent in milliseconds: {}", duration); if (failCount == 0) { backupState = BackupState.SUCCESS; } else if (failCount > 0 && failCount < files.length) { backupState = BackupState.PARTIAL_FAIL; } else { backupState = BackupState.FAIL; } builder.setTotalFiles(files.length).setUploadedFiles(files.length - failCount) .setMessage("Finished. Duration is " + duration); } builder.setBackupState(backupState); return builder.build(); }
From source file:com.uiintl.backup.agent.samples.S3Sample.java
License:Open Source License
public static void main2(String[] args) throws IOException { /*//from ww w.ja va 2 s . c o m * This credentials provider implementation loads your AWS credentials * from a properties file at the root of your classpath. * * Important: Be sure to fill in your AWS access credentials in the * AwsCredentials.properties file before you try to run this * sample. * http://aws.amazon.com/security-credentials */ AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider()); Region usWest2 = Region.getRegion(Regions.AP_SOUTHEAST_2); s3.setRegion(usWest2); String bucketName = "my-first-s3-bucket-" + UUID.randomUUID(); 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 (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"); 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"); ObjectListing objectListing = s3 .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My")); for (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 (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.universal.storage.UniversalS3Storage.java
License:Open Source License
/** * This method uploads a file with a length lesser than PART_SIZE (5Mb). * //from w w w .ja va 2s.com * @param file to be stored within the storage. * @param path is the path for this new file within the root. * @throws UniversalIOException when a specific IO error occurs. */ private void uploadTinyFile(File file, String path) throws UniversalIOException { try { ObjectMetadata objectMetadata = new ObjectMetadata(); if (this.settings.getEncryption()) { objectMetadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); } List<Tag> tags = new ArrayList<Tag>(); for (String key : this.settings.getTags().keySet()) { tags.add(new Tag(key, this.settings.getTags().get(key))); } PutObjectRequest request = new PutObjectRequest( this.settings.getRoot() + ("".equals(path) ? "" : ("/" + path)), file.getName(), file); request.setMetadata(objectMetadata); request.setTagging(new ObjectTagging(tags)); request.setStorageClass(getStorageClass()); this.triggerOnStoreFileListeners(); PutObjectResult result = this.s3client.putObject(request); this.triggerOnFileStoredListeners(new UniversalStorageData(file.getName(), PREFIX_S3_URL + (this.settings.getRoot() + ("".equals(path) ? "" : ("/" + path))) + "/" + file.getName(), result.getVersionId(), this.settings.getRoot() + ("".equals(path) ? "" : ("/" + path)))); } catch (Exception e) { UniversalIOException error = new UniversalIOException(e.getMessage()); this.triggerOnErrorListeners(error); throw error; } }
From source file:com.vanilla.transmilenio.servicio.AmazonServicio.java
public String guardarArchivo(File file, String nombreArchivo) { PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, nombreArchivo, file); putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead); s3client.putObject(putObjectRequest); String url = "https://s3.amazonaws.com/" + bucketName + "/" + nombreArchivo; return url;// ww w . j a v a 2 s . c om }
From source file:com.vitembp.services.interfaces.AmazonSimpleStorageService.java
License:Open Source License
/** * Uploads a file to S3 storage and sets its ACL to allow public access. * @param toUpload The file to uploadPublic. * @param destination The destination in the bucket to store the file. * @throws java.io.IOException If an I/O exception occurs while uploading * the file.//from w ww . j av a2s . co m */ public void uploadPublic(File toUpload, String destination) throws IOException { try { // create a request that makes the object public PutObjectRequest req = new PutObjectRequest(this.bucketName, destination, toUpload); req.setCannedAcl(CannedAccessControlList.PublicRead); // uploadPublic the file and wait for completion Upload xfer = this.transferManager.upload(req); xfer.waitForCompletion(); } catch (AmazonServiceException ex) { LOGGER.error("Exception uploading " + toUpload.toString(), ex); throw new IOException("Exception uploading " + toUpload.toString(), ex); } catch (AmazonClientException | InterruptedException ex) { LOGGER.error("Exception uploading " + toUpload.toString(), ex); throw new IOException("Exception uploading " + toUpload.toString(), ex); } }
From source file:com.wowza.wms.plugin.s3upload.ModuleS3Upload.java
License:Open Source License
private void resumeUploads() { if (!resumeUploads) { transferManager.abortMultipartUploads(bucketName, new Date()); return;/*from ww w .j ava 2s . c o m*/ } File storageDir = new File(appInstance.getStreamStorageDir()); File[] files = storageDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".upload"); } }); for (File file : files) { String mediaName = file.getPath().replace(storageDir.getPath(), ""); if (mediaName.startsWith("/")) mediaName = mediaName.substring(1); mediaName = mediaName.substring(0, mediaName.indexOf(".upload")); Upload upload = null; FileInputStream fis = null; try { if (file.length() == 0) { File mediaFile = new File(storageDir, mediaName); if (mediaFile.exists()) { // In order to support setting ACL permissions for the file upload, we will wrap the upload properties in a PutObjectRequest PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, mediaName, file); // If the user has specified ACL properties, setup the putObjectRequest with the acl permissions generated if (acl != null) { putObjectRequest.withAccessControlList(acl); } upload = transferManager.upload(putObjectRequest); } else { file.delete(); } } else { fis = new FileInputStream(file); // Deserialize PersistableUpload information from disk. PersistableUpload persistableUpload = PersistableTransfer.deserializeFrom(fis); upload = transferManager.resumeUpload(persistableUpload); } if (upload != null) upload.addProgressListener(new ProgressListener(mediaName)); } catch (Exception e) { logger.error(MODULE_NAME + ".resumeUploads error resuming upload: [" + appInstance.getContextStr() + "/" + file.getName() + "]", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } } } }
From source file:com.zhang.aws.s3.S3Sample.java
License:Open Source License
public static void main(String[] args) throws IOException { /*/*from w w w . ja v a2 s.c o m*/ * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (~/.aws/credentials). */ ResourceBundle bundle = ResourceBundle.getBundle("credentials"); AWSCredentials credentials = null; try { // credentials = new ProfileCredentialsProvider().getCredentials(); credentials = new BasicAWSCredentials(bundle.getString("aws_access_key_id"), bundle.getString("aws_secret_access_key")); } 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 (~/.aws/credentials), and is in valid format.", e); } AmazonS3 s3 = new AmazonS3Client(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); s3.setRegion(usWest2); String bucketName = "elasticbeanstalk-us-west-2-948206320069"; String key = "MyObjectKey2"; 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, getFileFromDisk())); /*** * * ?url * */ GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, key); URL generatePresignedUrl = s3.generatePresignedUrl(urlRequest); System.out.println("public url:" + generatePresignedUrl.toString()); /* * 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)); // 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).withPrefix("My")); for (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); System.out.println("------------------------------------------"); } 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:controllers.s3locationmodify.java
License:Open Source License
public static void main(String[] args) throws Exception { /*//from ww w. ja va2s. co m * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (/home/sravya/.aws/credentials). * * TransferManager manages a pool of threads, so we create a * single instance and share it throughout our application. */ 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/sravya/.aws/credentials), and is in valid format.", e); } int argLen = args.length; Region reg = Region.getRegion(Regions.US_WEST_2); int hack = 0; int userrequests; try { userrequests = Integer.parseInt(args[argLen - 1]); } catch (NumberFormatException e) { userrequests = 1; String use = args[argLen - 1]; if (use.equals("Australia")) { hack = 0; } else if (use.equals("SouthAfrica")) { hack = 1; } else if (use.equals("India")) { hack = 2; } else if (use.equals("UnitedKingdom")) { hack = 3; } else if (use.equals("China")) { hack = 4; } else if (use.equals("Germany")) { hack = 5; } else if (use.equals("France")) { hack = 6; } else if (use.equals("Japan")) { hack = 7; } else if (use.equals("Thailand")) { hack = 8; } else if (use.equals("Spain")) { hack = 9; } } int filecount = 0; for (int m = 0; m < argLen - 1; m++) { filecount = filecount + 1; } int numphotos = filecount; int numIDCs = numphotos; int locationInd = 0; long[] cusize = new long[6]; long photosspace = 0; for (int mm = 0; mm < userrequests; mm++) { for (int i = 0; i < cusize.length; i++) cusize[i] = 0; ArrayList<Integer> originalgarph = new ArrayList<Integer>(); loadObj ob = calculateload(); long[] regionload = new long[5]; regionload = ob.load; for (int i = 0; i < regionload.length; i++) { if (regionload[i] == 0) { regionload[i] = 1000; } } /*for (int i=0; i<5 ;i++) { System.out.println(regionload[i]); double diffload=0; double avgload=0; int count=0; for(int j=0;j<5; j++) { if(j!=i) { avgload = avgload + regionload[j]; count++; } } avgload= (avgload / count); diffload= (regionload[i]/avgload) ; System.out.println("avgload: "+ avgload); System.out.println("diffload: "+ diffload); if(diffload < 1.8) { originalgarph.add(i+1); } }*/ for (int i = 0; i < 5; i++) { originalgarph.add(i + 1); } availSpaceNorthCal = maxsize - regionload[0]; photosspace = numphotos * 6000; if (availSpaceNorthCal < photosspace) { availSpaceNorthCal = maxsize; cusize[1] = availSpaceNorthCal / 6000; } else { cusize[1] = availSpaceNorthCal / 6000; } availSpaceOregon = maxsize - regionload[1]; photosspace = numphotos * 6000; if (availSpaceOregon < photosspace) { availSpaceOregon = maxsize; cusize[2] = availSpaceOregon / 6000; } else { cusize[2] = availSpaceOregon / 6000; } availSpaceSingapore = maxsize - regionload[2]; photosspace = numphotos * 6000; if (availSpaceSingapore < photosspace) { availSpaceSingapore = maxsize; cusize[3] = availSpaceSingapore / 6000; } else { cusize[3] = availSpaceSingapore / 6000; } availSpaceTokyo = maxsize - regionload[3]; photosspace = numphotos * 6000; if (availSpaceTokyo < photosspace) { availSpaceTokyo = maxsize; cusize[4] = availSpaceTokyo / 6000; } else { cusize[4] = availSpaceTokyo / 6000; } availSpaceSydney = maxsize - regionload[4]; photosspace = numphotos * 6000; if (availSpaceSydney < photosspace) { availSpaceSydney = maxsize; cusize[5] = availSpaceSydney / 6000; } else { cusize[5] = availSpaceSydney / 6000; } int cou = originalgarph.size(); String fileName = algorithmPath + "request.alg"; PrintWriter writer = new PrintWriter(fileName, "UTF-8"); for (int i = 0; i < cou; i++) { int value = originalgarph.get(i); writer.print(value + " "); System.out.println(" IDC " + String.valueOf(value)); } writer.println(); for (int i = 0; i < originalgarph.size(); i++) { int j = originalgarph.get(i); writer.print(cusize[j] + " "); } writer.println(); writer.println(1); if (userrequests != 1) { locationInd = randInt(0, 9); } else { locationInd = hack; } writer.println(locationInd); System.out.println(" locationInd " + String.valueOf(locationInd)); writer.println(numphotos); System.out.println(" numphotos " + String.valueOf(numphotos)); writer.println(numIDCs); System.out.println(" numIDCs " + String.valueOf(numIDCs)); writer.close(); originalgarph.clear(); try { String prg = "import sys\nprint int(sys.argv[1])+int(sys.argv[2])\n"; String pythonCmd = "/usr/bin/python " + algorithmPath + "ramd.py"; Process p = Runtime.getRuntime().exec(pythonCmd); try { Thread.sleep(2000); //1000 milliseconds is one second. } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } String fileName1 = algorithmPath + "work.alg"; File log = new File(fileName1); int filenumber = 0; String fileName2 = algorithmPath + "filenumber.alg"; Scanner numberscan = new Scanner(new File(fileName2)); if (numberscan.hasNextLine()) { filenumber = numberscan.nextInt(); } else { filenumber = 1; } numberscan.close(); ArrayList<String> photofnames = new ArrayList<String>(); ArrayList<String> argFNames = new ArrayList<String>(); for (int ll = 0; ll < argLen - 1; ll++) { photofnames.add(photosPath + args[ll] + ".bmp"); argFNames.add(args[ll]); System.out.println("Will upload " + photosPath + args[ll] + ".bmp"); } String sCurrentLine; BufferedReader br = null; br = new BufferedReader(new FileReader(fileName1)); int currLine = 0; Integer userNumber = 0; ArrayList<Integer> idcSet = new ArrayList<Integer>(); ArrayList<Integer> photonos = new ArrayList<Integer>(); int currU = 0; while ((sCurrentLine = br.readLine()) != null) { if (currLine % 3 == 0) { userNumber = Integer.parseInt(sCurrentLine); idcSet.clear(); photonos.clear(); } if (currLine % 3 == 1) { String[] idcnums = sCurrentLine.split(" "); String regions = ""; String regionsFileName = algorithmPath + "regions.alg"; PrintWriter regionwriter = new PrintWriter(regionsFileName, "UTF-8"); for (int numIdcs = 0; numIdcs < idcnums.length; numIdcs++) { idcSet.add(Integer.parseInt(idcnums[numIdcs])); if (idcnums[numIdcs].equals("1")) { regions = "region1"; regionwriter.print(regions + " "); } else if (idcnums[numIdcs].equals("2")) { regions = "region2"; regionwriter.print(regions + " "); } else if (idcnums[numIdcs].equals("3")) { regions = "region3"; regionwriter.print(regions + " "); } else if (idcnums[numIdcs].equals("4")) { regions = "region4"; regionwriter.print(regions + " "); } else if (idcnums[numIdcs].equals("5")) { regions = "region5"; regionwriter.print(regions + " "); } System.out.println("IDCs: " + idcnums[numIdcs]); } regionwriter.close(); } if (currLine % 3 == 2) { String[] idcpnums = sCurrentLine.split(" "); for (int numIdcs = 0; numIdcs < idcpnums.length; numIdcs++) { photonos.add(Integer.parseInt(idcpnums[numIdcs])); } ArrayList<String> smallestBnames = new ArrayList<String>(); ArrayList<String> bucketnames = new ArrayList<String>(); for (int tot = 0; tot < idcSet.size(); tot++) { smallestBnames.add(ob.bnames[idcSet.get(tot) - 1]); } AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider()); int currPno = 0; ArrayList<String> transferThese = new ArrayList<String>(); ArrayList<Integer> transferThesebno = new ArrayList<Integer>(); System.out.println(String.valueOf(idcpnums.length)); //upload everything to 1 bucket for (int numIdcs = 0; numIdcs < idcpnums.length; numIdcs++) { for (int numP = 0; numP < photonos.get(numIdcs); numP++) { String uploadFileName = photofnames.get(currPno); String keyName = String.valueOf(userNumber) + "_" + argFNames.get(currPno) + '_' + filenumber++ + ".bmp"; if (numIdcs > 0) { transferThese.add(keyName); transferThesebno.add(numIdcs); } try { System.out.println("Uploading " + uploadFileName + " to " + smallestBnames.get(0) + " with keyname " + keyName); File file = new File(uploadFileName); s3client.putObject(new PutObjectRequest(smallestBnames.get(0), keyName, 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()); } currPno++; } } //transfer other files System.out.println("Number of files to transfer " + String.valueOf(transferThese.size())); for (int tot = 0; tot < transferThese.size(); tot++) { String source = smallestBnames.get(0); String dest = smallestBnames.get(transferThesebno.get(tot)); String fname = transferThese.get(tot); String src = "s3://" + source + "/" + fname; String d = "s3://" + dest; String cmd = "aws s3 mv " + src + " " + d + "\n"; System.out.println("Moving " + src + " to " + d + "\n"); Process p1 = Runtime.getRuntime().exec(cmd); } currU++; if (currU >= 1) { transferThese.clear(); transferThesebno.clear(); photofnames.clear(); argFNames.clear(); smallestBnames.clear(); break; } } currLine++; } String fileNumberFilePath = algorithmPath + "filenumber.alg"; PrintWriter numberwriter = new PrintWriter(fileNumberFilePath, "UTF-8"); numberwriter.println(filenumber); numberwriter.close(); } catch (Exception e) { } } // String s = null; // Process p1 = Runtime.getRuntime().exec("ls -alrt"); // // BufferedReader stdInput = new BufferedReader(new // InputStreamReader(p1.getInputStream())); // // BufferedReader stdError = new BufferedReader(new // InputStreamReader(p1.getErrorStream())); // // // read the output from the command // System.out.println("Here is the standard output of the command:\n"); // while ((s = stdInput.readLine()) != null) { // System.out.println(s); // } }