Example usage for com.amazonaws AmazonServiceException getStatusCode

List of usage examples for com.amazonaws AmazonServiceException getStatusCode

Introduction

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

Prototype

public int getStatusCode() 

Source Link

Document

Returns the HTTP status code that was returned with this service exception.

Usage

From source file:ch.cyberduck.core.iam.AmazonServiceExceptionMappingService.java

License:Open Source License

@Override
public BackgroundException map(final AmazonClientException e) {
    final StringBuilder buffer = new StringBuilder();
    if (e instanceof AmazonServiceException) {
        final AmazonServiceException failure = (AmazonServiceException) e;
        this.append(buffer, failure.getErrorMessage());
        switch (failure.getStatusCode()) {
        case HttpStatus.SC_BAD_REQUEST:
            switch (failure.getErrorCode()) {
            case "AccessDeniedException":
                return new AccessDeniedException(buffer.toString(), e);
            case "UnrecognizedClientException":
                return new LoginFailureException(buffer.toString(), e);
            }//from   w  w  w.j a  v  a  2  s  . co  m
            return new InteroperabilityException(buffer.toString(), e);
        case HttpStatus.SC_METHOD_NOT_ALLOWED:
            return new InteroperabilityException(buffer.toString(), e);
        case HttpStatus.SC_FORBIDDEN:
            switch (failure.getErrorCode()) {
            case "SignatureDoesNotMatch":
                return new LoginFailureException(buffer.toString(), e);
            case "InvalidAccessKeyId":
                return new LoginFailureException(buffer.toString(), e);
            case "InvalidClientTokenId":
                return new LoginFailureException(buffer.toString(), e);
            case "InvalidSecurity":
                return new LoginFailureException(buffer.toString(), e);
            case "MissingClientTokenId":
                return new LoginFailureException(buffer.toString(), e);
            case "MissingAuthenticationToken":
                return new LoginFailureException(buffer.toString(), e);
            }
            return new AccessDeniedException(buffer.toString(), e);
        case HttpStatus.SC_UNAUTHORIZED:
            return new LoginFailureException(buffer.toString(), e);
        case HttpStatus.SC_NOT_FOUND:
            return new NotfoundException(buffer.toString(), e);
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            return new ConnectionRefusedException(buffer.toString(), e);
        }
    }
    this.append(buffer, e.getMessage());
    return this.wrap(e, buffer);
}

From source file:Cloud.Tweets.SimpleQueueServiceSample.java

License:Open Source License

public void addmessage(AmazonSQS abc, String x) {
    System.out.println("Sending a message to MyQueue.\n" + myQueueUrl);
    try {/* ww  w .  ja v  a 2  s.  c om*/
        System.out.println(x);
        abc.sendMessage(new SendMessageRequest(myQueueUrl, x));

        System.out.println("Message Sent.\n");
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        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 SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:cloudExplorer.BucketClass.java

License:Open Source License

String makeBucket(String access_key, String secret_key, String bucket, String endpoint, String region) {
    String message = null;/*ww w.  j  a v a  2  s .co  m*/
    AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);
    AmazonS3 s3Client = new AmazonS3Client(credentials,
            new ClientConfiguration().withSignerOverride("S3SignerType"));
    s3Client.setEndpoint(endpoint);
    try {
        if (endpoint.contains("amazon")) {
            s3Client.createBucket(new CreateBucketRequest(bucket));

        } else {
            s3Client.createBucket(new CreateBucketRequest(bucket, region));
        }

        message = ("\nAttempting to create the bucket. Please view the Bucket list window for an update.");
    } catch (AmazonServiceException ase) {
        if (NewJFrame.gui) {
            mainFrame.jTextArea1.append("\n\nError Message:    " + ase.getMessage());
            mainFrame.jTextArea1.append("\nHTTP Status Code: " + ase.getStatusCode());
            mainFrame.jTextArea1.append("\nAWS Error Code:   " + ase.getErrorCode());
            mainFrame.jTextArea1.append("\nError Type:       " + ase.getErrorType());
            mainFrame.jTextArea1.append("\nRequest ID:       " + ase.getRequestId());
            calibrate();
        } else {
            System.out.print("\n\nError Message:    " + ase.getMessage());
            System.out.print("\nHTTP Status Code: " + ase.getStatusCode());
            System.out.print("\nAWS Error Code:   " + ase.getErrorCode());
            System.out.print("\nError Type:       " + ase.getErrorType());
            System.out.print("\nRequest ID:       " + ase.getRequestId());
        }
    }
    if (message == null) {
        message = "Failed to create bucket.";
    }
    return message;

}

From source file:cloudExplorer.BucketClass.java

License:Open Source License

String listBuckets(String access_key, String secret_key, String endpoint) {

    AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);
    AmazonS3 s3Client = new AmazonS3Client(credentials,
            new ClientConfiguration().withSignerOverride("S3SignerType"));
    s3Client.setEndpoint(endpoint);/*from   www  . j a  v a2s . c o m*/
    String[] array = new String[10];

    String bucketlist = null;

    int i = 0;
    try {

        for (Bucket bucket : s3Client.listBuckets()) {
            bucketlist = bucketlist + " " + bucket.getName();
        }

    } catch (AmazonServiceException ase) {
        if (NewJFrame.gui) {
            mainFrame.jTextArea1.append("\n\nError Message:    " + ase.getMessage());
            mainFrame.jTextArea1.append("\nHTTP Status Code: " + ase.getStatusCode());
            mainFrame.jTextArea1.append("\nAWS Error Code:   " + ase.getErrorCode());
            mainFrame.jTextArea1.append("\nError Type:       " + ase.getErrorType());
            mainFrame.jTextArea1.append("\nRequest ID:       " + ase.getRequestId());
            calibrate();
        } else {
            System.out.print("\n\nError Message:    " + ase.getMessage());
            System.out.print("\nHTTP Status Code: " + ase.getStatusCode());
            System.out.print("\nAWS Error Code:   " + ase.getErrorCode());
            System.out.print("\nError Type:       " + ase.getErrorType());
            System.out.print("\nRequest ID:       " + ase.getRequestId());
        }

    } catch (Exception lsbuckets) {

        if (lsbuckets.getMessage().contains("peer not authenticated")
                || lsbuckets.getMessage().contains("hostname in certificate didn't match")) {
            if (NewJFrame.gui) {
                mainFrame.jTextArea1.append(
                        "\nError: This program does not support non-trusted SSL certificates\n\nor your SSL certificates are incorrect.");
            } else {
                System.out.print(
                        "\n\nError: This program does not support non-trusted SSL certificates\n\nor your SSL certificates are not correctly installed.");
            }
        }
    }
    String parse = null;

    if (bucketlist != null) {
        parse = bucketlist.replace("null", "");

    } else {
        parse = "no_bucket_found";
    }

    return parse;
}

From source file:cloudExplorer.Delete.java

License:Open Source License

public void run() {
    AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);
    AmazonS3 s3Client = new AmazonS3Client(credentials,
            new ClientConfiguration().withSignerOverride("S3SignerType"));
    s3Client.setEndpoint(endpoint);//  w  ww. ja va2 s.c  om

    try {

        if (version != null) {
            s3Client.deleteVersion(new DeleteVersionRequest(bucket, what, version));
        } else {
            s3Client.deleteObject(new DeleteObjectRequest(bucket, what));
        }
        if (!debug) {
            NewJFrame.jTextArea1.append("\nDeleted object: " + what);
        }
        calibrate();
    } catch (AmazonServiceException ase) {
        if (NewJFrame.gui) {
            mainFrame.jTextArea1.append("\n\nError Message:    " + ase.getMessage());
            mainFrame.jTextArea1.append("\nHTTP Status Code: " + ase.getStatusCode());
            mainFrame.jTextArea1.append("\nAWS Error Code:   " + ase.getErrorCode());
            mainFrame.jTextArea1.append("\nError Type:       " + ase.getErrorType());
            mainFrame.jTextArea1.append("\nRequest ID:       " + ase.getRequestId());
            calibrate();
        } else {
            System.out.print("\n\nError Message:    " + ase.getMessage());
            System.out.print("\nHTTP Status Code: " + ase.getStatusCode());
            System.out.print("\nAWS Error Code:   " + ase.getErrorCode());
            System.out.print("\nError Type:       " + ase.getErrorType());
            System.out.print("\nRequest ID:       " + ase.getRequestId());
        }
    } catch (Exception delete) {
    }
}

From source file:cloudExplorer.Get.java

License:Open Source License

public void run() {
    String message = null;//from w  ww .  j  av a 2  s.  co m
    AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);
    File file = new File(what);
    AmazonS3 s3Client = new AmazonS3Client(credentials,
            new ClientConfiguration().withSignerOverride("S3SignerType"));
    s3Client.setEndpoint(endpoint);

    try {
        long t1 = System.currentTimeMillis();
        S3Object s3object = s3Client.getObject(new GetObjectRequest(bucket, what, version));
        InputStream objectData = s3object.getObjectContent();
        this.writeFile(objectData, destination);
        long t2 = System.currentTimeMillis();
        long diff = t2 - t1;

        if (!mainFrame.perf) {
            if (terminal) {
                System.out.print("\nDownloaded: " + what + " in " + diff / 1000 + " second(s).\n");
            } else {
                mainFrame.jTextArea1.append("\nDownloaded: " + what + " in " + diff / 1000 + " second(s).");
                mainFrame.calibrateTextArea();
            }
        }

    } catch (AmazonServiceException ase) {
        if (NewJFrame.gui) {
            mainFrame.jTextArea1.append("\n\nError Message:    " + ase.getMessage());
            mainFrame.jTextArea1.append("\nHTTP Status Code: " + ase.getStatusCode());
            mainFrame.jTextArea1.append("\nAWS Error Code:   " + ase.getErrorCode());
            mainFrame.jTextArea1.append("\nError Type:       " + ase.getErrorType());
            mainFrame.jTextArea1.append("\nRequest ID:       " + ase.getRequestId());
            calibrate();
        } else {
            System.out.print("\n\nError Message:    " + ase.getMessage());
            System.out.print("\nHTTP Status Code: " + ase.getStatusCode());
            System.out.print("\nAWS Error Code:   " + ase.getErrorCode());
            System.out.print("\nError Type:       " + ase.getErrorType());
            System.out.print("\nRequest ID:       " + ase.getRequestId());
        }
    } catch (Exception get) {
    }
    calibrate();
}

From source file:cloudExplorer.Put.java

License:Open Source License

public void run() {
    try {/*from  www .jav a  2  s . c o m*/
        AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);
        AmazonS3 s3Client = new AmazonS3Client(credentials,
                new ClientConfiguration().withSignerOverride("S3SignerType"));
        s3Client.setEndpoint(endpoint);
        TransferManager tx = new TransferManager(s3Client);
        File file = new File(what);
        PutObjectRequest putRequest;
        if (!rrs) {
            putRequest = new PutObjectRequest(bucket, ObjectKey, file);
        } else {
            putRequest = new PutObjectRequest(bucket, ObjectKey, file)
                    .withStorageClass(StorageClass.ReducedRedundancy);
        }
        MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        String mimeType = mimeTypesMap.getContentType(file);
        mimeType = mimeTypesMap.getContentType(file);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        if (encrypt) {
            objectMetadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
        }
        if ((ObjectKey.contains(".html")) || ObjectKey.contains(".txt")) {
            objectMetadata.setContentType("text/html");
        } else {
            objectMetadata.setContentType(mimeType);
        }
        long t1 = System.currentTimeMillis();
        putRequest.setMetadata(objectMetadata);
        Upload myUpload = tx.upload(putRequest);
        myUpload.waitForCompletion();
        tx.shutdownNow();
        long t2 = System.currentTimeMillis();
        long diff = t2 - t1;

        if (!mainFrame.perf) {
            if (terminal) {
                System.out.print("\nUploaded object: " + ObjectKey + " in " + diff / 1000 + " second(s).\n");
            } else {
                mainFrame.jTextArea1
                        .append("\nUploaded object: " + ObjectKey + " in " + diff / 1000 + " second(s).");
            }
        }
    } catch (AmazonServiceException ase) {
        if (NewJFrame.gui) {
            mainFrame.jTextArea1.append("\n\nError Message:    " + ase.getMessage());
            mainFrame.jTextArea1.append("\nHTTP Status Code: " + ase.getStatusCode());
            mainFrame.jTextArea1.append("\nAWS Error Code:   " + ase.getErrorCode());
            mainFrame.jTextArea1.append("\nError Type:       " + ase.getErrorType());
            mainFrame.jTextArea1.append("\nRequest ID:       " + ase.getRequestId());
            calibrate();
        } else {
            System.out.print("\n\nError Message:    " + ase.getMessage());
            System.out.print("\nHTTP Status Code: " + ase.getStatusCode());
            System.out.print("\nAWS Error Code:   " + ase.getErrorCode());
            System.out.print("\nError Type:       " + ase.getErrorType());
            System.out.print("\nRequest ID:       " + ase.getRequestId());
        }
    } catch (Exception put) {
    }

    calibrate();
}

From source file:cloudworker.DynamoDBService.java

License:Apache License

private static void createTable() throws Exception {
    try {/*w w  w. j  a  v a  2s . c  o m*/
        // Create table if it does not exist yet
        if (Tables.doesTableExist(dynamoDB, TABLE_NAME)) {
            //System.out.println("Table " + TABLE_NAME + " is already ACTIVE");
        } else {
            // Create a table with a primary hash key named 'taskID', which holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(TABLE_NAME)
                    .withKeySchema(new KeySchemaElement().withAttributeName("taskID").withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(new AttributeDefinition().withAttributeName("taskID")
                            .withAttributeType(ScalarAttributeType.S))
                    .withProvisionedThroughput(
                            new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));

            TableDescription tableDescription = dynamoDB.createTable(createTableRequest).getTableDescription();
            //System.out.println("Created Table: " + tableDescription);

            // Wait for it to become active
            //System.out.println("Waiting for " + TABLE_NAME + " to become ACTIVE...");
            Tables.waitForTableToBecomeActive(dynamoDB, TABLE_NAME);
        }

        // Describe our new table
        //            DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(TABLE_NAME);
        //            TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        //            System.out.println("Table Description: " + tableDescription);
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }

}

From source file:com.amazon.aws.myyoutube.videoUtil.GetRDSInstance.java

License:Open Source License

public static void main(String[] args) throws Exception {

    credentials = new PropertiesCredentials(
            GetRDSInstance.class.getResourceAsStream("AwsCredentials.properties"));

    try {/*  ww  w  .ja v a 2 s .  c o m*/
        rds = new AmazonRDSClient(credentials);

        /*********************************************
         *  RDS DB
         *********************************************/

        System.out.println("Creating a database instance");

        CreateDBSecurityGroupRequest d = new CreateDBSecurityGroupRequest()
                .withDBSecurityGroupName("javaSecurityGroup1")
                .withDBSecurityGroupDescription("DB security group1");
        rds.createDBSecurityGroup(d);

        AuthorizeDBSecurityGroupIngressRequest auth = new AuthorizeDBSecurityGroupIngressRequest()
                .withDBSecurityGroupName("javaSecurityGroup1")
                //         .withEC2SecurityGroupName("javaSecurityGroup")
                .withCIDRIP("0.0.0.0/0");
        //         .withCIDRIP("216.165.95.69/32");

        DBSecurityGroup dbsecuritygroup = rds.authorizeDBSecurityGroupIngress(auth);
        String[] dBSecurityGroups = { dbsecuritygroup.getDBSecurityGroupName() };

        CreateDBInstanceRequest createDBInstanceRequest = new CreateDBInstanceRequest().withEngine("MySQL")
                .withLicenseModel("general-public-license").withEngineVersion("5.6.13")
                .withDBInstanceClass("db.t1.micro").withMultiAZ(false).withAutoMinorVersionUpgrade(true)
                .withAllocatedStorage(5).withDBInstanceIdentifier("mydbinstance1").withMasterUsername("awsuser")
                .withMasterUserPassword("mypassword").withDBName("dbname1").withPort(3306)
                .withAvailabilityZone(null).withDBSecurityGroups(dBSecurityGroups);

        ArrayList<String> arrDbSecur = new ArrayList<String>();
        arrDbSecur.add("javaSecurityGroup1");
        createDBInstanceRequest.setDBSecurityGroups(arrDbSecur);

        DBInstance dbInstance = rds.createDBInstance(createDBInstanceRequest);

        Thread.sleep(600000);

        DescribeDBInstancesRequest instRequest = new DescribeDBInstancesRequest()
                .withDBInstanceIdentifier("mydbinstance1");

        DescribeDBInstancesResult instres = rds.describeDBInstances(instRequest);

        Endpoint e = instres.getDBInstances().get(0).getEndpoint();
        System.out.println("ENd point " + e.getAddress() + " " + e.getPort());
        System.out.println("Database Created");
        System.out.println("Creating a table");
        //connection
        java.sql.Connection con = null;
        Statement st = null;
        // Format "jdbc:mysql://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password=" + password;
        String url = "jdbc:mysql://" + e.getAddress() + ":" + e.getPort()
                + "/dbname1?user=awsuser&password=mypassword"; //  "jdbc:mysql://master:password@"+e+"/dbname";
        System.out.println("Url is " + url);
        String user = "awsuser";
        String password = "mypassword";

        con = DriverManager.getConnection(url, user, password);

        System.out.println("Connection created");

        java.sql.Statement stat = con.createStatement();

        String query = "CREATE TABLE Items ( item_id VARCHAR(200), type INTEGER, quantity INTEGER, user VARCHAR(100), price FLOAT(5,2) );";
        stat.execute(query);

        String query1 = "CREATE TABLE WishList ( user VARCHAR(200), wishlistId VARCHAR(100) );";
        stat.execute(query1);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Response Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }
}

From source file:com.amazon.photosharing.facade.ContentFacade.java

License:Open Source License

public Media uploadPictureToS3(User p_user, String p_file_name, InputStream p_file_stream,
        String p_content_type, Comment... _comments) throws IOException {
    Media media = null;/*from   ww w. java  2s  .com*/

    try {

        ContentHelper.getInstance()
                .createS3BucketIfNotExists(ContentHelper.getInstance().getConfiguredBucketName());

        beginTx();

        String s3Key = S3Helper.createS3Key(p_file_name, p_user.getUserName(), new Date());
        String s3ThumbKey = S3Helper.createS3Key("thumb_" + p_file_name, p_user.getUserName(), new Date());

        byte[] original_bytes = null;
        byte[] thumb_bytes = null;

        //clone a byte[] of the input original for image resize and thumb clone
        ByteArrayOutputStream byte_worker = new ByteArrayOutputStream();
        ImageIO.write(ImageIO.read(p_file_stream), p_file_name.substring(p_file_name.lastIndexOf(".") + 1),
                byte_worker);

        original_bytes = byte_worker.toByteArray();
        try {
            thumb_bytes = new MediaResizeTask(new ByteArrayInputStream(original_bytes), p_file_name).call();
        } catch (Exception e) {
            _logger.error(e.getMessage(), e);
        }

        User u = em().find(User.class, p_user.getId());

        media = new Media();
        media.setS3Bucket(ContentHelper.getInstance().getConfiguredBucketName());
        media.setS3FileName(s3Key);
        media.setS3ThumbFileName(s3ThumbKey);
        media.setName(p_file_name);
        media.setUser(u);

        if (_comments != null) {
            for (Comment comment : _comments) {
                comment.setMedia(media);
                media.getComments().add(comment);
            }
        }

        u.getMedia().add(media);

        em().persist(u);

        commitTx();

        ContentHelper.getInstance().uploadContent(p_content_type, thumb_bytes.length,
                ContentHelper.getInstance().getConfiguredBucketName(), s3ThumbKey,
                new ByteArrayInputStream(thumb_bytes));
        ContentHelper.getInstance().uploadContent(p_content_type, original_bytes.length,
                ContentHelper.getInstance().getConfiguredBucketName(), s3Key,
                new ByteArrayInputStream(original_bytes));

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            //do some sleeping here..
        }

    } catch (AmazonServiceException ase) {
        _logger.info("Caught an AmazonServiceException, which " + "means your request made it "
                + "to Amazon S3, but was rejected with an error response" + " for some reason.");
        _logger.info("Error Message:    " + ase.getMessage());
        _logger.info("HTTP Status Code: " + ase.getStatusCode());
        _logger.info("AWS Error Code:   " + ase.getErrorCode());
        _logger.info("Error Type:       " + ase.getErrorType());
        _logger.info("Request ID:       " + ase.getRequestId());

        try {
            rollbackTx();
        } catch (Exception ex) {
        }

        ase.printStackTrace();

    } catch (AmazonClientException ace) {
        _logger.info("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.");
        _logger.info("Error Message: " + ace.getMessage());

        ace.printStackTrace();

        rollbackTx();
    }

    return media;
}