Example usage for com.amazonaws AmazonServiceException setStatusCode

List of usage examples for com.amazonaws AmazonServiceException setStatusCode

Introduction

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

Prototype

public void setStatusCode(int statusCode) 

Source Link

Document

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

Usage

From source file:com.msi.dns53.client.DNS53Client.java

License:Apache License

@SuppressWarnings("unchecked")
public void exceptionMapper(ClientResponse response, String resultXml) throws AmazonServiceException {
    ErrorResponsePOJO er = null;/*from  w w  w  .j a v a  2 s.c  o  m*/
    try {
        StringReader reader = new StringReader(resultXml);
        JAXBContext context = JAXBContext.newInstance(ErrorResponsePOJO.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        er = (ErrorResponsePOJO) unmarshaller.unmarshal(reader);
    } catch (JAXBException e) {
        e.printStackTrace();
        throw new AmazonClientException("There was a problem parsing the error response xml with JAXB.", e);
    }
    if (er == null || er.getError() == null || er.getRequestId() == null || er.getError().getCode() == null
            || er.getError().getMessage() == null || er.getError().getType() == null) {
        throw new AmazonClientException(
                "Error response xml did not contain expected elements although it is well formed.");
    }

    String errCode = er.getError().getCode();
    Class<AmazonServiceException> clazz = null;
    Constructor<AmazonServiceException> c = null;
    AmazonServiceException exception = null;
    try {
        String clazzName = ExceptionMap.getExceptionMap().getMap().get(errCode);
        clazz = (Class<AmazonServiceException>) Class.forName(clazzName);
        c = (Constructor<AmazonServiceException>) clazz.getConstructor(String.class);
        exception = (AmazonServiceException) c.newInstance(new Object[] { er.getError().getMessage() });
    } catch (NullPointerException e) {
        exception = new AmazonServiceException(er.getError().getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        throw new AmazonClientException("Client could not determine the type of the error response.");
    }
    if (exception == null) {
        throw new AmazonClientException(
                "Client encountered a problem while it was mapping the error response.");
    }
    exception.setErrorCode(er.getError().getCode());
    ErrorType et = ErrorType.Unknown;
    if ("Sender".equals(er.getError().getType())) {
        et = ErrorType.Service;
    }
    exception.setErrorType(et);
    exception.setRequestId(er.getRequestId());
    exception.setStatusCode(response.getStatus());
    exception.setServiceName("DNS53");
    throw exception;
}

From source file:com.netflix.edda.AwsException.java

License:Apache License

public static void raise(int code, String svc, String reqId, String error, String msg) {
    StringBuffer buf = new StringBuffer().append("Status Code: ").append(code).append(", AWS Service: ")
            .append(svc).append(", AWS Request ID: ").append(reqId).append(", AWS Error Code: ").append(error)
            .append(", AWS Error Message:").append(msg);
    AmazonServiceException e = new AmazonServiceException(buf.toString());
    e.setStatusCode(code);
    e.setServiceName(svc);/*from  ww  w .  j a v  a  2 s.c om*/
    e.setRequestId(reqId);
    e.setErrorCode(error);
    throw e;
}

From source file:com.netflix.edda.EddaAwsClient.java

License:Apache License

protected byte[] doGet(final String uri) {
    try {//from  ww w.  j  a v  a2 s . c  o  m
        return EddaContext.getContext().getRxHttp().get(mkUrl(uri)).flatMap(response -> {
            if (response.getStatus().code() != 200) {
                AmazonServiceException e = new AmazonServiceException("Failed to fetch " + uri);
                e.setStatusCode(response.getStatus().code());
                e.setErrorCode("Edda");
                e.setRequestId(uri);
                return rx.Observable.error(e);
            }
            return response.getContent().reduce(new ByteArrayOutputStream(), (out, bb) -> {
                try {
                    bb.readBytes(out, bb.readableBytes());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                return out;
            }).map(out -> {
                return out.toByteArray();
            });
        }).toBlocking().toFuture().get(2, TimeUnit.MINUTES);
    } catch (Exception e) {
        throw new RuntimeException("failed to get url: " + uri, e);
    }
}

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

License:Apache License

private <T> List<T> describe(AmazonWebServiceRequest request, String idKey, final String object,
        final Class<T> singleType) {
    lastModified.set(null);/*from  www. j a v  a 2 s . com*/
    try {
        JavaType singleMeta = objectMapper.getTypeFactory().constructParametrizedType(Metadata.class,
                Metadata.class, singleType);
        Collection<String> ids = getRequestIds(request, idKey);
        Long mtime = null;
        List<T> results = new ArrayList<>();
        if (ids.isEmpty()) {
            final byte[] json = getJson(object, null);
            JavaType listMeta = objectMapper.getTypeFactory().constructParametrizedType(List.class, List.class,
                    singleMeta);
            List<Metadata<T>> metadataResults = objectMapper.readValue(json, listMeta);
            for (Metadata<T> meta : metadataResults) {
                mtime = mtime == null ? meta.mtime : Math.min(mtime, meta.mtime);
                results.add(meta.data);
            }
        } else {
            for (String id : ids) {
                final byte[] json = getJson(object, id);
                Metadata<T> result = objectMapper.readValue(json, singleMeta);
                mtime = mtime == null ? result.mtime : Math.min(mtime, result.mtime);
                results.add(result.data);
            }
        }
        lastModified.set(mtime);
        return results;
    } catch (Exception e) {
        AmazonServiceException ex = new AmazonServiceException(
                "400 Bad Request -- Edda could not find one of the managed objects requested.", e);
        ex.setStatusCode(400);
        ex.setServiceName(serviceName);
        ex.setErrorType(AmazonServiceException.ErrorType.Unknown);
        throw ex;
    }
}

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

License:Apache License

private <T> List<T> describe(AmazonWebServiceRequest request, String idKey, final String object,
        final Class<T> singleType) {
    lastModified.set(null);//  w ww.  ja va2  s.com
    final Map<String, String> metricTags = new HashMap<>(this.metricTags);
    metricTags.put("collection", object);
    try {
        final Collection<String> ids = getRequestIds(request, idKey);
        metricTags.put("collectionMode", ids.isEmpty() ? "full" : "byId");
        final JavaType singleMeta = objectMapper.getTypeFactory().constructParametrizedType(Metadata.class,
                Metadata.class, singleType);
        Long mtime = null;
        final List<T> results = new ArrayList<>();

        final Id deserializeJsonTimer = registry.createId("edda.deserializeJson", metricTags);
        final Id resultSizeCounter = registry.createId("edda.resultSize", metricTags);
        if (ids.isEmpty()) {
            HttpEntity entity = getHttpEntity(metricTags, object, null);
            try {
                final JavaType listMeta = objectMapper.getTypeFactory().constructParametrizedType(List.class,
                        List.class, singleMeta);
                final List<Metadata<T>> metadataResults = registry.timer(deserializeJsonTimer)
                        .record(() -> objectMapper.readValue(entity.getContent(), listMeta));
                for (Metadata<T> meta : metadataResults) {
                    mtime = mtime == null ? meta.mtime : Math.min(mtime, meta.mtime);
                    results.add(meta.data);
                }
            } finally {
                EntityUtils.consume(entity);
            }
        } else {
            for (String id : ids) {
                HttpEntity entity = getHttpEntity(metricTags, object, id);
                try {
                    final Metadata<T> result = registry.timer(deserializeJsonTimer)
                            .record(() -> objectMapper.readValue(entity.getContent(), singleMeta));
                    mtime = mtime == null ? result.mtime : Math.min(mtime, result.mtime);
                    results.add(result.data);
                } finally {
                    EntityUtils.consume(entity);
                }
            }
        }
        registry.counter(resultSizeCounter).increment(results.size());
        lastModified.set(mtime);
        return results;
    } catch (Exception e) {
        log.error(e.getMessage() + " (retries exhausted)");

        registry.counter(registry.createId("edda.failures", metricTags)).increment();
        final AmazonServiceException ex = new AmazonServiceException(
                "400 Bad Request -- Edda could not find one of the managed objects requested.", e);
        ex.setStatusCode(400);
        ex.setServiceName(serviceName);
        ex.setErrorType(AmazonServiceException.ErrorType.Unknown);
        throw ex;
    }
}

From source file:com.netflix.spinnaker.kork.aws.AwsMetricsSupport.java

License:Apache License

static AmazonServiceException amazonServiceException(Exception exception, String serviceName, int statusCode) {
    if (exception instanceof AmazonServiceException) {
        return (AmazonServiceException) exception;
    }/*from   w ww.  j  av  a 2 s  .c  o  m*/

    final AmazonServiceException ase = new AmazonServiceException(exception.getMessage(), exception);
    ase.setStatusCode(statusCode);
    ase.setErrorCode(DEFAULT_UNKNOWN);
    ase.setServiceName(serviceName);
    ase.setErrorType(AmazonServiceException.ErrorType.Unknown);
    return ase;
}

From source file:edu.si.services.beans.cameratrap.AmazonS3ClientMock.java

License:Apache License

@Override
public ObjectListing listObjects(ListObjectsRequest listObjectsRequest)
        throws AmazonClientException, AmazonServiceException {
    if ("nonExistingBucket".equals(listObjectsRequest.getBucketName()) && !nonExistingBucketCreated) {
        AmazonServiceException ex = new AmazonServiceException("Unknown bucket");
        ex.setStatusCode(404);
        throw ex;
    }//from  w  w  w .j  ava  2 s  .c om
    ObjectListing objectListing = new ObjectListing();
    for (int index = 0; index < objects.size(); index++) {
        if (objects.get(index).getBucketName().equals(listObjectsRequest.getBucketName())) {
            S3ObjectSummary s3ObjectSummary = new S3ObjectSummary();
            s3ObjectSummary.setBucketName(objects.get(index).getBucketName());
            s3ObjectSummary.setKey(objects.get(index).getKey());

            objectListing.getObjectSummaries().add(s3ObjectSummary);
        }
    }

    return objectListing;
}

From source file:org.apache.camel.component.aws.s3.AmazonS3ClientMock.java

License:Apache License

@Override
public ObjectListing listObjects(ListObjectsRequest listObjectsRequest)
        throws AmazonClientException, AmazonServiceException {
    if ("nonExistingBucket".equals(listObjectsRequest.getBucketName()) && !nonExistingBucketCreated) {
        AmazonServiceException ex = new AmazonServiceException("Unknow bucket");
        ex.setStatusCode(404);
        throw ex;
    }/* www. j  a  va 2  s .  com*/

    ObjectListing objectListing = new ObjectListing();
    int capacity = listObjectsRequest.getMaxKeys();

    for (int index = 0; index < objects.size() && index < capacity; index++) {
        S3ObjectSummary s3ObjectSummary = new S3ObjectSummary();
        s3ObjectSummary.setBucketName(objects.get(index).getBucketName());
        s3ObjectSummary.setKey(objects.get(index).getKey());

        objectListing.getObjectSummaries().add(s3ObjectSummary);
    }

    return objectListing;
}

From source file:org.finra.dm.dao.impl.MockEc2OperationsImpl.java

License:Apache License

/**
 * In-memory implementation of describeSubnets. Returns the subnets from the pre-configured subnets.
 * The method can be ordered to throw an AmazonServiceException with a specified error code by specifying a subnet ID with prefix "throw." followed by a
 * string indicating the error code to throw. The exception thrown in this manner will always set the status code to 500.
 *///from w w w.  j ava 2 s. c  o m
@Override
public DescribeSubnetsResult describeSubnets(AmazonEC2Client ec2Client,
        DescribeSubnetsRequest describeSubnetsRequest) {
    List<Subnet> subnets = new ArrayList<>();

    List<String> requestedSubnetIds = describeSubnetsRequest.getSubnetIds();

    // add all subnets if request is empty (this is AWS behavior)
    if (requestedSubnetIds.isEmpty()) {
        requestedSubnetIds.addAll(mockSubnets.keySet());
    }

    for (String requestedSubnetId : requestedSubnetIds) {
        MockSubnet mockSubnet = mockSubnets.get(requestedSubnetId);

        // Throw exception if any of the subnet ID do not exist
        if (mockSubnet == null) {
            AmazonServiceException amazonServiceException;

            if (requestedSubnetId.startsWith("throw.")) {
                String errorCode = requestedSubnetId.substring("throw.".length());

                amazonServiceException = new AmazonServiceException(errorCode);
                amazonServiceException.setErrorCode(errorCode);
                amazonServiceException.setStatusCode(500);
            } else {
                amazonServiceException = new AmazonServiceException(
                        "The subnet ID '" + requestedSubnetId + "' does not exist");
                amazonServiceException.setErrorCode(Ec2DaoImpl.ERROR_CODE_SUBNET_ID_NOT_FOUND);
                amazonServiceException.setStatusCode(400);
            }

            throw amazonServiceException;
        }

        subnets.add(mockSubnet.toAwsObject());
    }

    DescribeSubnetsResult describeSubnetsResult = new DescribeSubnetsResult();
    describeSubnetsResult.setSubnets(subnets);
    return describeSubnetsResult;
}

From source file:org.finra.dm.dao.impl.MockEmrOperationsImpl.java

License:Apache License

@Override
public String runEmrJobFlow(AmazonElasticMapReduceClient emrClient, RunJobFlowRequest jobFlowRequest) {
    String clusterStatus = ClusterState.BOOTSTRAPPING.toString();

    if (StringUtils.isNotBlank(jobFlowRequest.getAmiVersion())) {
        if (jobFlowRequest.getAmiVersion().equals(MockAwsOperationsHelper.AMAZON_THROTTLING_EXCEPTION)) {
            AmazonServiceException throttlingException = new AmazonServiceException(
                    "test throttling exception");
            throttlingException.setErrorCode("ThrottlingException");

            throw throttlingException;
        } else if (jobFlowRequest.getAmiVersion().equals(MockAwsOperationsHelper.AMAZON_BAD_REQUEST)) {
            AmazonServiceException badRequestException = new AmazonServiceException(
                    MockAwsOperationsHelper.AMAZON_BAD_REQUEST);
            badRequestException.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            throw badRequestException;
        } else if (jobFlowRequest.getAmiVersion().equals(MockAwsOperationsHelper.AMAZON_NOT_FOUND)) {
            AmazonServiceException notFoundException = new AmazonServiceException(
                    MockAwsOperationsHelper.AMAZON_NOT_FOUND);
            notFoundException.setStatusCode(HttpStatus.SC_NOT_FOUND);
            throw notFoundException;
        } else if (jobFlowRequest.getAmiVersion().equals(MockAwsOperationsHelper.AMAZON_SERVICE_EXCEPTION)) {
            throw new AmazonServiceException(MockAwsOperationsHelper.AMAZON_SERVICE_EXCEPTION);
        } else if (jobFlowRequest.getAmiVersion()
                .equals(MockAwsOperationsHelper.AMAZON_CLUSTER_STATUS_WAITING)) {
            clusterStatus = ClusterState.WAITING.toString();
        } else if (jobFlowRequest.getAmiVersion()
                .equals(MockAwsOperationsHelper.AMAZON_CLUSTER_STATUS_RUNNING)) {
            clusterStatus = ClusterState.RUNNING.toString();
        }/* w  w  w  .  jav a2s  .  c  o  m*/
    }

    return createNewCluster(jobFlowRequest, clusterStatus).getJobFlowId();
}