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:org.apache.stratos.aws.extension.AWSHelper.java

License:Apache License

public CreateAppCookieStickinessPolicyResult createStickySessionPolicy(String lbName, String cookieName,
        String policyName, String region) {

    elbClient.setEndpoint(String.format(Constants.ELB_ENDPOINT_URL_FORMAT, region));

    CreateAppCookieStickinessPolicyRequest stickinessPolicyReq = new CreateAppCookieStickinessPolicyRequest()
            .withLoadBalancerName(lbName).withCookieName(cookieName).withPolicyName(policyName);

    CreateAppCookieStickinessPolicyResult stickinessPolicyResult = null;
    try {/*from  ww  w. j  a  va  2 s  .com*/
        stickinessPolicyResult = elbClient.createAppCookieStickinessPolicy(stickinessPolicyReq);

    } catch (AmazonServiceException e) {
        log.error(e.getMessage(), e);

    } catch (AmazonClientException e) {
        log.error(e.getMessage(), e);
    }

    if (stickinessPolicyResult == null) {
        log.error("Error in creating Application Stickiness policy for for cookie name: " + cookieName
                + ", policy: " + policyName);
    } else {
        log.info("Enabled Application stickiness using: " + cookieName + ", policy: " + policyName + " for LB "
                + lbName);
    }

    return stickinessPolicyResult;
}

From source file:org.apache.stratos.aws.extension.AWSHelper.java

License:Apache License

private void applyPolicyToListener(String loadBalancerName, int listenerPort, String policyName,
        String region) {//from w w w  .ja v a2s .co m

    SetLoadBalancerPoliciesOfListenerRequest loadBalancerPoliciesOfListenerReq = new SetLoadBalancerPoliciesOfListenerRequest()
            .withLoadBalancerName(loadBalancerName).withLoadBalancerPort(listenerPort)
            .withPolicyNames(policyName);

    elbClient.setEndpoint(String.format(Constants.ELB_ENDPOINT_URL_FORMAT, region));

    SetLoadBalancerPoliciesOfListenerResult setLBPoliciesOfListenerRes = null;
    try {
        setLBPoliciesOfListenerRes = elbClient
                .setLoadBalancerPoliciesOfListener(loadBalancerPoliciesOfListenerReq);

    } catch (AmazonServiceException e) {
        log.error(e.getMessage(), e);

    } catch (AmazonClientException e) {
        log.error(e.getMessage(), e);
    }

    if (setLBPoliciesOfListenerRes == null) {
        log.error("Unable to apply policy " + policyName + " for Listener port: " + listenerPort + " for LB: "
                + loadBalancerName);
    } else {
        log.info("Successfully applied policy " + policyName + " for Listener port: " + listenerPort
                + " for LB: " + loadBalancerName);
    }
}

From source file:org.apache.stratos.aws.extension.AWSHelper.java

License:Apache License

public List<String> getAvailabilityZonesFromRegion(final String region) {

    DescribeAvailabilityZonesRequest availabilityZonesReq = new DescribeAvailabilityZonesRequest();
    List<Filter> availabilityZoneFilters = new ArrayList<Filter>();
    availabilityZoneFilters.add(new Filter("region-name", new ArrayList<String>() {
        {/*from  www .j av  a  2 s.  co m*/
            add(region);
        }
    }));
    availabilityZoneFilters.add(new Filter("state", new ArrayList<String>() {
        {
            add("available");
        }
    }));

    ec2Client.setEndpoint(String.format(Constants.EC2_ENDPOINT_URL_FORMAT, region));
    DescribeAvailabilityZonesResult availabilityZonesRes = null;

    try {
        availabilityZonesRes = ec2Client.describeAvailabilityZones(availabilityZonesReq);

    } catch (AmazonServiceException e) {
        log.error(e.getMessage(), e);

    } catch (AmazonClientException e) {
        log.error(e.getMessage(), e);
    }

    List<String> availabilityZones = null;

    if (availabilityZonesRes != null) {
        availabilityZones = new ArrayList<>();
        for (AvailabilityZone zone : availabilityZonesRes.getAvailabilityZones()) {
            availabilityZones.add(zone.getZoneName());
        }
    } else {
        log.error("Unable to retrieve the active availability zones for region " + region);
    }

    return availabilityZones;
}

From source file:org.apache.stratos.aws.extension.AWSHelper.java

License:Apache License

public void addAvailabilityZonesForLoadBalancer(String loadBalancerName, List<String> availabilityZones,
        String region) {//w  ww. j  a v  a 2s  .  co  m

    EnableAvailabilityZonesForLoadBalancerRequest enableAvailabilityZonesReq = new EnableAvailabilityZonesForLoadBalancerRequest()
            .withLoadBalancerName(loadBalancerName).withAvailabilityZones(availabilityZones);

    elbClient.setEndpoint(String.format(Constants.ELB_ENDPOINT_URL_FORMAT, region));

    EnableAvailabilityZonesForLoadBalancerResult enableAvailabilityZonesRes = null;

    try {
        enableAvailabilityZonesRes = elbClient
                .enableAvailabilityZonesForLoadBalancer(enableAvailabilityZonesReq);

    } catch (AmazonServiceException e) {
        log.error(e.getMessage(), e);

    } catch (AmazonClientException e) {
        log.error(e.getMessage(), e);
    }

    if (enableAvailabilityZonesRes != null) {
        log.info("Availability zones successfully added to LB " + loadBalancerName + ". Updated zone list: ");
        for (String zone : enableAvailabilityZonesRes.getAvailabilityZones()) {
            log.info(zone);
        }
    } else {
        log.error("Updating availability zones failed for LB " + loadBalancerName);
    }
}

From source file:org.apache.usergrid.apm.service.ApplicationServiceImpl.java

License:Apache License

boolean deleteSQSQueue(String appName) {
    log.info("Deleting Queue for App : " + appName.toString());
    DeleteQueueRequest deleteQueueRequest = new DeleteQueueRequest();
    deleteQueueRequest.setQueueUrl(AWSUtil.formFullQueueUrl(appName.toString()));
    try {/*  w  w w.  ja v  a 2s.c  o m*/
        sqsClient.deleteQueue(deleteQueueRequest);
        return true;
    } catch (AmazonServiceException ase) {
        if (ase.getErrorCode().equals("AWS.SimpleQueueService.NonExistentQueue")) {
            log.info("Queue for app : " + appName.toString() + " was probably already deleted. "
                    + ase.getMessage());
        } else {
            log.error(ase);
        }
    } catch (AmazonClientException ace) {
        log.error(ace);
    }
    return false;
}

From source file:org.apache.usergrid.rest.applications.ServiceResource.java

License:Apache License

@CheckPermissionsForPath
@GET// w ww  .  ja v a2 s  .c o m
@Produces(MediaType.WILDCARD)
public Response executeStreamGet(@Context UriInfo ui, @PathParam("entityId") PathSegment entityId,
        @HeaderParam("range") String rangeHeader, @HeaderParam("if-modified-since") String modifiedSince)
        throws Exception {

    if (logger.isTraceEnabled()) {
        logger.trace("ServiceResource.executeStreamGet");
    }

    //Needed for testing
    if (properties.getProperty(PROPERTIES_USERGRID_BINARY_UPLOADER).equals("local")) {
        this.binaryStore = localFileBinaryStore;
    } else {
        this.binaryStore = awsSdkS3BinaryStore;
    }

    ApiResponse response = createApiResponse();
    response.setAction("get");
    response.setApplication(services.getApplication());
    response.setParams(ui.getQueryParameters());
    ServiceResults serviceResults = executeServiceRequest(ui, response, ServiceAction.GET, null);
    Entity entity = serviceResults.getEntity();

    if (logger.isTraceEnabled()) {
        logger.trace("In ServiceResource.executeStreamGet with id: {}, range: {}, modifiedSince: {}", entityId,
                rangeHeader, modifiedSince);
    }

    Map<String, Object> fileMetadata = AssetUtils.getFileMetadata(entity);

    // return a 302 if not modified
    Date modified = AssetUtils.fromIfModifiedSince(modifiedSince);
    if (modified != null) {
        Long lastModified = (Long) fileMetadata.get(AssetUtils.LAST_MODIFIED);
        if (lastModified - modified.getTime() < 0) {
            return Response.status(Response.Status.NOT_MODIFIED).build();
        }
    }

    boolean range = StringUtils.isNotBlank(rangeHeader);
    long start = 0, end = 0, contentLength = 0;
    InputStream inputStream;

    if (range) { // honor range request, calculate start & end

        String rangeValue = rangeHeader.trim().substring("bytes=".length());
        contentLength = (Long) fileMetadata.get(AssetUtils.CONTENT_LENGTH);
        end = contentLength - 1;
        if (rangeValue.startsWith("-")) {
            start = contentLength - 1 - Long.parseLong(rangeValue.substring("-".length()));
        } else {
            String[] startEnd = rangeValue.split("-");
            long parsedStart = Long.parseLong(startEnd[0]);
            if (parsedStart > start && parsedStart < end) {
                start = parsedStart;
            }
            if (startEnd.length > 1) {
                long parsedEnd = Long.parseLong(startEnd[1]);
                if (parsedEnd > start && parsedEnd < end) {
                    end = parsedEnd;
                }
            }
        }
        try {
            inputStream = binaryStore.read(getApplicationId(), entity, start, end - start);
        } catch (AwsPropertiesNotFoundException apnfe) {
            logger.error("Amazon Property needed for this operation not found", apnfe);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        } catch (RuntimeException re) {
            logger.error(re.getMessage());
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    } else { // no range
        try {
            inputStream = binaryStore.read(getApplicationId(), entity);
        } catch (AwsPropertiesNotFoundException apnfe) {
            logger.error("Amazon Property needed for this operation not found", apnfe);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        } catch (AmazonServiceException ase) {

            if (ase.getStatusCode() > 499) {
                logger.error(ase.getMessage());
            } else if (logger.isDebugEnabled()) {
                logger.debug(ase.getMessage());
            }
            return Response.status(ase.getStatusCode()).build();
        } catch (RuntimeException re) {
            logger.error(re.getMessage());
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    // return 404 if not found
    if (inputStream == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }

    Long lastModified = (Long) fileMetadata.get(AssetUtils.LAST_MODIFIED);
    Response.ResponseBuilder responseBuilder = Response.ok(inputStream)
            .type((String) fileMetadata.get(AssetUtils.CONTENT_TYPE)).lastModified(new Date(lastModified));

    if (fileMetadata.get(AssetUtils.E_TAG) != null) {
        responseBuilder.tag((String) fileMetadata.get(AssetUtils.E_TAG));
    }

    if (range) {
        responseBuilder.header("Content-Range", "bytes " + start + "-" + end + "/" + contentLength);
    }

    return responseBuilder.build();
}

From source file:org.apereo.portal.portlets.dynamicskin.storage.s3.AwsS3DynamicSkinService.java

License:Apache License

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

From source file:org.applicationMigrator.serverAgent.ServerAgentFileTransferClient.java

License:Apache License

private void uploadFile(AWSCredentials awsCredentials, String sourcePathString, String destinationPathString,
        boolean forceUpload) throws FileNotFoundException {
    // TODO Think about one file being used by many apps (e.g HP1.pdf read
    // through Adobe reader and OpenOffice)
    AmazonS3 s3client = new AmazonS3Client(awsCredentials);
    boolean fileIsPresentOnServer = checkIfFileIsPresentOnServer(s3client, BUCKET_NAME, destinationPathString);
    if (fileIsPresentOnServer && !forceUpload)
        return;//from   www.j a  va 2s  .c  om
    try {
        File file = new File(sourcePathString);
        if (!file.exists())
            throw new FileNotFoundException();
        s3client.putObject(new PutObjectRequest(BUCKET_NAME, destinationPathString, 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());
        throw ase;
    } 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());
        throw ace;
    }
    // TODO:verify completion of upload operation

}

From source file:org.boriken.s3fileuploader.S3SampleRefactored.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*// w  w  w .  java 2  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
     */
    AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(
            S3SampleRefactored.class.getResourceAsStream("../conf/AwsCredentials.properties")));

    //        String bucketName = "chamakits-my-first-s3-bucket-" + UUID.randomUUID();
    String bucketName = "chamakits-HelloS3";
    String key = "somekey";

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon S3");
    System.out.println("===========================================\n");

    try {
        //           createBucket(s3,bucketName);
        //           listBuckets(s3);
        //           createFile(s3,bucketName,key);
        //           downloadFile(s3,bucketName,key);
        //           listFiles(s3, bucketName,"");
        //            deleteFile(s3, bucketName, key);
        //           deleteBucket(s3, bucketName);

        listFiles(s3, 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:org.crypto.sse.IEX2LevAMAZON.java

License:Open Source License

/**
 * @param args/*  w w w . j a v a  2 s .c  om*/
 * @throws Exception
 */
@SuppressWarnings("null")
public static void main(String[] args) throws Exception {

    //First Job
    Configuration conf = new Configuration();

    Job job = Job.getInstance(conf, "IEX-2Lev");

    job.setJarByClass(IEX2LevAMAZON.class);

    job.setMapperClass(MLK1.class);

    job.setReducerClass(RLK1.class);

    job.setMapOutputKeyClass(Text.class);

    job.setMapOutputValueClass(Text.class);

    job.setOutputKeyClass(Text.class);

    job.setNumReduceTasks(1);

    job.setOutputValueClass(ArrayListWritable.class);

    job.setInputFormatClass(FileNameKeyInputFormat.class);

    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));

    //Second Job
    Configuration conf2 = new Configuration();

    Job job2 = Job.getInstance(conf2, "IEX-2Lev");

    job2.setJarByClass(IEX2LevAMAZON.class);

    job2.setMapperClass(MLK2.class);

    job2.setReducerClass(RLK2.class);

    job2.setNumReduceTasks(1);

    job2.setMapOutputKeyClass(Text.class);

    job2.setMapOutputValueClass(Text.class);

    job2.setOutputKeyClass(Text.class);

    job2.setOutputValueClass(ArrayListWritable.class);

    job2.setInputFormatClass(FileNameKeyInputFormat.class);

    FileInputFormat.addInputPath(job2, new Path(args[0]));
    FileOutputFormat.setOutputPath(job2, new Path(args[2]));

    job.waitForCompletion(true);
    job2.waitForCompletion(true);

    //Here add your Amazon Credentials

    AWSCredentials credentials = new BasicAWSCredentials("XXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXX");
    // create a client connection based on credentials
    AmazonS3 s3client = new AmazonS3Client(credentials);

    // create bucket - name must be unique for all S3 users
    String bucketName = "iexmaptest";

    S3Object s3object = s3client.getObject(new GetObjectRequest(bucketName, args[4]));
    System.out.println(s3object.getObjectMetadata().getContentType());
    System.out.println(s3object.getObjectMetadata().getContentLength());
    List<String> lines = new ArrayList<String>();

    String folderName = "2";

    BufferedReader reader = new BufferedReader(new InputStreamReader(s3object.getObjectContent()));
    String line;
    int counter = 0;
    while ((line = reader.readLine()) != null) {
        // can copy the content locally as well
        // using a buffered writer
        lines.add(line);
        System.out.println(line);
        // upload file to folder 
        String fileName = folderName + "/" + Integer.toString(counter);
        ByteArrayInputStream input = new ByteArrayInputStream(line.getBytes());
        s3client.putObject(bucketName, fileName, input, new ObjectMetadata());
        counter++;
    }

    Multimap<String, String> lookup = ArrayListMultimap.create();

    for (int i = 0; i < lines.size(); i++) {
        String[] tokens = lines.get(i).split("\\s+");
        for (int j = 1; j < tokens.length; j++) {
            lookup.put(tokens[0], tokens[j]);
        }
    }

    // Loading inverted index that associates files identifiers to keywords
    lines = new ArrayList<String>();
    s3object = s3client.getObject(new GetObjectRequest(bucketName, args[5]));
    System.out.println(s3object.getObjectMetadata().getContentType());
    System.out.println(s3object.getObjectMetadata().getContentLength());

    // Loading inverted index that associates keywords to identifiers

    reader = new BufferedReader(new InputStreamReader(s3object.getObjectContent()));
    while ((line = reader.readLine()) != null) {
        lines.add(line);
    }
    Multimap<String, String> lookup2 = ArrayListMultimap.create();
    for (int i = 0; i < lines.size(); i++) {
        String[] tokens = lines.get(i).split("\\s+");
        for (int j = 1; j < tokens.length; j++) {
            lookup2.put(tokens[0], tokens[j]);
        }
    }

    // Delete File
    try {
        s3client.deleteObject(new DeleteObjectRequest(bucketName, args[4]));
    } 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.");
        System.out.println("Error Message: " + ace.getMessage());
    }

    /*
     * Start of IEX-2Lev construction
     */

    // Generation of keys for IEX-2Lev
    BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter your password :");
    String pass = keyRead.readLine();

    // You can change the size of the key; Here we set it to 128

    List<byte[]> listSK = IEX2Lev.keyGen(128, pass, "salt/salt", 100);

    // Generation of Local Multi-maps with Mapper job only without reducer

    Configuration conf3 = new Configuration();

    String testSerialization1 = new String(Base64.encodeBase64(Serializer.serialize(lookup)));
    String testSerialization2 = new String(Base64.encodeBase64(Serializer.serialize(lookup2)));

    String testSerialization3 = new String(Base64.encodeBase64(Serializer.serialize(listSK)));

    //String testSerialization2 = gson.toJson(lookup2);
    conf3.set("lookup", testSerialization1);
    conf3.set("lookup2", testSerialization2);
    conf3.set("setKeys", testSerialization3);

    Job job3 = Job.getInstance(conf3, "Local MM");

    job3.setJarByClass(IEX2LevAMAZON.class);

    job3.setMapperClass(LocalMM.class);

    job3.setNumReduceTasks(0);

    FileInputFormat.addInputPath(job3, new Path(args[2]));
    FileOutputFormat.setOutputPath(job3, new Path(args[3]));

    job3.waitForCompletion(true);

}