Example usage for com.amazonaws AmazonServiceException getErrorCode

List of usage examples for com.amazonaws AmazonServiceException getErrorCode

Introduction

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

Prototype

public String getErrorCode() 

Source Link

Document

Returns the AWS error code represented by this exception.

Usage

From source file:edu.columbia.cc.elPonePeli.app.LiveStreamingHelper.java

public void createFormation(String stackName, String logicalResourceName) {

    try {//from   www .j a v  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  w  w .  ja v  a2  s  .c  o m*/
    }
    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   w w w.j a  v a2 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/* www  .  j  a  v  a 2s  .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/* w ww.j  a  v  a2s .c  om*/
 * @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());
        }
    }
}

From source file:edu.utn.frba.grupo5303.serverenviolibre.services.NotificacionesPushService.java

@Override
public void enviarNotificacion(NotificacionPush notificacion) {
    try {//from  w w w.  j a  v a2 s .c o m
        logger.log(Level.INFO, "Enviando notificacion al snsId: {0}", notificacion.getGcmIdDestino());
        logger.log(Level.INFO, "Enviando notificacion de tipo: {0}", notificacion.getCodigo());
        PublishRequest publishRequest = new PublishRequest();
        Map<String, MessageAttributeValue> notificationAttributes = getValidNotificationAttributes(
                attributesMap.get(plataforma));
        if (notificationAttributes != null && !notificationAttributes.isEmpty()) {
            publishRequest.setMessageAttributes(notificationAttributes);
        }
        publishRequest.setMessageStructure("json");
        // If the message attributes are not set in the requisite method,
        // notification is sent with default attributes
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put(plataforma.name(), notificacion.getMensajeDeNotificacion());
        String message = SampleMessageGenerator.jsonify(messageMap);

        // Create Platform Application. This corresponds to an app on a
        // platform.
        CreatePlatformApplicationResult platformApplicationResult = createPlatformApplication();

        // The Platform Application Arn can be used to uniquely identify the
        // Platform Application.
        String platformApplicationArn = platformApplicationResult.getPlatformApplicationArn();

        // Create an Endpoint. This corresponds to an app on a device.
        CreatePlatformEndpointResult platformEndpointResult = createPlatformEndpoint("CustomData",
                notificacion.getGcmIdDestino(), platformApplicationArn);

        // For direct publish to mobile end points, topicArn is not relevant.
        publishRequest.setTargetArn(platformEndpointResult.getEndpointArn());

        publishRequest.setMessage(message);
        snsClient.publish(publishRequest);
    } catch (AmazonServiceException ase) {
        logger.log(Level.SEVERE, "Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SNS, but was rejected with an error response for some reason.");
        logger.log(Level.SEVERE, "Error Message:    {0}", ase.getMessage());
        logger.log(Level.SEVERE, "HTTP Status Code: {0}", ase.getStatusCode());
        logger.log(Level.SEVERE, "AWS Error Code:   {0}", ase.getErrorCode());
        logger.log(Level.SEVERE, "Error Type:       {0}", ase.getErrorType());
        logger.log(Level.SEVERE, "Request ID:       {0}", ase.getRequestId());
    } catch (AmazonClientException ace) {
        logger.log(Level.SEVERE,
                "Caught an AmazonClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with SNS, such as not "
                        + "being able to access the network.");
        logger.log(Level.SEVERE, "Error Message: {0}", ace.getMessage());
    }
}

From source file:eu.optimis.interopt.provider.aws.AmazonClient.java

License:Apache License

private String printServiceException(AmazonServiceException se) {
    return se.getMessage() + "(HTTP Code: " + se.getStatusCode() + " - AWS Code: " + se.getErrorCode()
            + " - Error Type: " + se.getErrorType() + " )";
}

From source file:example.uploads3.UploadS3.java

License:Apache License

public static void main(String[] args) throws Exception {
    String uploadFileName = args[0];
    String bucketName = "haos3";
    String keyName = "test/byspark.txt";
    // Create a Java Spark Context.
    SparkConf conf = new SparkConf().setAppName("UploadS3");
    JavaSparkContext sc = new JavaSparkContext(conf);

    AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
    try {/*from   w  ww .  java2 s  .c  o m*/
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFileName);
        PutObjectRequest putRequest = new PutObjectRequest(bucketName, keyName, file);

        // Request server-side encryption.
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setServerSideEncryption("AES256");
        putRequest.setMetadata(objectMetadata);

        s3client.putObject(putRequest);

    } 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:exemplos.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*//from  w  w  w.  j  ava 2 s .com
     * This credentials provider implementation loads your AWS credentials
     * from a properties file at the root of your classpath.
     *
     * 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 ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
    String key = "MyObjectKey";

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

    try {
        /*
         * Create a new S3 bucket - Amazon S3 bucket names are globally unique,
         * so once a bucket name has been taken by any user, you can't create
         * another bucket with that same name.
         *
         * You can optionally specify a location for your bucket if you want to
         * keep your data closer to your applications or users.
         */
        System.out.println("Creating bucket " + bucketName + "\n");
        s3.createBucket(bucketName);

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        /*
         * Upload an object to your bucket - You can easily upload a file to
         * S3, or upload directly an InputStream if you know the length of
         * the data in the stream. You can also specify your own metadata
         * when uploading to S3, which allows you set a variety of options
         * like content-type and content-encoding, plus additional metadata
         * specific to your applications.
         */
        System.out.println("Uploading a new object to S3 from a file\n");
        s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        /*
         * Download an object - When you download an object, you get all of
         * the object's metadata and a stream from which to read the contents.
         * It's important to read the contents of the stream as quickly as
         * possibly since the data is streamed directly from Amazon S3 and your
         * network connection will remain open until you read all the data or
         * close the input stream.
         *
         * GetObjectRequest also supports several other options, including
         * conditional downloading of objects based on modification times,
         * ETags, and selectively downloading a range of an object.
         */
        System.out.println("Downloading an object");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());

        /*
         * List objects in your bucket by prefix - There are many options for
         * listing the objects in your bucket.  Keep in mind that buckets with
         * many objects might truncate their results when listing their objects,
         * so be sure to check if the returned object listing is truncated, and
         * use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve
         * additional results.
         */
        System.out.println("Listing objects");
        ObjectListing objectListing = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(
                    " - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();

        /*
         * Delete an object - Unless versioning has been turned on for your bucket,
         * there is no way to undelete an object, so use caution when deleting objects.
         */
        System.out.println("Deleting an object\n");
        s3.deleteObject(bucketName, key);

        /*
         * Delete a bucket - A bucket must be completely empty before it can be
         * deleted, so remember to delete any objects from your buckets before
         * you try to delete them.
         */
        System.out.println("Deleting bucket " + bucketName + "\n");
        s3.deleteBucket(bucketName);
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon S3, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java

License:Apache License

KeyPair createOrOverWriteSshKeyPair(String userName) {
    String keyPairName;//from w  ww.  j a v  a  2  s. c o  m
    if (userName.endsWith("@xebia.fr") || userName.endsWith("@xebia.com")) {
        keyPairName = userName.substring(0, userName.indexOf("@xebia."));
    } else {
        keyPairName = userName.replace("@", "_at_").replace(".", "_dot_").replace("+", "_plus_");
    }
    try {
        DescribeKeyPairsResult describeKeyPairsResult = ec2
                .describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyPairName));
        if (!describeKeyPairsResult.getKeyPairs().isEmpty()) {
            // unexpected, should be an "InvalidKeyPair.NotFound"
            // AmazonServiceException
            ec2.deleteKeyPair(new DeleteKeyPairRequest(keyPairName));
        }
    } catch (AmazonServiceException e) {
        if ("InvalidKeyPair.NotFound".equals(e.getErrorCode())) {
            // key does not exist
        } else {
            throw e;
        }
    }
    CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(new CreateKeyPairRequest(keyPairName));
    KeyPair keyPair = createKeyPairResult.getKeyPair();
    return keyPair;
}