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:com.cloudbees.gasp.services.APNRegistrationService.java

License:Apache License

@POST
@Path("unregister")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response doUnregister(@FormParam("token") String token) {
    try {//w  w  w .  j ava  2s.  co m
        // Delete the SNS app endpoint
        snsMobile.deleteEndpointArn(APNDataStore.getEndpointArn(token));
        LOGGER.info("Deleted endpoint: " + APNDataStore.getEndpointArn(token));

        APNDataStore.unregisterArn(token);
        LOGGER.info("Unregistered device: " + token);

    } catch (AmazonServiceException ase) {
        LOGGER.debug("AmazonServiceException");
        LOGGER.debug("  Error Message:    " + ase.getMessage());
        LOGGER.debug("  HTTP Status Code: " + ase.getStatusCode());
        LOGGER.debug("  AWS Error Code:   " + ase.getErrorCode());
        LOGGER.debug("  Error Type:       " + ase.getErrorType());
        LOGGER.debug("  Request ID:       " + ase.getRequestId());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } catch (AmazonClientException ace) {
        LOGGER.debug("AmazonClientException");
        LOGGER.debug("  Error Message: " + ace.getMessage());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }

    return Response.status(Response.Status.OK).build();
}

From source file:com.cloudbees.gasp.services.DataSyncService.java

License:Apache License

private void sendPushNotifications(String messageText) {
    try {//from ww  w.  j  ava 2 s.co m
        SNSMobile snsMobile = new SNSMobile();

        // Send update to all registered APN endpoints
        for (String endpointArn : APNDataStore.getEndpoints()) {
            LOGGER.info("Sending update to APN endpoint ARN: " + endpointArn);
            snsMobile.pushNotification(SNSMobile.Platform.APNS_SANDBOX, endpointArn,
                    getApnMessage(messageText));
        }

        // Send update to all registered GCM endpoints
        for (String endpointArn : GCMDataStore.getEndpoints()) {
            LOGGER.info("Sending update to GCM endpoint ARN: " + endpointArn);
            snsMobile.pushNotification(SNSMobile.Platform.GCM, endpointArn, getGcmMessage(messageText));
        }
    } catch (AmazonServiceException ase) {
        LOGGER.debug("AmazonServiceException");
        LOGGER.debug("  Error Message:    " + ase.getMessage());
        LOGGER.debug("  HTTP Status Code: " + ase.getStatusCode());
        LOGGER.debug("  AWS Error Code:   " + ase.getErrorCode());
        LOGGER.debug("  Error Type:       " + ase.getErrorType());
        LOGGER.debug("  Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        LOGGER.debug("AmazonClientException");
        LOGGER.debug("  Error Message: " + ace.getMessage());
    } catch (Exception e) {
        return;
    }
}

From source file:com.cloudbees.gasp.services.GCMRegistrationService.java

License:Apache License

@POST
@Path("register")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response doRegister(@FormParam("regId") String regId) {

    try {/*from   w w  w  .ja  va  2  s . co m*/
        CreatePlatformEndpointResult platformEndpointResult = snsMobile
                .createPlatformEndpoint("Gasp GCM Platform Endpoint", regId, snsMobile.getGcmPlatformArn());

        GCMDataStore.registerArn(regId, platformEndpointResult.getEndpointArn());
        LOGGER.info("Registered: " + platformEndpointResult.getEndpointArn());

    } catch (AmazonServiceException ase) {
        LOGGER.debug("AmazonServiceException");
        LOGGER.debug("  Error Message:    " + ase.getMessage());
        LOGGER.debug("  HTTP Status Code: " + ase.getStatusCode());
        LOGGER.debug("  AWS Error Code:   " + ase.getErrorCode());
        LOGGER.debug("  Error Type:       " + ase.getErrorType());
        LOGGER.debug("  Request ID:       " + ase.getRequestId());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } catch (AmazonClientException ace) {
        LOGGER.debug("AmazonClientException");
        LOGGER.debug("  Error Message: " + ace.getMessage());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }

    return Response.status(Response.Status.OK).build();
}

From source file:com.cloudbees.gasp.services.GCMRegistrationService.java

License:Apache License

@POST
@Path("unregister")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response doUnregister(@FormParam("regId") String regId) {
    try {//from w  w w.j a v  a  2s.c  o  m
        // Delete the SNS app endpoint
        snsMobile.deleteEndpointArn(GCMDataStore.getEndpointArn(regId));
        LOGGER.info("Deleted endpoint: " + GCMDataStore.getEndpointArn(regId));

        GCMDataStore.unregisterArn(regId);
        LOGGER.info("Unregistered device: " + regId);

    } catch (AmazonServiceException ase) {
        LOGGER.debug("AmazonServiceException");
        LOGGER.debug("  Error Message:    " + ase.getMessage());
        LOGGER.debug("  HTTP Status Code: " + ase.getStatusCode());
        LOGGER.debug("  AWS Error Code:   " + ase.getErrorCode());
        LOGGER.debug("  Error Type:       " + ase.getErrorType());
        LOGGER.debug("  Request ID:       " + ase.getRequestId());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } catch (AmazonClientException ace) {
        LOGGER.debug("AmazonClientException");
        LOGGER.debug("  Error Message: " + ace.getMessage());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }

    return Response.status(Response.Status.OK).build();
}

From source file:com.clouddrive.parth.NewClass.java

public static String runCluster() throws Exception {
    long start = System.currentTimeMillis();
    String temp = "";
    // Configure the job flow
    //RunJobFlowRequest request = new RunJobFlowRequest().withName("parth");
    // if (request == null) {
    RunJobFlowRequest request = new RunJobFlowRequest(FLOW_NAME, configInstance());
    request.setLogUri(S3N_LOG_URI);
    // }/*from  w w  w . j  av a2 s.c om*/

    // Configure the Hadoop jar to use
    HadoopJarStepConfig jarConfig = new HadoopJarStepConfig(S3N_HADOOP_JAR);
    jarConfig.setArgs(ARGS_AS_LIST);

    try {

        StepConfig enableDebugging = new StepConfig().withName("Enable debugging")
                .withActionOnFailure("TERMINATE_JOB_FLOW")
                .withHadoopJarStep(new StepFactory().newEnableDebuggingStep());

        StepConfig runJar = new StepConfig(S3N_HADOOP_JAR.substring(S3N_HADOOP_JAR.indexOf('/') + 1),
                jarConfig);

        request.setSteps(Arrays.asList(new StepConfig[] { enableDebugging, runJar }));

        // Run the job flow
        RunJobFlowResult result = emr.runJobFlow(request);

        // Check the status of the running job
        String lastState = "";

        STATUS_LOOP: while (true) {
            DescribeJobFlowsRequest desc = new DescribeJobFlowsRequest(
                    Arrays.asList(new String[] { result.getJobFlowId() }));
            DescribeJobFlowsResult descResult = emr.describeJobFlows(desc);
            for (JobFlowDetail detail : descResult.getJobFlows()) {
                String state = detail.getExecutionStatusDetail().getState();
                if (isDone(state)) {
                    System.out.println("Job " + state + ": " + detail.toString());
                    break STATUS_LOOP;
                } else if (!lastState.equals(state)) {
                    lastState = state;
                    System.out.println("Job " + state + " at " + new Date().toString());
                }
            }
            Thread.sleep(10000);
        }
        temp = FLOW_NAME;
        long end = System.currentTimeMillis();
        System.out.println("Computation " + (end - start));
    } 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 temp;
}

From source file:com.cloudera.director.aws.ec2.ebs.EBSAllocator.java

License:Apache License

/**
 * Waits for the volumes in a list of {@code InstanceEbsVolumes} to reach an available state.
 * Returns an updated list of {@code InstanceEbsVolumes} with the volumes that became
 * available marked as AVAILABLE and volumes that failed or timed out marked as FAILED.
 *
 * @param createdInstanceVolumes list of instances with their created ebs volumes
 * @return updated list of instances EBS volumes
 *///  www.j  ava  2s .c  o m
public List<InstanceEbsVolumes> waitUntilVolumesAvailable(List<InstanceEbsVolumes> createdInstanceVolumes)
        throws InterruptedException {

    Set<String> volumesToCheck = getAllVolumeIdsWithStatus(createdInstanceVolumes,
            InstanceEbsVolumes.Status.CREATED);

    int numRequestedVolumes = volumesToCheck.size();
    Set<String> volumesAvailable = Sets.newHashSetWithExpectedSize(numRequestedVolumes);

    if (numRequestedVolumes > 0) {
        LOG.info("Waiting for a maximum of {} seconds for volumes to become available",
                availableTimeoutSeconds);

        Stopwatch watch = Stopwatch.createStarted();
        while (watch.elapsed(TimeUnit.SECONDS) < availableTimeoutSeconds) {
            DescribeVolumesRequest volumeRequest = new DescribeVolumesRequest().withVolumeIds(volumesToCheck);

            try {
                List<Volume> volumes = client.describeVolumes(volumeRequest).getVolumes();

                for (Volume volume : volumes) {
                    String id = volume.getVolumeId();
                    VolumeState state = VolumeState.fromValue(volume.getState());

                    switch (state) {
                    case Creating:
                        break;
                    case Available:
                        volumesToCheck.remove(id);
                        volumesAvailable.add(id);
                        break;
                    case Error:
                        // TODO log why the volume failed which may need a separate api call
                        volumesToCheck.remove(id);
                        break;
                    default:
                        String err = String
                                .format("A requested volume went into an unexpected state %s while waiting "
                                        + "for volume to become available", state);
                        throw new IllegalStateException(String.format(err, state));
                    }
                }

                if (volumesToCheck.isEmpty()) {
                    break;
                }
            } catch (AmazonServiceException ex) {
                // ignore exception when volume isn't found, newly created volumes may not be found right away
                if (ex.getErrorCode().equals("InvalidVolume.NotFound")) {
                    LOG.info("Requested volume(s) not yet found");
                } else {
                    throw AWSExceptions.propagate(ex);
                }
            }

            LOG.info("Waiting on {} out of {} volumes to reach a final state, next check in {} seconds",
                    volumesToCheck.size(), numRequestedVolumes, WAIT_UNTIL_AVAILABLE_INTERVAL_SECONDS);
            TimeUnit.SECONDS.sleep(WAIT_UNTIL_AVAILABLE_INTERVAL_SECONDS);
        }

        if (volumesToCheck.size() > 0) {
            LOG.error(
                    "Timed out while waiting for volumes to be created, {} out of {} volumes became available",
                    volumesAvailable.size(), numRequestedVolumes);
        }
    } else {
        LOG.info("Skipping wait for availability because no EBS volumes were created");
    }

    // Update the status of each volume to AVAILABLE or FAILED based on the result

    List<InstanceEbsVolumes> updated = Lists.newArrayList();
    for (InstanceEbsVolumes instanceEbsVolumes : createdInstanceVolumes) {
        Map<String, InstanceEbsVolumes.Status> updatedVolumes = Maps.newHashMap();
        for (String volumeId : instanceEbsVolumes.getVolumeStatuses().keySet()) {
            InstanceEbsVolumes.Status updatedStatus = volumesAvailable.contains(volumeId)
                    ? InstanceEbsVolumes.Status.AVAILABLE
                    : InstanceEbsVolumes.Status.FAILED;
            updatedVolumes.put(volumeId, updatedStatus);
        }
        updated.add(new InstanceEbsVolumes(instanceEbsVolumes.getVirtualInstanceId(),
                instanceEbsVolumes.getEc2InstanceId(), updatedVolumes));
    }

    return updated;
}

From source file:com.cloudera.director.aws.ec2.EC2InstanceTemplateConfigurationValidator.java

License:Apache License

/**
 * Validates the configured AMI.// w ww  .  j ava2s.  com
 *
 * @param client              the EC2 client
 * @param configuration       the configuration to be validated
 * @param accumulator         the exception condition accumulator
 * @param localizationContext the localization context
 */
@VisibleForTesting
@SuppressWarnings("PMD.CollapsibleIfStatements")
void checkImage(AmazonEC2Client client, Configured configuration,
        PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) {

    String imageName = configuration.getConfigurationValue(IMAGE, localizationContext);
    String type = configuration.getConfigurationValue(TYPE, localizationContext);

    int conditionCount = accumulator.getConditionsByKey().size();

    if (!imageName.startsWith("ami-")) {
        addError(accumulator, IMAGE, localizationContext, null, INVALID_AMI_NAME_MSG, imageName);
        return;
    }

    LOG.info(">> Describing AMI '{}'", imageName);
    DescribeImagesResult result = null;
    try {
        result = client.describeImages(new DescribeImagesRequest().withImageIds(imageName));
        checkCount(accumulator, IMAGE, localizationContext, imageName, result.getImages());
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().startsWith(INVALID_AMI_ID)) {
            addError(accumulator, IMAGE, localizationContext, null, INVALID_AMI_MSG, imageName);
        } else {
            throw Throwables.propagate(e);
        }
    }

    if ((result == null) || (accumulator.getConditionsByKey().size() > conditionCount)) {
        return;
    }

    Image image = Iterables.getOnlyElement(result.getImages());
    if (!SIXTY_FOUR_BIT_ARCHITECTURE.equals(image.getArchitecture())) {
        addError(accumulator, IMAGE, localizationContext, null, INVALID_AMI_ARCHITECTURE_MSG, imageName,
                image.getArchitecture());
    }

    AWSFilters imageFilters = templateFilters.getSubfilters(IMAGE.unwrap().getConfigKey());
    boolean useSpotInstances = Boolean
            .parseBoolean(configuration.getConfigurationValue(USE_SPOT_INSTANCES, localizationContext));

    String ownerId = image.getOwnerId();
    if (ownerId != null) {
        String blacklistValue = imageFilters.getBlacklistValue(IMAGE_OWNER_ID_BLACKLIST_KEY,
                ownerId.toLowerCase());
        if (blacklistValue != null) {
            addError(accumulator, IMAGE, localizationContext, null, INVALID_AMI_OWNER_MSG, imageName, ownerId,
                    blacklistValue);
        } else {
            if (useSpotInstances) {
                blacklistValue = imageFilters.getBlacklistValue(IMAGE_SPOT_OWNER_ID_BLACKLIST_KEY,
                        ownerId.toLowerCase());
                if (blacklistValue != null) {
                    addError(accumulator, IMAGE, localizationContext, null, INVALID_AMI_OWNER_SPOT_MSG,
                            imageName, ownerId, blacklistValue);
                }
            }
        }
    }

    String platform = image.getPlatform();
    if (platform != null) {
        String blacklistValue = imageFilters.getBlacklistValue(IMAGE_PLATFORM_BLACKLIST_KEY,
                platform.toLowerCase());
        if (blacklistValue != null) {
            addError(accumulator, IMAGE, localizationContext, null, INVALID_AMI_PLATFORM_MSG, imageName,
                    platform, blacklistValue);
        } else {
            if (useSpotInstances) {
                blacklistValue = imageFilters.getBlacklistValue(IMAGE_SPOT_PLATFORM_BLACKLIST_KEY,
                        platform.toLowerCase());
                if (blacklistValue != null) {
                    addError(accumulator, IMAGE, localizationContext, null, INVALID_AMI_PLATFORM_SPOT_MSG,
                            imageName, platform, blacklistValue);
                }
            }
        }
    }

    if (!AVAILABLE_STATE.equals(image.getState())) {
        addError(accumulator, IMAGE, localizationContext, null, INVALID_AMI_STATE_MSG, imageName,
                image.getState());
    }

    if (!provider.getVirtualizationMappings().apply(image.getVirtualizationType()).contains(type)) {
        addError(accumulator, IMAGE, localizationContext, null, INVALID_AMI_INSTANCE_TYPE_COMPATIBILITY_MSG,
                type, image.getVirtualizationType(), imageName);
    }

    if (!ROOT_DEVICE_TYPE.equals(image.getRootDeviceType())) {
        addError(accumulator, IMAGE, localizationContext, null, INVALID_AMI_ROOT_DEVICE_TYPE_MSG, imageName,
                image.getRootDeviceType());
    }
}

From source file:com.cloudera.director.aws.ec2.EC2InstanceTemplateConfigurationValidator.java

License:Apache License

/**
 * Validates the configured availability zone.
 *
 * @param client              the EC2 client
 * @param configuration       the configuration to be validated
 * @param accumulator         the exception condition accumulator
 * @param localizationContext the localization context
 *///w ww  . j  a va  2  s .c  o  m
@VisibleForTesting
void checkAvailabilityZone(AmazonEC2Client client, Configured configuration,
        PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) {

    String zoneName = configuration.getConfigurationValue(AVAILABILITY_ZONE, localizationContext);
    if (zoneName != null) {
        LOG.info(">> Describing zone '{}'", zoneName);

        try {
            DescribeAvailabilityZonesResult result = client
                    .describeAvailabilityZones(new DescribeAvailabilityZonesRequest().withZoneNames(zoneName));

            checkCount(accumulator, AVAILABILITY_ZONE, localizationContext, "Availability zone",
                    result.getAvailabilityZones());
        } catch (AmazonServiceException e) {
            if (e.getErrorCode().equals(INVALID_PARAMETER_VALUE)
                    && e.getMessage().contains(INVALID_AVAILABILITY_ZONE)) {
                addError(accumulator, AVAILABILITY_ZONE, localizationContext, null,
                        INVALID_AVAILABILITY_ZONE_MSG, zoneName);
            } else {
                throw Throwables.propagate(e);
            }
        }
    }
}

From source file:com.cloudera.director.aws.ec2.EC2InstanceTemplateConfigurationValidator.java

License:Apache License

/**
 * Validates the configured placement group.
 *
 * @param client              the EC2 client
 * @param configuration       the configuration to be validated
 * @param accumulator         the exception condition accumulator
 * @param localizationContext the localization context
 *//*from  w w w .java2s  . com*/
@VisibleForTesting
void checkPlacementGroup(AmazonEC2Client client, Configured configuration,
        PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) {

    String placementGroup = configuration.getConfigurationValue(PLACEMENT_GROUP, localizationContext);

    if (placementGroup != null) {
        LOG.info(">> Describing placement group '{}'", placementGroup);

        try {
            DescribePlacementGroupsResult result = client.describePlacementGroups(
                    new DescribePlacementGroupsRequest().withGroupNames(placementGroup));

            checkCount(accumulator, PLACEMENT_GROUP, localizationContext, "Placement group",
                    result.getPlacementGroups());
        } catch (AmazonServiceException e) {
            if (e.getErrorCode().startsWith(INVALID_PLACEMENT_GROUP_ID)) {
                addError(accumulator, PLACEMENT_GROUP, localizationContext, null, INVALID_PLACEMENT_GROUP_MSG,
                        placementGroup);
            } else {
                throw Throwables.propagate(e);
            }
        }
    }
}

From source file:com.cloudera.director.aws.ec2.EC2InstanceTemplateConfigurationValidator.java

License:Apache License

/**
 * Validates the configured subnet ID./*  w  w  w.  j  a  va 2 s . c  o  m*/
 *
 * @param client              the EC2 client
 * @param configuration       the configuration to be validated
 * @param accumulator         the exception condition accumulator
 * @param localizationContext the localization context
 */
@VisibleForTesting
void checkSubnetId(AmazonEC2Client client, Configured configuration,
        PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) {
    String subnetId = configuration.getConfigurationValue(SUBNET_ID, localizationContext);
    LOG.info(">> Describing subnet '{}'", subnetId);

    try {
        DescribeSubnetsResult result = client
                .describeSubnets(new DescribeSubnetsRequest().withSubnetIds(subnetId));
        checkCount(accumulator, SUBNET_ID, localizationContext, "Subnet", result.getSubnets());
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().startsWith(INVALID_SUBNET_ID)) {
            addError(accumulator, SUBNET_ID, localizationContext, null, INVALID_SUBNET_MSG, subnetId);
        } else {
            throw Throwables.propagate(e);
        }
    }
}