List of usage examples for com.amazonaws.auth PropertiesCredentials PropertiesCredentials
public PropertiesCredentials(InputStream inputStream) throws IOException
From source file:ClienTopTen.java
License:Open Source License
/** * The only information needed to create a client are security credentials * consisting of the AWS Access Key ID and Secret Access Key. All other * configuration, such as the service endpoints, are performed * automatically. Client parameters, such as proxies, can be specified in an * optional ClientConfiguration object when constructing a client. * //from w ww . ja v a 2s . c o m * @see com.amazonaws.auth.BasicAWSCredentials * @see com.amazonaws.auth.PropertiesCredentials * @see com.amazonaws.ClientConfiguration */ private static void init() throws Exception { AWSCredentials credentials = new PropertiesCredentials( ClienTopTen.class.getResourceAsStream("AwsCredentials.properties")); ec2 = new AmazonEC2Client(credentials); // s3 = new AmazonS3Client(credentials); // sdb = new AmazonSimpleDBClient(credentials); }
From source file:S3Sample.java
License:Open Source License
public static void main(String[] args) throws IOException { // s3/* w ww .j av a 2 s . c o m*/ String imageBucketName = "ringtone_image"; String ringBucketName = "ringtone_ring"; AmazonS3 s3 = new AmazonS3Client( new PropertiesCredentials(S3Sample.class.getResourceAsStream("AwsCredentials.properties"))); String bucketName; System.out.println("Start Sending Files To Amazon S3"); // directory and files String pathName = "/home/liutao/workspace/python/1-fetch/download_Holiday/"; File dir = new File(pathName); File list[] = dir.listFiles(); String fileName; // sort by record index Arrays.sort(list, new Comparator<File>() { public int compare(File f1, File f2) { String s1 = f1.getName(); String s2 = f2.getName(); int idx1 = s1.indexOf(".xml"); int idx2 = s2.indexOf(".xml"); if (idx1 != -1 && idx2 != -1) { int num1 = Integer.parseInt(s1.substring(s1.indexOf('d') + 1, idx1)); int num2 = Integer.parseInt(s2.substring(s2.indexOf('d') + 1, idx2)); return num1 - num2; } else if (idx1 == -1) return -1; else return 1; } }); // xml parser DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); InputStream in; // String uuid; String key; URL url; int i = 0, j; try { DocumentBuilder docBuilder = factory.newDocumentBuilder(); FileWriter log = new FileWriter(pathName + "log"); while (i < list.length) { if (list[i].getName().endsWith(".xml")) break; i++; } // start process xml file for (; i < list.length; i++) { System.out.println(list[i].getName()); log.write(list[i].getName() + ","); try { in = new FileInputStream(pathName + list[i].getName()); Document doc = docBuilder.parse(in); org.w3c.dom.Element root = doc.getDocumentElement(); //System.out.println(root.getNodeName()); NodeList childen = root.getChildNodes(); org.w3c.dom.Node curNode, node; uuid = UUID.randomUUID().toString(); for (j = 0; j < childen.getLength(); j++) { curNode = childen.item(j); if (curNode.getNodeType() == Node.ELEMENT_NODE) if (curNode.getNodeName().equals("Ring") || curNode.getNodeName().equals("Image")) { //System.out.println(curNode.getFirstChild().getNodeValue()); fileName = curNode.getFirstChild().getNodeValue(); File file = new File(pathName + fileName); if (!file.exists()) { log.write(fileName + " not Found!\n"); break; } key = uuid + fileName; //bucketName = curNode.getNodeName().equals("Ring")?ringBucketName:imageBucketName; bucketName = "ringtone_test_2010"; try { s3.putObject(new PutObjectRequest(bucketName, key, file)); // s3.setObjectAcl(bucketName, key, CannedAccessControlList.PublicRead); // ?? // url = s3.generatePresignedUrl(bucketName, key, expireDate); // System.out.println(url); } catch (AmazonServiceException ase) { log.write("AmazonServiceException\n"); } catch (AmazonClientException ace) { log.write("AmazonClientException\n"); } } } if (j == childen.getLength()) {// if success, record it log.write("uuid:" + uuid + "\n"); } } catch (FileNotFoundException e) { log.write("FileNotFound\n"); } catch (SAXException e) { log.write("xml parse error\n"); } catch (IOException e) { log.write("IOexception\n"); } } log.flush(); log.close(); } catch (ParserConfigurationException e) { e.printStackTrace(); } System.out.println("Sending Finished!"); }
From source file:S3Sample.java
License:Open Source License
public static void main2(String[] args) throws IOException { /*//from www .ja va 2 s . co m * 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 PropertiesCredentials(S3Sample.class.getResourceAsStream("AwsCredentials.properties"))); //String bucketName = "my-first-s3-bucket-" + UUID.randomUUID(); String bucketName = "ringtone_image"; String key = "test"; System.out.println("being..."); System.out.println("size:"); System.out.println("end.\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() + ")"); } */ /* * 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:AWSJavaMailSample.java
License:Open Source License
public static void main(String[] args) throws IOException { /*//from w ww. ja v a2 s . c om * 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 */ PropertiesCredentials credentials = new PropertiesCredentials( AWSJavaMailSample.class.getResourceAsStream("AwsCredentials.properties")); AmazonSimpleEmailService ses = new AmazonSimpleEmailServiceClient(credentials); /* * Before you can send email via Amazon SES, you need to verify that you * own the email address from which youll be sending email. This will * trigger a verification email, which will contain a link that you can * click on to complete the verification process. */ verifyEmailAddress(ses, FROM); /* * If you've just signed up for SES, then you'll be placed in the Amazon * SES sandbox, where you must also verify the email addresses you want * to send mail to. * * You can uncomment the line below to verify the TO address in this * sample. * * Once you have full access to Amazon SES, you will *not* be required * to verify each email address you want to send mail to. * * You can request full access to Amazon SES here: * http://aws.amazon.com/ses/fullaccessrequest */ //verifyEmailAddress(ses, TO); /* * Setup JavaMail to use the Amazon Simple Email Service by specifying * the "aws" protocol. */ Properties props = new Properties(); props.setProperty("mail.transport.protocol", "aws"); /* * Setting mail.aws.user and mail.aws.password are optional. Setting * these will allow you to send mail using the static transport send() * convince method. It will also allow you to call connect() with no * parameters. Otherwise, a user name and password must be specified * in connect. */ props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId()); props.setProperty("mail.aws.password", credentials.getAWSSecretKey()); Session session = Session.getInstance(props); try { // Create a new Message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(FROM)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(TO)); msg.setSubject(SUBJECT); msg.setText(BODY); msg.saveChanges(); // Reuse one Transport object for sending all your messages // for better performance Transport t = new AWSJavaMailTransport(session, null); t.connect(); t.sendMessage(msg, null); // Close your transport when you're completely done sending // all your messages t.close(); } catch (AddressException e) { e.printStackTrace(); System.out.println("Caught an AddressException, which means one or more of your " + "addresses are improperly formatted."); } catch (MessagingException e) { e.printStackTrace(); System.out.println("Caught a MessagingException, which means that there was a " + "problem sending your message to Amazon's E-mail Service check the " + "stack trace for more information."); } }
From source file:Conductor.java
License:Open Source License
/** * Initialization of program "connect to DB, load configurations, connect to Amazon, run minimum encode servers we need etc". *///from ww w .java 2s . c o m private static void init() { /********************************************************************** ***************************** EC2 INITIALS *************************** **********************************************************************/ try { // System.out.println("Working Directory = " + System.getProperty("user.dir")); /********************************************************************* * ******************************************************************* * Loading Program config information. * ******************************************************************* *********************************************************************/ DefaultSettingsPath = System.getProperty("user.dir") + "/settings/"; config = new Properties(); config.load(new FileInputStream(DefaultSettingsPath + "conductor_initial_config.properties")); System.out.println("Program config info loaded: Ok."); //debugModeEnable = Boolean.parseBoolean(config.getProperty("DebugModeEnable")); DebugMessage = new Debuger(Boolean.parseBoolean(config.getProperty("DebugModeEnable"))); /********************************************************************** *********************** JERSEY SERVER INITIALS ********************************** **********************************************************************/ Authentication.getInstance().setAuthenticationInitials(config.getProperty("AdminUserName"), config.getProperty("AdminPassword"), config.getProperty("AdminSessionValidTimeInMinut")); UriRestServer = config.getProperty("UriRestServer"); System.out.println(UriRestServer); server = HttpServerFactory.create(UriRestServer); server.start(); DebugMessage.ShowInfo("Http Server started: Ok.", true); boolean blNeedSoftBoot = checkForSoftBoot(); /*##################################*/ blNeedSoftBoot = true; /********************************************************************** *********************** DB INITIALS ********************************* **********************************************************************/ if (!SQL.connect( config.getProperty("PostgraSQLServerAddress") + ":" + config.getProperty("PostgraSQLServerPort") + "/", config.getProperty("PostgraSQLUserName"), config.getProperty("PostgraSQLPassWord"), config.getProperty("MySqlDataBase"))) { throw new Exception(Constants._ERR_DBAccessError); } if (!blNeedSoftBoot) { SQL.query("DROP TABLE IF EXISTS " + config.getProperty("TableUploadSessions") + ", " + config.getProperty("TableInstanceServers")); SQL.query(config.getProperty("CreatTableUploadSessions")); SQL.query(config.getProperty("CreatTableInstanceServers")); DebugMessage.ShowInfo("Connect to db: Ok.", true); } //AWSCredentials credentials = new PropertiesCredentials(Conductor.class.getResourceAsStream("settings/"+ "AwsCredentials.properties")); AWSCredentials credentials = new PropertiesCredentials( Conductor.class.getResourceAsStream("AwsCredentials.properties")); ec2 = new AmazonEC2Client(credentials); // / Check available zones. if (GetCurrentAvailableZones().getAvailabilityZones().size() > 0) { DebugMessage.ShowInfo("Available zones access: Ok.", true); DebugMessage.ShowInfo( "Number of zones: " + GetCurrentAvailableZones().getAvailabilityZones().size(), true); int countAvailableZones = 0; for (int i = 0; i < GetCurrentAvailableZones().getAvailabilityZones().size(); i++) { //countAvailableZones DebugMessage.ShowInfo( "Zone " + "1: " + GetCurrentAvailableZones().getAvailabilityZones().get(i), true); // I do not know this algorithm is correct or not (lack of fucking AWS documents!) if (GetCurrentAvailableZones().getAvailabilityZones().get(i).getRegionName() .contains(config.getProperty("StringEndPointRegion"))) { if (GetCurrentAvailableZones().getAvailabilityZones().get(i).getState() .contentEquals("available")) { countAvailableZones++; } } } if (countAvailableZones != GetCurrentAvailableZones().getAvailabilityZones().size()) throw new Exception(Constants._ERR_CannotAccessZones); // Get number of running instances. int numberofrunninginstance = getNumberofInstances(0); DebugMessage.ShowInfo("You have " + numberofrunninginstance + " Amazon EC2 instance(s) running.", true); System.out.println("==========================================="); ec2.setEndpoint(config.getProperty("SetEndPointName")); System.out.println(getProcessJobsStatistic("UnderProcess")); System.out.println(getProcessJobsStatistic("Finished")); System.out.println(getProcessJobsStatistic("Waiting")); System.out.println(getProcessJobsStatistic("Unsuccess")); System.out.println(getProcessJobsStatistic("WaitingAndUnderProcess")); //System.in.read(); server.stop(0); System.exit(0); /* * There is not server ready or number of them is not * enough for initialization of system. So run some. */ if ((numberofrunninginstance < Integer.parseInt(config.getProperty("MinimumEssentialTiers"))) && (blNeedSoftBoot != false)) { /* * Calculating number of servers needed to be run as minimum * number transcoders in the initialization. */ int _numOfSrvNeedToRun = Integer.parseInt(config.getProperty("MinimumEssentialTiers")) - numberofrunninginstance; DebugMessage.ShowInfo("Number of needed transcoder instancess to run for initial stage: " + _numOfSrvNeedToRun, true); // CREATE EC2 INSTANCES RunInstancesRequest runInstancesRequest = new RunInstancesRequest() .withInstanceType(config.getProperty("InstanceType")) .withImageId(config.getProperty("InstanceAmiToRun")).withMinCount(_numOfSrvNeedToRun) .withMaxCount(_numOfSrvNeedToRun).withMonitoring(false) .withKeyName(config.getProperty("InstanceAmiToRunSecurityKey")) .withSecurityGroupIds(config.getProperty("InstanceAmiSecurityGroup")); RunInstancesResult runInstances = ec2.runInstances(runInstancesRequest); /* * Now waiting for 120s to servers to be run. Except after * timeout something is wrong. */ int counter = 0; boolean isRunning = true; int i; System.out.println("==========================================="); while (isRunning) // the loop { i = waitInitialInstancesTobeReady(); System.out.print("Number of current running servers in the waiting loop: " + i); // waits until all the servers be in running state. if (i == Integer.parseInt(config.getProperty("MinimumEssentialTiers"))) { System.out.println(""); System.out.println("Minimum transcoding servers added and finished. Continue ...."); isRunning = false; break; } counter++; // 24*5000 = 120 Second if (counter == Integer.parseInt(config.getProperty("TimeWaitInstanceBeOprational"))) { isRunning = false; throw new Exception(Constants._ERR_CannotRunInstance); } DebugMessage.ShowInfo("\r" + (counter * Integer.parseInt(config.getProperty("TickTimeTierBeReady"))) / 1000 + " second... ", true); Thread.sleep(Integer.parseInt(config.getProperty("TickTimeTierBeReady"))); // the timing mechanism } } else { DebugMessage.ShowInfo("No need to add any instance in initialization. Continue ....", true); } /* * Put recently added transcoding servers in the database as * pool of current available servers. */ //if (!LogTheServersInTheDB(0)) // throw new Exception(Constants._ERR_DBAccessError); } else { throw new Exception(Constants._ERR_CannotAccessZones); } } catch (Exception e) { e.printStackTrace(); String reflectErr; switch (e.getMessage()) { case Constants._ERR_CannotAccessZones: reflectErr = DebugMessage.ShowErrors("init()", e.getMessage(), "Can not access any available zone", true); Log_Report(reflectErr); System.exit(1); break; case Constants._ERR_DBAccessError: System.out.println("-> Err Critical: Can not connect to db error."); reflectErr = DebugMessage.ShowErrors("init()", e.getMessage(), "Can not connect to db error", true); Log_Report(reflectErr); System.exit(1); break; case Constants._ERR_CannotRunInstance: reflectErr = DebugMessage.ShowErrors("init()", e.getMessage(), "Can not run instaces.", true); Log_Report(reflectErr); System.exit(1); /* sendemail( config.getProperty("EmailSenderUsername"), config.getProperty("EmailSenderPassword"), config.getProperty("EmailSender"), config.getProperty("EmailRecipient"), "Conductor Can not run instaces in initial stage!", "Error High Critical:\nCan not run instaces in initial stage! In init function.");*/ break; default: reflectErr = DebugMessage.ShowErrors("init()", e.getMessage(), "Uncategorized error", true); Log_Report(reflectErr); System.exit(1); break; } } }
From source file:SimpleDBPerformanceSample.java
License:Apache License
public static void main(String[] args) throws Exception { AmazonSimpleDB sdb = new AmazonSimpleDBClient( new PropertiesCredentials(SimpleDBSample.class.getResourceAsStream("AwsCredentials.properties"))); // ?[WGh|Cgw//from w w w . jav a 2 s . c o m sdb.setEndpoint(args[0]); int roopCount = 100; long insertTimeSum = 0; long selectTimeSum = 0; long updateTimeSum = 0; long deleteTimeSum = 0; long startTime; long finishedTime; try { // h?C?? String myDomain = "MyStore"; sdb.createDomain(new CreateDomainRequest(myDomain)); for (int i = 0; i < roopCount; i++) { // ?f?[^ sdb.batchPutAttributes(new BatchPutAttributesRequest(myDomain, createSampleData())); // f?[^1?}(PutAttributes API) ReplaceableItem rItem = new ReplaceableItem("Item_06").withAttributes( new ReplaceableAttribute("Category", "Car Parts", true), new ReplaceableAttribute("Subcategory", "Exhaust", true), new ReplaceableAttribute("Name", "O2 Sensor", true), new ReplaceableAttribute("Make", "Audi", true), new ReplaceableAttribute("Model", "TT Coupe", true), new ReplaceableAttribute("Year", "2009", true), new ReplaceableAttribute("Year", "2010", true), new ReplaceableAttribute("Year", "2011", true)); PutAttributesRequest putAttributesRequest = new PutAttributesRequest(myDomain, rItem.getName(), rItem.getAttributes()); startTime = System.currentTimeMillis(); sdb.putAttributes(putAttributesRequest); finishedTime = System.currentTimeMillis(); insertTimeSum += finishedTime - startTime; // f?[^?iSelect API) String selectExpression = "select * from `" + myDomain + "` where Category = 'Clothes'"; SelectRequest selectRequest = new SelectRequest(selectExpression); startTime = System.currentTimeMillis(); sdb.select(selectRequest); finishedTime = System.currentTimeMillis(); selectTimeSum += finishedTime - startTime; // f?[^?X?V(PutAttributes API) List<ReplaceableAttribute> replaceableAttributes = new ArrayList<ReplaceableAttribute>(); replaceableAttributes.add(new ReplaceableAttribute("Size", "Medium", true)); startTime = System.currentTimeMillis(); sdb.putAttributes(new PutAttributesRequest(myDomain, "Item_03", replaceableAttributes)); finishedTime = System.currentTimeMillis(); updateTimeSum += finishedTime - startTime; // f?[^??(DeleteAttributes API) startTime = System.currentTimeMillis(); sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03")); finishedTime = System.currentTimeMillis(); deleteTimeSum += finishedTime - startTime; // f?[^?? sdb.batchDeleteAttributes(new BatchDeleteAttributesRequest(myDomain, deleteSampleData())); } // h?C?? sdb.deleteDomain(new DeleteDomainRequest(myDomain)); System.out.println("insert:AVG:" + (float) insertTimeSum / roopCount); System.out.println("select:AVG:" + (float) selectTimeSum / roopCount); System.out.println("update:AVG:" + (float) updateTimeSum / roopCount); System.out.println("delete:AVG:" + (float) deleteTimeSum / roopCount); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon SimpleDB, 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 SimpleDB, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:BackupManager.java
License:Open Source License
public static void main(String[] args) throws IOException { AmazonS3 s3 = new AmazonS3Client( new PropertiesCredentials(BackupManager.class.getResourceAsStream("AwsCredentials.properties"))); 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 {// w w w . j a va 2 s. com /* * 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:SNSMobilePush.java
License:Open Source License
public static void main(String[] args) throws IOException { /*//from w w w. ja va 2s . c o m * TODO: 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 */ AmazonSNS sns = new AmazonSNSClient( new PropertiesCredentials(SNSMobilePush.class.getResourceAsStream("AwsCredentials.properties"))); sns.setEndpoint("https://sns.us-east-1.amazonaws.com"); System.out.println("===========================================\n"); System.out.println("Getting Started with Amazon SNS"); System.out.println("===========================================\n"); try { SNSMobilePush sample = new SNSMobilePush(sns); /* TODO: Uncomment the services you wish to use. */ sample.demoAndroidAppNotification(); // sample.demoKindleAppNotification(); // sample.demoAppleAppNotification(); // sample.demoAppleSandboxAppNotification(); // sample.demoBaiduAppNotification(); // sample.demoWNSAppNotification(); // sample.demoMPNSAppNotification(); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon SNS, 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 SNS, such as not " + "being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:PutTestFile.java
License:Apache License
public static void main(String[] args) throws IOException { /*// ww w . j a v a 2 s . c o m * 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 PropertiesCredentials( PutTestFile.class.getResourceAsStream("AwsCredentials.properties"))); String bucketName = "dtccTest"; String key = "largerfile.txt"; System.out.println("==========================================="); System.out.println("Getting Started with Amazon S3"); System.out.println("===========================================\n"); try { /* * List the buckets in your account */ System.out.println("Listing buckets"); for (Bucket bucket : s3.listBuckets()) { System.out.println(" - " + bucket.getName()); } System.out.println(); System.out.println("Uploading a new object to S3 from a file\n"); PutObjectRequest request = new PutObjectRequest(bucketName, key, createSampleFile()); request.setCannedAcl(CannedAccessControlList.PublicRead); s3.putObject(request); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, whichmeans your request made it " + "to Amazon S3, but was rejected with an errorresponse 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, whichmeans the client encountered " + "a serious internal problem while trying tocommunicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:EBS_S3.java
License:Open Source License
public static void main(String[] args) throws Exception { AWSCredentials credentials = new PropertiesCredentials( EBS_S3.class.getResourceAsStream("AwsCredentials.properties")); /********************************************* * #1 Create Amazon Client object/*from w ww.jav a2s . com*/ **********************************************/ ec2 = new AmazonEC2Client(credentials); // We assume that we've already created an instance. Use the id of the instance. String instanceId = "i-278afe40"; //put your own instance id to test this code. try { /********************************************* * #2.1 Create a volume *********************************************/ // release System.out.println(ec2.describeVolumes()); List<Volume> v_list = ec2.describeVolumes().getVolumes(); System.out.println("Volume size: " + v_list.size()); DeleteVolumeRequest rq; for (Volume v : v_list) { if (v.getVolumeId().compareTo("vol-343dd879") != 0) { rq = new DeleteVolumeRequest(v.getVolumeId()); ec2.deleteVolume(rq); } } System.out.println(ec2.describeVolumes()); System.out.println("Volume size: " + v_list.size()); //create a volume System.out.println("2.1 Create a volume"); CreateVolumeRequest cvr = new CreateVolumeRequest(); cvr.setAvailabilityZone("us-east-1b"); cvr.setSize(10); //size = 10 gigabytes CreateVolumeResult volumeResult = ec2.createVolume(cvr); String createdVolumeId = volumeResult.getVolume().getVolumeId(); System.out.println("Created Volume ID: " + createdVolumeId); /********************************************* * #2.2 Attach the volume to the instance *********************************************/ System.out.println("2.2 Attach the volume to the instance"); Thread.sleep(30000); AttachVolumeRequest avr = new AttachVolumeRequest(); avr.setVolumeId(createdVolumeId); avr.setInstanceId(instanceId); avr.setDevice("/dev/sdf"); ec2.attachVolume(avr); /********************************************* * #2.3 Detach the volume from the instance *********************************************/ System.out.println("2.3 Detach the volume from the instance"); DetachVolumeRequest dvr = new DetachVolumeRequest(); dvr.setVolumeId(createdVolumeId); dvr.setInstanceId(instanceId); ec2.detachVolume(dvr); /************************************************ * #3 S3 bucket and object ***************************************************/ System.out.println("3 S3 bucket and object"); s3 = new AmazonS3Client(credentials); //create bucket String bucketName = "cloud-xiangyao-bucket"; s3.createBucket(bucketName); //set key String key = "object-name.txt"; //set value File file = File.createTempFile("temp", ".txt"); file.deleteOnExit(); Writer writer = new OutputStreamWriter(new FileOutputStream(file)); writer.write("This is a sample sentence.\r\nYes!"); writer.close(); //put object - bucket, key, value(file) s3.putObject(new PutObjectRequest(bucketName, key, file)); //get object S3Object object = s3.getObject(new GetObjectRequest(bucketName, key)); BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent())); String data = null; while ((data = reader.readLine()) != null) { System.out.println(data); } /********************************************* * #4 shutdown client object *********************************************/ System.out.println("4 shutdown client object"); ec2.shutdown(); s3.shutdown(); } catch (AmazonServiceException ase) { System.out.println("Caught Exception: " + ase.getMessage()); System.out.println("Reponse Status Code: " + ase.getStatusCode()); System.out.println("Error Code: " + ase.getErrorCode()); System.out.println("Request ID: " + ase.getRequestId()); } }