Example usage for com.amazonaws AmazonServiceException getMessage

List of usage examples for com.amazonaws AmazonServiceException getMessage

Introduction

In this page you can find the example usage for com.amazonaws AmazonServiceException getMessage.

Prototype

@Override
    public String getMessage() 

Source Link

Usage

From source file:com.maya.portAuthority.util.ImageUploader.java

public static void uploadImage(String imageURL, String imageName, String bucketName)
         throws MalformedURLException, IOException {
     // credentials object identifying user for authentication

     AWSCredentials credentials = new BasicAWSCredentials("AKIAJBFSMHRTIQQ7BKYA",
             "AdHgeP4dyWInWwPn9YlfxFCm3qP1lHjdxOxeJqDa");

     // create a client connection based on credentials
     AmazonS3 s3client = new AmazonS3Client(credentials);

     String folderName = "image"; //folder name
     //    String bucketName = "ppas-image-upload"; //must be unique

     try {//from  ww  w . ja  v  a  2 s .  c o m
         if (!(s3client.doesBucketExist(bucketName))) {
             s3client.setRegion(Region.getRegion(Regions.US_EAST_1));
             // Note that CreateBucketRequest does not specify region. So bucket is 
             // created in the region specified in the client.
             s3client.createBucket(new CreateBucketRequest(bucketName));
         }

         //Enabe CORS:
         //     <?xml version="1.0" encoding="UTF-8"?>
         //<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
         //    <CORSRule>
         //        <AllowedOrigin>http://ask-ifr-download.s3.amazonaws.com</AllowedOrigin>
         //        <AllowedMethod>GET</AllowedMethod>
         //    </CORSRule>
         //</CORSConfiguration>
         BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration();

         CORSRule corsRule = new CORSRule()
                 .withAllowedMethods(
                         Arrays.asList(new CORSRule.AllowedMethods[] { CORSRule.AllowedMethods.GET }))
                 .withAllowedOrigins(Arrays.asList(new String[] { "http://ask-ifr-download.s3.amazonaws.com" }));
         configuration.setRules(Arrays.asList(new CORSRule[] { corsRule }));
         s3client.setBucketCrossOriginConfiguration(bucketName, configuration);

     } catch (AmazonServiceException ase) {
         System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                 + "to Amazon S3, but was rejected with an error response" + " for some reason.");
         System.out.println("Error Message:    " + ase.getMessage());
         System.out.println("HTTP Status Code: " + ase.getStatusCode());
         System.out.println("AWS Error Code:   " + ase.getErrorCode());
         System.out.println("Error Type:       " + ase.getErrorType());
         System.out.println("Request ID:       " + ase.getRequestId());
     } catch (AmazonClientException ace) {
         System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                 + "an internal error while trying to " + "communicate with S3, "
                 + "such as not being able to access the network.");
         System.out.println("Error Message: " + ace.getMessage());
     }

     String fileName = folderName + SUFFIX + imageName + ".png";
     URL url = new URL(imageURL);

     ObjectMetadata omd = new ObjectMetadata();
     omd.setContentType("image/png");
     omd.setContentLength(url.openConnection().getContentLength());
     // upload file to folder and set it to public
     s3client.putObject(new PutObjectRequest(bucketName, fileName, url.openStream(), omd)
             .withCannedAcl(CannedAccessControlList.PublicRead));
 }

From source file:com.mycompany.mytubeaws.DownloadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w w  w .  j a  va2s  . c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String result = "";
    String downloadLink = "";

    String inputKey = request.getParameter("downloadKey");

    if (inputKey == null)
        result += "inputKey is null; ";
    else if (inputKey.length() == 0)
        result += "inputKey is blank; ";
    else {
        result += "Downloading an object; ";

        try {
            //            S3Object object = s3.getObject(new GetObjectRequest(bucketName, inputKey));
            //            S3ObjectInputStream objectContent = object.getObjectContent();
            //            
            //            File f = File.createTempFile("aws-java-sdk-download", "");
            //            FileOutputStream fos = new FileOutputStream(f);
            //            IOUtils.copy(objectContent, fos);
            //            fos.close();
            //            
            //            result += "Content-Type: '" + object.getObjectMetadata().getContentType() + "'; ";
            //            result += "Mime '" + new MimetypesFileTypeMap().getContentType(f) + "'; ";
            //            
            //            response.setContentType(new MimetypesFileTypeMap().getContentType(f));
            //            response.setHeader("Content-Disposition","attachment;filename="+inputKey);
            //            
            //            ServletOutputStream out = response.getOutputStream();
            //            
            //            
            //            f.delete();

            GeneratePresignedUrlRequest requestUrl = new GeneratePresignedUrlRequest(bucketName, inputKey);
            downloadLink = s3.generatePresignedUrl(requestUrl).toString();
            System.out.println(downloadLink);
            //result += downloadLink + " ; ";
        } catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException, which means your request made it "
                    + "to Amazon S3, but was rejected with an error response for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());

            result += "AmazonServiceException thrown; ";
        } catch (AmazonClientException ace) {
            System.out.println("Caught an AmazonClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with S3, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());

            result += "AmazonClientException thrown; ";
        }
    }

    System.out.println(result);

    request.setAttribute("resultText", result);
    request.setAttribute("downloadLink", downloadLink);
    request.getRequestDispatcher("/DownloadResult.jsp").forward(request, response);
    //response.sendRedirect("UploadResult.jsp");
}

From source file:com.mycompany.mytubeaws.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w w  w  .  ja  v a  2 s . co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String result = "";
    String fileName = null;

    boolean uploaded = false;

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(1024 * 1024 * 3); // 3mb
    factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // sets temporary location to store files

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(1024 * 1024 * 40); // sets maximum size of upload file
    upload.setSizeMax(1024 * 1024 * 50); // sets maximum size of request (include file + form data)

    try {
        List<FileItem> formItems = upload.parseRequest(request); // parses the request's content to extract file data

        if (formItems != null && formItems.size() > 0) // iterates over form's fields
        {
            for (FileItem item : formItems) // processes only fields that are not form fields
            {
                if (!item.isFormField()) {
                    fileName = item.getName();
                    UUID id = UUID.randomUUID();
                    fileName = FilenameUtils.getBaseName(fileName) + "_ID-" + id.toString() + "."
                            + FilenameUtils.getExtension(fileName);

                    File file = File.createTempFile("aws-java-sdk-upload", "");
                    item.write(file); // write form item to file (?)

                    if (file.length() == 0)
                        throw new RuntimeException("No file selected or empty file uploaded.");

                    try {
                        s3.putObject(new PutObjectRequest(bucketName, fileName, file));
                        result += "File uploaded successfully; ";
                        uploaded = true;
                    } catch (AmazonServiceException ase) {
                        System.out.println("Caught an AmazonServiceException, which means your request made it "
                                + "to Amazon S3, but was rejected with an error response for some reason.");
                        System.out.println("Error Message:    " + ase.getMessage());
                        System.out.println("HTTP Status Code: " + ase.getStatusCode());
                        System.out.println("AWS Error Code:   " + ase.getErrorCode());
                        System.out.println("Error Type:       " + ase.getErrorType());
                        System.out.println("Request ID:       " + ase.getRequestId());

                        result += "AmazonServiceException thrown; ";
                    } catch (AmazonClientException ace) {
                        System.out
                                .println("Caught an AmazonClientException, which means the client encountered "
                                        + "a serious internal problem while trying to communicate with S3, "
                                        + "such as not being able to access the network.");
                        System.out.println("Error Message: " + ace.getMessage());

                        result += "AmazonClientException thrown; ";
                    }

                    file.delete();
                }
            }
        }
    } catch (Exception ex) {
        result += "Generic exception: '" + ex.getMessage() + "'; ";
        ex.printStackTrace();
    }

    if (fileName != null && uploaded)
        result += "Generated file ID: " + fileName;

    System.out.println(result);

    request.setAttribute("resultText", result);
    request.getRequestDispatcher("/UploadResult.jsp").forward(request, response);
}

From source file:com.netflix.dynomitemanager.sidecore.backup.S3Backup.java

License:Apache License

/**
 * Uses the Amazon S3 API to upload the AOF/RDB to S3
 * Filename: Backup location + DC + Rack + App + Token
 */// ww w  . j  a va 2  s  .com
@Override
public boolean upload(File file, DateTime todayStart) {
    logger.info("Snapshot backup: sending " + file.length() + " bytes to S3");

    /* Key name is comprised of the 
    * backupDir + DC + Rack + token + Date
    */
    String keyName = config.getBackupLocation() + "/" + iid.getInstance().getDatacenter() + "/"
            + iid.getInstance().getRack() + "/" + iid.getInstance().getToken() + "/" + todayStart.getMillis();

    // Get bucket location.
    logger.info("Key in Bucket: " + keyName);
    logger.info("S3 Bucket Name:" + config.getBucketName());

    AmazonS3Client s3Client = new AmazonS3Client(cred.getAwsCredentialProvider());

    try {
        // Checking if the S3 bucket exists, and if does not, then we create it

        if (!(s3Client.doesBucketExist(config.getBucketName()))) {
            logger.error("Bucket with name: " + config.getBucketName() + " does not exist");
            return false;
        } else {
            logger.info("Uploading data to S3\n");
            // Create a list of UploadPartResponse objects. You get one of these for
            // each part upload.
            List<PartETag> partETags = new ArrayList<PartETag>();

            InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(
                    config.getBucketName(), keyName);

            InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(initRequest);

            long contentLength = file.length();
            long filePosition = 0;
            long partSize = this.initPartSize;

            try {
                for (int i = 1; filePosition < contentLength; i++) {
                    // Last part can be less than initPartSize (500MB). Adjust part size.
                    partSize = Math.min(partSize, (contentLength - filePosition));

                    // Create request to upload a part.
                    UploadPartRequest uploadRequest = new UploadPartRequest()
                            .withBucketName(config.getBucketName()).withKey(keyName)
                            .withUploadId(initResponse.getUploadId()).withPartNumber(i)
                            .withFileOffset(filePosition).withFile(file).withPartSize(partSize);

                    // Upload part and add response to our list.
                    partETags.add(s3Client.uploadPart(uploadRequest).getPartETag());

                    filePosition += partSize;
                }

                CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(
                        config.getBucketName(), keyName, initResponse.getUploadId(), partETags);

                s3Client.completeMultipartUpload(compRequest);

            } catch (Exception e) {
                logger.error("Abosting multipart upload due to error");
                s3Client.abortMultipartUpload(new AbortMultipartUploadRequest(config.getBucketName(), keyName,
                        initResponse.getUploadId()));
            }

            return true;
        }
    } catch (AmazonServiceException ase) {

        logger.error(
                "AmazonServiceException;" + " request made it to Amazon S3, but was rejected with an error ");
        logger.error("Error Message:    " + ase.getMessage());
        logger.error("HTTP Status Code: " + ase.getStatusCode());
        logger.error("AWS Error Code:   " + ase.getErrorCode());
        logger.error("Error Type:       " + ase.getErrorType());
        logger.error("Request ID:       " + ase.getRequestId());
        return false;

    } catch (AmazonClientException ace) {
        logger.error("AmazonClientException;" + " the client encountered "
                + "an internal error while trying to " + "communicate with S3, ");
        logger.error("Error Message: " + ace.getMessage());
        return false;
    }
}

From source file:com.netflix.dynomitemanager.sidecore.backup.S3Restore.java

License:Apache License

/**
  * Uses the Amazon S3 API to restore from S3
  *//*from w w  w.j  av a  2  s.  c om*/
@Override
public boolean restoreData(String dateString) {
    long time = restoreTime(dateString);
    if (time > -1) {
        logger.info("Restoring data from S3.");
        AmazonS3Client s3Client = new AmazonS3Client(cred.getAwsCredentialProvider());

        try {
            /* construct the key for the backup data */
            String keyName = config.getBackupLocation() + "/" + iid.getInstance().getDatacenter() + "/"
                    + iid.getInstance().getRack() + "/" + iid.getInstance().getToken() + "/" + time;

            logger.info("S3 Bucket Name: " + config.getBucketName());
            logger.info("Key in Bucket: " + keyName);

            // Checking if the S3 bucket exists, and if does not, then we create it
            if (!(s3Client.doesBucketExist(config.getBucketName()))) {
                logger.error("Bucket with name: " + config.getBucketName() + " does not exist");
            } else {
                S3Object s3object = s3Client.getObject(new GetObjectRequest(config.getBucketName(), keyName));

                logger.info("Content-Type: " + s3object.getObjectMetadata().getContentType());

                String filepath = null;

                if (config.isAof()) {
                    filepath = config.getPersistenceLocation() + "/appendonly.aof";
                } else {
                    filepath = config.getPersistenceLocation() + "/nfredis.rdb";
                }

                IOUtils.copy(s3object.getObjectContent(), new FileOutputStream(new File(filepath)));
            }
            return true;
        } catch (AmazonServiceException ase) {

            logger.error("AmazonServiceException;"
                    + " request made it to Amazon S3, but was rejected with an error ");
            logger.error("Error Message:    " + ase.getMessage());
            logger.error("HTTP Status Code: " + ase.getStatusCode());
            logger.error("AWS Error Code:   " + ase.getErrorCode());
            logger.error("Error Type:       " + ase.getErrorType());
            logger.error("Request ID:       " + ase.getRequestId());

        } catch (AmazonClientException ace) {
            logger.error("AmazonClientException;" + " the client encountered "
                    + "an internal error while trying to " + "communicate with S3, ");
            logger.error("Error Message: " + ace.getMessage());
        } catch (IOException io) {
            logger.error("File storing error: " + io.getMessage());
        }
    } else {
        logger.error("Date in FP: " + dateString);
    }
    return false;
}

From source file:com.netflix.priam.aws.SDBInstanceRegistry.java

License:Apache License

@Override
public PriamInstance acquireSlotId(int slotId, String expectedInstanceId, String app, String instanceID,
        String hostname, String ip, String rac, Map<String, Object> volumes, String token) {
    try {/*from w w  w  .ja v  a 2  s.co  m*/
        PriamInstance ins = PriamInstance.from(app, slotId, instanceID, hostname, ip, rac, volumes, token,
                amazonConfiguration.getRegionName());
        dao.registerInstance(ins, expectedInstanceId);
        // Only return a result if we successfully overwrote the previous value; otherwise return null to indicate failure
        PriamInstance storedInstance = dao.getInstance(ins.getApp(), ins.getId(), true);
        if (storedInstance.getInstanceId().equals(ins.getInstanceId())) {
            return ins;
        } else {
            return null;
        }
    } catch (AmazonServiceException e) {
        logger.error(e.getMessage());
        throw new RuntimeException("Unable to update/create priam instance", e);
    }
}

From source file:com.netflix.spinnaker.clouddriver.aws.security.DefaultAWSAccountInfoLookup.java

License:Apache License

@Override
public String findAccountId() {
    AmazonEC2 ec2 = amazonClientProvider.getAmazonEC2(credentialsProvider, AmazonClientProvider.DEFAULT_REGION);
    try {/*from  w w  w . j  a  va2 s .  c o  m*/
        List<Vpc> vpcs = ec2.describeVpcs().getVpcs();
        boolean supportsByName = false;
        if (vpcs.isEmpty()) {
            supportsByName = true;
        } else {
            for (Vpc vpc : vpcs) {
                if (vpc.getIsDefault()) {
                    supportsByName = true;
                    break;
                }
            }
        }

        DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
        if (supportsByName) {
            request.withGroupNames(DEFAULT_SECURITY_GROUP_NAME);
        }
        DescribeSecurityGroupsResult result = ec2.describeSecurityGroups(request);

        for (SecurityGroup sg : result.getSecurityGroups()) {
            //if there is a vpcId or it is the default security group it won't be an EC2 cross account group
            if ((sg.getVpcId() != null && sg.getVpcId().length() > 0)
                    || DEFAULT_SECURITY_GROUP_NAME.equals(sg.getGroupName())) {
                return sg.getOwnerId();
            }
        }

        throw new IllegalArgumentException("Unable to lookup accountId with provided credentials");
    } catch (AmazonServiceException ase) {
        if ("AccessDenied".equals(ase.getErrorCode())) {
            String message = ase.getMessage();
            Matcher matcher = IAM_ARN_PATTERN.matcher(message);
            if (matcher.matches()) {
                return matcher.group(1);
            }
        }
        throw ase;
    }
}

From source file:com.neu.cloud.Controller.FifthUseCaseController.java

private void uploadInS3(String uploadFilePath, String uploadFileName, String dateForFolder) {
    String bucketName = "reports-sppard";
    String keyName = "UseCase5-" + dateForFolder + "/" + uploadFileName;
    AmazonS3 s3client = new AmazonS3Client(
            new BasicAWSCredentials("AKIAJ2E67YVFQ5PZSWQA", "xiVuejpUofGonrsiy2owvu/wgeNKq5nYjxYVC0ma"));
    try {/*from  ww w  .j a  va 2 s. co  m*/
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFilePath + uploadFileName);
        s3client.putObject(new PutObjectRequest(bucketName, 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());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                + "an internal error while trying to " + "communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.neu.cloud.Controller.FirstUseCaseController.java

private void uploadInS3(String uploadFilePath, String uploadFileName, String dateForFolder) {
    String bucketName = "reports-sppard";
    String keyName = "UseCase1-" + dateForFolder + "/" + uploadFileName;
    AmazonS3 s3client = new AmazonS3Client(
            new BasicAWSCredentials("AKIAJ2E67YVFQ5PZSWQA", "xiVuejpUofGonrsiy2owvu/wgeNKq5nYjxYVC0ma"));
    try {//from w w  w. j  a va 2s  . c  o  m
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFilePath + uploadFileName);
        s3client.putObject(new PutObjectRequest(bucketName, 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());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                + "an internal error while trying to " + "communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.neu.cloud.Controller.FourthUseCaseController.java

private void uploadInS3(String uploadFilePath, String uploadFileName, String dateForFolder) {
    String bucketName = "reports-sppard";
    String keyName = "UseCase4-" + dateForFolder + "/" + uploadFileName;
    AmazonS3 s3client = new AmazonS3Client(
            new BasicAWSCredentials("AKIAJ2E67YVFQ5PZSWQA", "xiVuejpUofGonrsiy2owvu/wgeNKq5nYjxYVC0ma"));
    try {//from  w  w w . ja va  2s.  c om
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFilePath + uploadFileName);
        s3client.putObject(new PutObjectRequest(bucketName, 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());
    } 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());
    }
}