List of usage examples for com.amazonaws AmazonServiceException getRequestId
public String getRequestId()
From source file:dataMappers.PictureDataMapper.java
public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request) throws FileUploadException, IOException, SQLException { if (!ServletFileUpload.isMultipartContent(request)) { System.out.println("Invalid upload request"); return;/* ww w .java 2s . co m*/ } // Define limits for disk item DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); // Define limit for servlet upload ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); FileItem itemFile = null; int reportID = 0; // Get list of items in request (parameters, files etc.) List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // Loop items while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { itemFile = item; // If not form field, must be item } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field try { System.out.println(item.getString()); reportID = Integer.parseInt(item.getString()); } catch (NumberFormatException e) { reportID = 0; } } } // This will be null if no fields were declared as image/upload. // Also, reportID must be > 0 if (itemFile != null || reportID == 0) { try { // Create credentials from final vars BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY); // Create client with credentials AmazonS3 s3client = new AmazonS3Client(awsCredentials); // Set region s3client.setRegion(Region.getRegion(Regions.EU_WEST_1)); // Set content length (size) of file ObjectMetadata om = new ObjectMetadata(); om.setContentLength(itemFile.getSize()); // Get extension for file String ext = FilenameUtils.getExtension(itemFile.getName()); // Generate random filename String keyName = UUID.randomUUID().toString() + '.' + ext; // This is the actual upload command s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om)); // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report. PreparedStatement stmt = dbconnector.getCon() .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)"); stmt.setInt(1, reportID); stmt.setString(2, keyName); stmt.executeUpdate(); stmt.close(); } 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:dbs.Getfroms3.java
public static void main(String[] args) throws IOException { AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.AP_SOUTH_1) .withCredentials(new AWSStaticCredentialsProvider(credentials)).build(); //AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider("inhack2hire28")); try {/* ww w.j a v a2s . c om*/ System.out.println("Downloading an object"); S3Object s3object = s3Client.getObject(new GetObjectRequest(bucketName, key)); System.out.println("Content-Type: " + s3object.getObjectMetadata().getContentType()); displayTextInputStream(s3object.getObjectContent()); // Get a range of bytes from an object. GetObjectRequest rangeObjectRequest = new GetObjectRequest(bucketName, key); rangeObjectRequest.setRange(0, 10); S3Object objectPortion = s3Client.getObject(rangeObjectRequest); System.out.println("Printing bytes retrieved."); displayTextInputStream(objectPortion.getObjectContent()); } 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:de.fischer.thotti.ec2.clients.EC2InternalClient.java
License:Apache License
/** * Handles an {@link AmazonServiceException} by logging the information * provided by Amazon AWS and turning the caught exception into * an {@link de.fischer.thotti.awscommon.AWSRemoteServiceException}. *///from w w w .j a v a 2s. com protected void handleAmazonServiceException(AmazonServiceException exception) throws AWSRemoteServiceException { if (logger.isErrorEnabled()) { String message = exception.getMessage(); String code = exception.getErrorCode(); AmazonServiceException.ErrorType type = exception.getErrorType(); String requestId = exception.getRequestId(); String service = exception.getServiceName(); logger.error("Amazon AWS was not able to fullfil the last operation. " + "Error message = {}, error code = {}, error type = {}, " + "service = {}, requestID = {}", new Object[] { message, code, type, requestId, service }); } throw new AWSRemoteServiceException(exception.getMessage()); }
From source file:DynamicProvisioning.Requests.java
License:Open Source License
public String waitUntilActiveandRunning(String request) throws InterruptedException { boolean isActive = false; boolean isRunning = false; List<Reservation> reservation = new ArrayList<Reservation>(); List<Instance> ins = new ArrayList<Instance>(); String instanceid = null;/* ww w. j a va 2s . c om*/ String ipaddress = null; while (!isActive) { DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest(); describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds); try { // Retrieve all of the requests we want to monitor. DescribeSpotInstanceRequestsResult describeResult = ec2 .describeSpotInstanceRequests(describeRequest); List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests(); for (SpotInstanceRequest describeResponse : describeResponses) { if (describeResponse.getSpotInstanceRequestId().equalsIgnoreCase(request)) { if (describeResponse.getState().equals("active")) { System.out.println(describeResponse.getSpotInstanceRequestId() + " is active"); isActive = true; instanceid = describeResponse.getInstanceId(); DescribeInstancesRequest req = new DescribeInstancesRequest() .withInstanceIds(instanceid); DescribeInstancesResult k = ec2.describeInstances(req); reservation = k.getReservations(); for (Reservation i : reservation) { ins = i.getInstances(); for (Instance in : ins) { if ((in.getInstanceId()).equals(instanceid)) { ipaddress = in.getPublicIpAddress(); while (ipaddress == null) { Thread.currentThread().sleep(1000); ipaddress = in.getPublicIpAddress(); } } } } } } else { Thread.currentThread().sleep(1000); } } } catch (AmazonServiceException e) { // Print out the error. System.out.println("Error when calling describeSpotInstances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); // If we have an exception, ensure we don't break out of the loop. // This prevents the scenario where there was blip on the wire. } } return ipaddress; }
From source file:ecplugins.s3.S3Util.java
License:Apache License
public static void UploadObject(String bucketName, String key) throws AmazonClientException, AmazonServiceException, Exception { Properties props = TestUtils.getProperties(); File file = new File(createFile()); BasicAWSCredentials credentials = new BasicAWSCredentials(props.getProperty(StringConstants.ACCESS_ID), props.getProperty(StringConstants.SECRET_ACCESS_ID)); // Create TransferManager TransferManager tx = new TransferManager(credentials); // Get S3 Client AmazonS3 s3 = tx.getAmazonS3Client(); try {/*from w w w . j a v a 2 s. c o m*/ System.out.println("Uploading a new object to S3 from a file\n"); s3.putObject(new PutObjectRequest(bucketName, key, file)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException"); 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 such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:edu.columbia.cc.elPonePeli.app.LiveStreamingHelper.java
public void createFormation(String stackName, String logicalResourceName) { try {/*from w w w. jav a 2 s . c o m*/ // Create a stack Collection<Parameter> params = new ArrayList<Parameter>(); Parameter pInstanceType = new Parameter().withParameterKey("InstanceType") .withParameterValue("m1.small"); params.add(pInstanceType); Parameter pKeyPair = new Parameter().withParameterKey("KeyPair").withParameterValue("fbtest"); params.add(pKeyPair); Parameter pLicKey = new Parameter().withParameterKey("WowzaLicenseKey") .withParameterValue("SVRT3-HEKkZ-zRp6C-xPTA7-b4a8P-VwR9R-7U6W7f6TXXxt"); params.add(pLicKey); CreateStackRequest createRequest = new CreateStackRequest().withTemplateURL(streamingTemplateURL) .withStackName(streamingStackName).withParameters(params); System.out.println("Creating a stack called " + createRequest.getStackName() + "."); stackbuilder.createStack(createRequest); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS CloudFormation, 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 CloudFormation, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:edu.harvard.hms.dbmi.bd2k.irct.aws.event.result.S3AfterGetResult.java
License:Mozilla Public License
@Override public void fire(Result result) { if (result.getResultStatus() != ResultStatus.AVAILABLE) { return;/*from w ww . ja va 2 s . c om*/ } if (!result.getResultSetLocation().startsWith("S3://")) { File temp = new File(result.getResultSetLocation()); if (temp.exists()) { return; } else { result.setResultSetLocation( "S3://" + s3Folder + result.getResultSetLocation().replaceAll(irctSaveLocation + "/", "")); } } String location = result.getResultSetLocation().substring(5); // List the files in that bucket path try { final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName) .withPrefix(location); // Loop Through all the files ListObjectsV2Result s3Files; do { s3Files = s3client.listObjectsV2(req); for (S3ObjectSummary objectSummary : s3Files.getObjectSummaries()) { // Download the files to the directory specified String keyName = objectSummary.getKey(); String fileName = irctSaveLocation + keyName.replace(location, ""); log.info("Downloading: " + keyName + " --> " + fileName); s3client.getObject(new GetObjectRequest(bucketName, keyName), new File(fileName)); } req.setContinuationToken(s3Files.getNextContinuationToken()); } while (s3Files.isTruncated() == true); // Update the result set id result.setResultSetLocation(irctSaveLocation + "/" + location.replace(s3Folder, "")); } catch (AmazonServiceException ase) { log.warn("Caught an AmazonServiceException, which " + "means your request made it " + "to Amazon S3, but was rejected with an error response" + " for some reason."); log.warn("Error Message: " + ase.getMessage()); log.warn("HTTP Status Code: " + ase.getStatusCode()); log.warn("AWS Error Code: " + ase.getErrorCode()); log.warn("Error Type: " + ase.getErrorType()); log.warn("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { log.warn("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."); log.warn("Error Message: " + ace.getMessage()); } }
From source file:edu.harvard.hms.dbmi.bd2k.irct.aws.event.result.S3AfterSaveResult.java
License:Mozilla Public License
@Override public void fire(SecureSession session, Executable executable) { try {/*from www . j a va2 s . c o m*/ if (executable.getStatus() != ExecutableStatus.COMPLETED) { return; } Result result = executable.getResults(); for (File resultFile : result.getData().getFileList()) { String keyName = s3Folder + result.getId() + "/" + resultFile.getName(); // Copy the result into S3 if bucketName is not empty or null s3client.putObject(new PutObjectRequest(bucketName, keyName, resultFile)); log.info("Moved " + result.getResultSetLocation() + " to " + bucketName + "/" + keyName); // Delete File resultFile.delete(); log.info("Deleted " + resultFile.getName()); } result.setResultSetLocation("S3://" + s3Folder + result.getId()); } catch (AmazonServiceException ase) { log.warn("Caught an AmazonServiceException, which " + "means your request made it " + "to Amazon S3, but was rejected with an error response" + " for some reason."); log.warn("Error Message: " + ase.getMessage()); log.warn("HTTP Status Code: " + ase.getStatusCode()); log.warn("AWS Error Code: " + ase.getErrorCode()); log.warn("Error Type: " + ase.getErrorType()); log.warn("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { log.warn("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."); log.warn("Error Message: " + ace.getMessage()); } catch (ResourceInterfaceException e) { log.warn("Error Message: " + e.getMessage()); } }
From source file:edu.umass.cs.aws.support.AWSEC2.java
License:Apache License
/** * Creates an EC2 instance in the region given. Timeout in milleseconds can be specified. * * @param ec2/*from ww w .j av a 2 s .c om*/ * @param region * @param amiRecord * @param instanceName * @param keyName * @param securityGroupName * @param script * @param tags * @param elasticIP * @param timeout * @return a new instance instance */ public static Instance createAndInitInstance(AmazonEC2 ec2, RegionRecord region, AMIRecord amiRecord, String instanceName, String keyName, String securityGroupName, String script, Map<String, String> tags, String elasticIP, int timeout) { try { // set the region (AKA endpoint) setRegion(ec2, region); // create the instance SecurityGroup securityGroup = findOrCreateSecurityGroup(ec2, securityGroupName); String keyPair = findOrCreateKeyPair(ec2, keyName); String instanceID = createInstanceAndWait(ec2, amiRecord, keyPair, securityGroup); if (instanceID == null) { return null; } System.out.println("Instance " + instanceName + " is running in " + region.name()); // add a name to the instance addInstanceTag(ec2, instanceID, "Name", instanceName); if (tags != null) { addInstanceTags(ec2, instanceID, tags); } Instance instance = findInstance(ec2, instanceID); if (instance == null) { return null; } String hostname = instance.getPublicDnsName(); System.out.println("Waiting " + timeout / 1000 + " seconds for " + instanceName + " (" + hostname + ", " + instanceID + ") to be reachable."); long startTime = System.currentTimeMillis(); while (!Pinger.isReachable(hostname, SSHPORT, 2000)) { ThreadUtils.sleep(1000); System.out.print("."); if (System.currentTimeMillis() - startTime > timeout) { System.out.println( instanceName + " (" + hostname + ")" + " timed out during reachability check."); return null; } } System.out.println(); System.out.println(instanceName + " (" + hostname + ")" + " is reachable."); // associate the elasticIP if one is provided if (elasticIP != null) { System.out.println( "Using ElasticIP " + elasticIP + " for instance " + instanceName + " (" + instanceID + ")"); AWSEC2.associateAddress(ec2, elasticIP, instance); // get a new copy cuz things have changed instance = findInstance(ec2, instanceID); if (instance == null) { return null; } // recheck reachability hostname = instance.getPublicDnsName(); System.out.println("Waiting " + timeout / 1000 + " s for " + instanceName + " (" + hostname + ", " + instanceID + ") to be reachable after Elastic IP change."); startTime = System.currentTimeMillis(); while (!Pinger.isReachable(hostname, SSHPORT, 2000)) { ThreadUtils.sleep(1000); System.out.print("."); if (System.currentTimeMillis() - startTime > timeout) {// give it a minute and ahalf System.out.println(instanceName + " (" + hostname + ")" + " timed out during second (elastic IP) reachability check."); return null; } } System.out.println(); System.out.println(instanceName + " (" + hostname + ")" + " is still reachable."); } if (script != null) { File keyFile = new File(KEYHOME + FILESEPARATOR + keyName + PRIVATEKEYFILEEXTENSION); ExecuteBash.executeBashScript("ec2-user", hostname, keyFile, true, "installScript.sh", script); } return instance; } 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()); } return null; }
From source file:edu.umass.cs.aws.support.examples.AWSStatusCheck.java
License:Apache License
/** * * @param args/*from w w w. ja v a 2 s . co m*/ * @throws Exception */ public static void main(String[] args) throws Exception { init(); /* * Amazon EC2 */ for (String endpoint : endpoints) { try { ec2.setEndpoint(endpoint); System.out.println("**** Endpoint: " + endpoint); DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones(); System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() + " Availability Zones."); for (AvailabilityZone zone : availabilityZonesResult.getAvailabilityZones()) { System.out.println(zone.getZoneName()); } DescribeInstancesResult describeInstancesRequest = ec2.describeInstances(); List<Reservation> reservations = describeInstancesRequest.getReservations(); Set<Instance> instances = new HashSet<Instance>(); System.out.println("Instances: "); for (Reservation reservation : reservations) { for (Instance instance : reservation.getInstances()) { instances.add(instance); System.out.println(instance.getPublicDnsName() + " is " + instance.getState().getName()); } } System.out.println("Security groups: "); DescribeSecurityGroupsResult describeSecurityGroupsResult = ec2.describeSecurityGroups(); for (SecurityGroup securityGroup : describeSecurityGroupsResult.getSecurityGroups()) { System.out.println(securityGroup.getGroupName()); } //System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running."); } 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()); } /* * Amazon SimpleDB * */ try { ListDomainsRequest sdbRequest = new ListDomainsRequest().withMaxNumberOfDomains(100); ListDomainsResult sdbResult = sdb.listDomains(sdbRequest); int totalItems = 0; for (String domainName : sdbResult.getDomainNames()) { DomainMetadataRequest metadataRequest = new DomainMetadataRequest().withDomainName(domainName); DomainMetadataResult domainMetadata = sdb.domainMetadata(metadataRequest); totalItems += domainMetadata.getItemCount(); } System.out.println("You have " + sdbResult.getDomainNames().size() + " Amazon SimpleDB domain(s)" + "containing a total of " + totalItems + " items."); } 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()); } /* * Amazon S3 *. */ try { List<Bucket> buckets = s3.listBuckets(); long totalSize = 0; int totalItems = 0; for (Bucket bucket : buckets) { /* * In order to save bandwidth, an S3 object listing does not * contain every object in the bucket; after a certain point the * S3ObjectListing is truncated, and further pages must be * obtained with the AmazonS3Client.listNextBatchOfObjects() * method. */ ObjectListing objects = s3.listObjects(bucket.getName()); do { for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) { totalSize += objectSummary.getSize(); totalItems++; } objects = s3.listNextBatchOfObjects(objects); } while (objects.isTruncated()); } System.out.println("You have " + buckets.size() + " Amazon S3 bucket(s), " + "containing " + totalItems + " objects with a total size of " + totalSize + " bytes."); } catch (AmazonServiceException ase) { /* * AmazonServiceExceptions represent an error response from an AWS * services, i.e. your request made it to AWS, but the AWS service * either found it invalid or encountered an error trying to execute * it. */ 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) { /* * AmazonClientExceptions represent an error that occurred inside * the client on the local host, either while trying to send the * request to AWS or interpret the response. For example, if no * network connection is available, the client won't be able to * connect to AWS to execute a request and will throw an * AmazonClientException. */ System.out.println("Error Message: " + ace.getMessage()); } } }