private HashMap<String, Object> extractHttpResponseInformation(HttpResponse httpResponse) { HashMap<String, Object> ret = new HashMap<>(); HashMap<String, Object> response = new HashMap<>(); response.put(STATUS_SUBSEGMENT_KEY, httpResponse.getStatusCode()); try { if (null != httpResponse.getHeaders().get(CONTENT_LENGTH_HEADER_KEY) ) { response.put(CONTENT_LENGTH_SUBSEGMENT_KEY, Long.parseLong(httpResponse.getHeaders().get(CONTENT_LENGTH_HEADER_KEY))); } } catch (NumberFormatException nfe) { logger.warn("Unable to parse Content-Length header.", nfe); } ret.put(RESPONSE_SUBSEGMENT_KEY, response); return ret; }
@Test public void testConvert() throws IOException { Response responseMock = mock(Response.class); HttpHeaders headers = new DefaultHttpHeaders(); headers.add(TEST_KEY_A, TEST_VALUE_B); headers.add(TEST_KEY_C, TEST_VALUE_D); when(responseMock.getHeaders()).thenReturn(headers); when(responseMock.getStatusCode()).thenReturn(STATUS_CODE); when(responseMock.getStatusText()).thenReturn(STATUS_TEXT); when(responseMock.getResponseBodyAsStream()).thenReturn( new ByteArrayInputStream(ENCODED_BODY.getBytes(StandardCharsets.UTF_8)) ); BiFunction<Response, Request, HttpResponse> converter = new AsyncResponseConverter(); HttpResponse awsResponse = converter.apply(responseMock, null); assertThat(awsResponse.getHeaders().get(TEST_KEY_A)).isEqualTo(TEST_VALUE_B); assertThat(awsResponse.getHeaders().get(TEST_KEY_C)).isEqualTo(TEST_VALUE_D); assertThat(awsResponse.getStatusCode()).isEqualTo(STATUS_CODE); assertThat(awsResponse.getStatusText()).isEqualTo(STATUS_TEXT); assertThat(new BufferedReader(new InputStreamReader(awsResponse.getContent())).readLine()) .isEqualTo(ENCODED_BODY); }
/** * Used to log the "x-amzn-RequestId" header at DEBUG level, if any, from the response. This * method assumes the apache httpClientSettings request/response has just been successfully * executed. The request id is logged using the "com.amazonaws.requestId" logger if it was * enabled at DEBUG level; otherwise, it is logged at DEBUG level using the * "com.amazonaws.request" logger. * * @return true if the AWS request id is available from the httpClientSettings header; false * otherwise. */ private boolean logHeaderRequestId(final HttpResponse response) { final String reqIdHeader = response.getHeaders() .get(HttpResponseHandler.X_AMZN_REQUEST_ID_HEADER); final boolean isHeaderReqIdAvail = reqIdHeader != null; if (requestIdLog.isDebugEnabled() || requestLog.isDebugEnabled()) { final String msg = HttpResponseHandler.X_AMZN_REQUEST_ID_HEADER + ": " + (isHeaderReqIdAvail ? reqIdHeader : "not available"); if (requestIdLog.isDebugEnabled()) { requestIdLog.debug(msg); } else { requestLog.debug(msg); } } return isHeaderReqIdAvail; }
public static <T> HttpResponseHandler<AmazonWebServiceResponse<T>> responseHandler(final FunctionWithException<HttpResponse, T> handle) { return new HttpResponseHandler<AmazonWebServiceResponse<T>>() { @Override public AmazonWebServiceResponse<T> handle(HttpResponse response) throws Exception { AmazonWebServiceResponse<T> resp = new AmazonWebServiceResponse<T>(); resp.setResult(handle.apply(response)); return resp; } @Override public boolean needsConnectionLeftOpen() { return false; } }; }
@Test public void beforeUnmarshalling_ModifiedResponseForwardedToNextInChain() { final HttpResponse origHttpResponse = mock(HttpResponse.class); final HttpResponse afterFirstHttpResponse = mock(HttpResponse.class); final HttpResponse afterSecondHttpResponse = mock(HttpResponse.class); final HttpResponse afterThirdHttpResponse = mock(HttpResponse.class); doReturn(afterThirdHttpResponse).when(third).beforeUnmarshalling(request, origHttpResponse); doReturn(afterSecondHttpResponse).when(second).beforeUnmarshalling(request, afterThirdHttpResponse); doReturn(afterFirstHttpResponse).when(first).beforeUnmarshalling(request, afterSecondHttpResponse); assertEquals(afterFirstHttpResponse, stackedRequestHandler.beforeUnmarshalling(request, origHttpResponse)); InOrder inOrder = inOrder(third, second, first); inOrder.verify(third).beforeUnmarshalling(request, origHttpResponse); inOrder.verify(second).beforeUnmarshalling(request, afterThirdHttpResponse); inOrder.verify(first).beforeUnmarshalling(request, afterSecondHttpResponse); }
@Override public AmazonWebServiceResponse<HeadBucketResult> handle(HttpResponse response) throws Exception { final AmazonWebServiceResponse<HeadBucketResult> awsResponse = new AmazonWebServiceResponse<HeadBucketResult>(); final HeadBucketResult result = new HeadBucketResult(); result.setBucketRegion(response.getHeaders().get(Headers.S3_BUCKET_REGION)); if (!StringUtils.isNullOrEmpty(response.getHeaders().get(Headers.IBM_SSE_KP_ENABLED))){ result.setIBMSSEKPEnabled(Boolean.parseBoolean(response.getHeaders().get(Headers.IBM_SSE_KP_ENABLED))); } if (!StringUtils.isNullOrEmpty(response.getHeaders().get(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN))){ result.setIBMSSEKPCrk(response.getHeaders().get(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN)); } awsResponse.setResult(result); return awsResponse; }
private AmazonS3Exception createExceptionFromHeaders( HttpResponse errorResponse, String errorResponseXml) { final Map<String, String> headers = errorResponse.getHeaders(); final int statusCode = errorResponse.getStatusCode(); final AmazonS3ExceptionBuilder exceptionBuilder = new AmazonS3ExceptionBuilder(); exceptionBuilder.setErrorMessage(errorResponse.getStatusText()); exceptionBuilder.setErrorResponseXml(errorResponseXml); exceptionBuilder.setStatusCode(statusCode); exceptionBuilder .setExtendedRequestId(headers.get(Headers.EXTENDED_REQUEST_ID)); exceptionBuilder.setRequestId(headers.get(Headers.REQUEST_ID)); exceptionBuilder.setCloudFrontId(headers.get(Headers.CLOUD_FRONT_ID)); exceptionBuilder .setErrorCode(statusCode + " " + errorResponse.getStatusText()); exceptionBuilder.addAdditionalDetail(Headers.S3_BUCKET_REGION, errorResponse.getHeaders().get(Headers.S3_BUCKET_REGION)); return exceptionBuilder.build(); }
/** * @see com.amazonaws.http.HttpResponseHandler#handle(com.amazonaws.http.HttpResponse) */ public AmazonWebServiceResponse<T> handle(HttpResponse response) throws Exception { AmazonWebServiceResponse<T> awsResponse = parseResponseMetadata(response); responseHeaders = response.getHeaders(); if (responseUnmarshaller != null) { log.trace("Beginning to parse service response XML"); T result = responseUnmarshaller.unmarshall(response.getContent()); log.trace("Done parsing service response XML"); awsResponse.setResult(result); if (result instanceof ObjectListing) { if (!StringUtils.isNullOrEmpty(responseHeaders.get(Headers.IBM_SSE_KP_ENABLED))){ ((ObjectListing) result).setIBMSSEKPEnabled(Boolean.parseBoolean(responseHeaders.get(Headers.IBM_SSE_KP_ENABLED))); } if (!StringUtils.isNullOrEmpty(responseHeaders.get(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN))) { ((ObjectListing) result).setIBMSSEKPCrk(responseHeaders.get(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN)); } } } return awsResponse; }
/** * Test the IBM_SSE_KP_ENABLED & IBM_SSE_KP_CRK are set in the ObjectLIsting * response object * @throws Exception * */ @Test public void testHeadersAddedToObjectListing() throws Exception { Unmarshaller<ObjectListing, InputStream> unmarshaller = new Unmarshallers.ListObjectsUnmarshaller(false); S3XmlResponseHandler xmlResponseHandler = new S3XmlResponseHandler<ObjectListing>(unmarshaller); HttpResponse httpResponse = new HttpResponse(null, null); httpResponse.addHeader(Headers.IBM_SSE_KP_ENABLED, "True"); httpResponse.addHeader(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN, "123456"); InputStream is = new ByteArrayInputStream(getXmlContent().getBytes());; httpResponse.setContent(is); AmazonWebServiceResponse<ObjectListing> objectListing = xmlResponseHandler.handle(httpResponse); assertEquals(objectListing.getResult().getIBMSSEKPCrk(), "123456"); assertEquals(objectListing.getResult().getIBMSSEKPEnabled(), true); }
/** * Test the IBM_SSE_KP_ENABLED & IBM_SSE_KP_CRK null headers are handled * * @throws Exception * */ @Test public void testNullKPHeadersAreHandled() throws Exception { Unmarshaller<ObjectListing, InputStream> unmarshaller = new Unmarshallers.ListObjectsUnmarshaller(false); S3XmlResponseHandler xmlResponseHandler = new S3XmlResponseHandler<ObjectListing>(unmarshaller); HttpResponse httpResponse = new HttpResponse(null, null); httpResponse.addHeader(Headers.IBM_SSE_KP_ENABLED, null); httpResponse.addHeader(Headers.IBM_SSE_KP_CRK, null); InputStream is = new ByteArrayInputStream(getXmlContent().getBytes());; httpResponse.setContent(is); AmazonWebServiceResponse<ObjectListing> objectListing = xmlResponseHandler.handle(httpResponse); assertEquals(objectListing.getResult().getIBMSSEKPCrk(), null); assertEquals(objectListing.getResult().getIBMSSEKPEnabled(), false); }
/** * Test the IBM_SSE_KP_ENABLED & IBM_SSE_KP_CRK empty headers are handled * * @throws Exception * */ @Test public void testEmptyKPHeadersAreHandled() throws Exception { Unmarshaller<ObjectListing, InputStream> unmarshaller = new Unmarshallers.ListObjectsUnmarshaller(false); S3XmlResponseHandler xmlResponseHandler = new S3XmlResponseHandler<ObjectListing>(unmarshaller); HttpResponse httpResponse = new HttpResponse(null, null); InputStream is = new ByteArrayInputStream(getXmlContent().getBytes());; httpResponse.setContent(is); AmazonWebServiceResponse<ObjectListing> objectListing = xmlResponseHandler.handle(httpResponse); assertEquals(objectListing.getResult().getIBMSSEKPCrk(), null); assertEquals(objectListing.getResult().getIBMSSEKPEnabled(), false); }
/** * Test the IBM_SSE_KP_CRK empty header is handled * * @throws Exception * */ @Test public void testOnlyKPEnabledHeaderIsSet() throws Exception { Unmarshaller<ObjectListing, InputStream> unmarshaller = new Unmarshallers.ListObjectsUnmarshaller(false); S3XmlResponseHandler xmlResponseHandler = new S3XmlResponseHandler<ObjectListing>(unmarshaller); HttpResponse httpResponse = new HttpResponse(null, null); httpResponse.addHeader(Headers.IBM_SSE_KP_ENABLED, "True"); InputStream is = new ByteArrayInputStream(getXmlContent().getBytes());; httpResponse.setContent(is); AmazonWebServiceResponse<ObjectListing> objectListing = xmlResponseHandler.handle(httpResponse); assertEquals(objectListing.getResult().getIBMSSEKPCrk(), null); assertEquals(objectListing.getResult().getIBMSSEKPEnabled(), true); }
/** * Test the IBM_SSE_KP_CRK empty header is handled * * @throws Exception * */ @Test public void testOnlyCRKHeaderIsSet() throws Exception { Unmarshaller<ObjectListing, InputStream> unmarshaller = new Unmarshallers.ListObjectsUnmarshaller(false); S3XmlResponseHandler xmlResponseHandler = new S3XmlResponseHandler<ObjectListing>(unmarshaller); HttpResponse httpResponse = new HttpResponse(null, null); httpResponse.addHeader(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN, "34567"); InputStream is = new ByteArrayInputStream(getXmlContent().getBytes());; httpResponse.setContent(is); AmazonWebServiceResponse<ObjectListing> objectListing = xmlResponseHandler.handle(httpResponse); assertEquals(objectListing.getResult().getIBMSSEKPCrk(), "34567"); assertEquals(objectListing.getResult().getIBMSSEKPEnabled(), false); }
@Override public DescribeStreamResult describeStream(String streamName, String exclusiveStartShardId) { int nextShardId = 0; if (exclusiveStartShardId != null) { nextShardId = parseInt(exclusiveStartShardId) + 1; } boolean hasMoreShards = nextShardId + 1 < shardedData.size(); List<Shard> shards = new ArrayList<>(); if (nextShardId < shardedData.size()) { shards.add(new Shard().withShardId(Integer.toString(nextShardId))); } HttpResponse response = new HttpResponse(null, null); response.setStatusCode(200); DescribeStreamResult result = new DescribeStreamResult(); result.setSdkHttpMetadata(SdkHttpMetadata.from(response)); result.withStreamDescription( new StreamDescription() .withHasMoreShards(hasMoreShards) .withShards(shards) .withStreamName(streamName)); return result; }
/** * Delete the elasticsearch index. * @param name Name of the index. */ @Override public void delete() { final AwsHttpRequest<HttpResponse> deleteIndex = new SignedRequest<>( new AwsDelete<>( new EsHttpRequest<>( this.esEdp, this.indexName, new SimpleAwsResponseHandler(false), new SimpleAwsErrorHandler(false) ) ), this.accesskey, this.secretKey, this.reg ); deleteIndex.perform(); }
@Override public void delete(final String type, final String id) { final AwsHttpRequest<HttpResponse> deleteDoc = new SignedRequest<>( new AwsDelete<>( new EsHttpRequest<>( this.esEdp, this.indexName + "/" + type + "/" + id, new SimpleAwsResponseHandler(false), new SimpleAwsErrorHandler(false) ) ), this.accesskey, this.secretKey, this.reg ); deleteDoc.perform(); }
@Override public HttpResponse handle(HttpResponse response) { int status = response.getStatusCode(); if(status < 200 || status >= 300) { String content; final StringWriter writer = new StringWriter(); try { IOUtils.copy(response.getContent(), writer, "UTF-8"); content = writer.toString(); } catch (final IOException e) { content = "Couldn't get response content!"; } AmazonServiceException ase = new AmazonServiceException(content); ase.setStatusCode(status); throw ase; } return response; }
/** * SearchResponseHandler can build the search results page from an * aws HttpResponse * @throws Exception If something goes wrong. */ @Test public void buildsSearchResultsPage() throws Exception { HttpResponse response = Mockito.mock(HttpResponse.class); Mockito.when(response.getStatusCode()).thenReturn(HttpURLConnection.HTTP_OK); Mockito.when(response.getContent()).thenReturn( new FileInputStream( new File("src/test/resources/esSearchResponse.json") ) ); SearchResultsPage page = new SearchResponseHandler().handle(response); assertTrue(page.totalHits() == 27); assertTrue(page.results().size() == 10); SearchResult first = page.results().get(0); assertTrue(first.link().equals("http://amihaiemil.com/page.html")); assertTrue(first.category().equals("tech")); SearchResult last = page.results().get(9); assertTrue(last.link().equals("http://amihaiemil.com/some/other/page.html")); assertTrue(last.category().equals("mischelaneous")); }
/** * SimpleAwsResponseHandler returns the plain response as is, since the status is * in range [200, 300) * @throws Exception If something goes wrong. */ @Test public void responseStatusInRange() throws Exception { HttpResponse response = Mockito.mock(HttpResponse.class); Mockito.when(response.getStatusCode()).thenReturn(HttpURLConnection.HTTP_OK); String content = "This content should not be affected!"; Mockito.when(response.getContent()).thenReturn( new ByteArrayInputStream(content.getBytes()) ); SimpleAwsResponseHandler handler = new SimpleAwsResponseHandler(false); assertFalse(handler.needsConnectionLeftOpen()); HttpResponse handled = handler.handle(response); assertTrue(handled.getStatusCode() == HttpURLConnection.HTTP_OK); String expected = new String(IOUtils.toByteArray(handled.getContent())); assertTrue(expected.equals(content)); }
/** * {@link SimpleAwsResponseHandler} can throw AmazonServiceException * in case the response status is not in the expected range. */ @Test public void throwsAwsExceptionOnBadStatus() { HttpResponse response = Mockito.mock(HttpResponse.class); Mockito.when(response.getStatusCode()).thenReturn(HttpURLConnection.HTTP_BAD_METHOD); String content = "bad request message"; Mockito.when(response.getContent()) .thenReturn( new ByteArrayInputStream(content.getBytes()) ); try { new SimpleAwsResponseHandler(true).handle(response); fail("AmazonServiceException should have been thrown!"); } catch (AmazonServiceException awsEx) { assertTrue(awsEx.getErrorMessage().equals(content)); assertTrue(awsEx.getStatusCode() == HttpURLConnection.HTTP_BAD_METHOD); } }
private void execRequest(String endpoint, int status) { AWSRequestMetrics metrics = new AWSRequestMetricsFullSupport(); metrics.addProperty(AWSRequestMetrics.Field.ServiceName, "AmazonCloudWatch"); metrics.addProperty(AWSRequestMetrics.Field.ServiceEndpoint, endpoint); metrics.addProperty(AWSRequestMetrics.Field.StatusCode, "" + status); if (status == 503) { metrics.addProperty(AWSRequestMetrics.Field.AWSErrorCode, "Throttled"); } String counterName = "BytesProcessed"; String timerName = "ClientExecuteTime"; metrics.setCounter(counterName, 12345); metrics.getTimingInfo().addSubMeasurement(timerName, TimingInfo.unmodifiableTimingInfo(100000L, 200000L)); Request<?> req = new DefaultRequest(new ListMetricsRequest(), "AmazonCloudWatch"); req.setAWSRequestMetrics(metrics); req.setEndpoint(URI.create(endpoint)); HttpResponse hr = new HttpResponse(req, new HttpPost(endpoint)); hr.setStatusCode(status); Response<?> resp = new Response<>(null, new HttpResponse(req, new HttpPost(endpoint))); collector.collectMetrics(req, resp); }
@Override public CreateSpeechResult unmarshall(HttpResponse response) { String requestId = response.getHeaders().get(HEADER_AMZN_REQUEST_ID); String ttsRequestId = response.getHeaders().get(HEADER_IVONA_TTS_REQUEST_ID); String contentType = response.getHeaders().get(HEADER_CONTENT_TYPE); int requestCharacters = Integer.parseInt(response.getHeaders().get(HEADER_TTS_REQUEST_CHARACTERS)); int requestUnits = Integer.parseInt(response.getHeaders().get(HEADER_TTS_REQUEST_UNITS)); CreateSpeechResult createSpeechResult = new CreateSpeechResult(); createSpeechResult.setRequestId(requestId); createSpeechResult.setTtsRequestId(ttsRequestId); createSpeechResult.setContentType(contentType); createSpeechResult.setTtsRequestCharacters(requestCharacters); createSpeechResult.setTtsRequestUnits(requestUnits); createSpeechResult.setBody(response.getContent()); return createSpeechResult; }
@Override public ResponseT parseHttpResponse(Response response) throws Exception { HttpResponse httpResponse = responseConverter.apply(response, awsHttpRequest); int statusCode = httpResponse.getStatusCode(); if (HTTP_STATUS_RANGE_SUCCESS.contains(statusCode)) { AmazonWebServiceResponse<ResponseT> awsResponse = staxResponseHandler.handle(httpResponse); return awsResponse.getResult(); } else { throw errorResponseHandler.handle(httpResponse); } }
public HttpResponse apply(Response asyncResponse, Request originalRequest) { HttpResponse output = new HttpResponse(originalRequest, null); output.setStatusCode(asyncResponse.getStatusCode()); output.setStatusText(asyncResponse.getStatusText()); output.setContent(asyncResponse.getResponseBodyAsStream()); asyncResponse.getHeaders().forEach((header) -> output.addHeader(header.getKey(), header.getValue())); return output; }
public JsonUnmarshallerContextImpl(JsonParser jsonParser, Map<Class<?>, Unmarshaller<?, JsonUnmarshallerContext>> mapper, Map<UnmarshallerType, Unmarshaller<?, JsonUnmarshallerContext>> customUnmarshallerMap, HttpResponse httpResponse) { this.jsonParser = jsonParser; this.unmarshallerMap = mapper; this.customUnmarshallerMap = customUnmarshallerMap; this.httpResponse = httpResponse; }
/** * Static factory method to create a JsonContent object from the contents of the HttpResponse * provided */ public static JsonContent createJsonContent(HttpResponse httpResponse, JsonFactory jsonFactory) { byte[] rawJsonContent = null; try { if (httpResponse.getContent() != null) { rawJsonContent = IOUtils.toByteArray(httpResponse.getContent()); } } catch (Exception e) { LOG.info("Unable to read HTTP response content", e); } return new JsonContent(rawJsonContent, new ObjectMapper(jsonFactory) .configure(JsonParser.Feature.ALLOW_COMMENTS, true)); }
@Override public T handle(HttpResponse response) throws Exception { final AmazonWebServiceResponse<T> awsResponse = delegate.handle(response); if (awsResponse == null) { throw new RuntimeException("Unable to unmarshall response metadata. Response Code: " + response.getStatusCode() + ", Response Text: " + response.getStatusText()); } AmazonWebServiceRequest userRequest = request.getOriginalRequest(); if (userRequest.getCloneRoot() != null) { userRequest = userRequest.getCloneRoot(); } responseMetadataCache.add(userRequest, awsResponse.getResponseMetadata()); final String awsRequestId = awsResponse.getRequestId(); if (requestLog.isDebugEnabled()) { requestLog .debug("Received successful response: " + response.getStatusCode() + ", AWS Request ID: " + awsRequestId); } if (!logHeaderRequestId(response)) { // Logs the AWS request ID extracted from the payload if // it is not available from the response header. logResponseRequestId(awsRequestId); } awsRequestMetrics.addProperty(AWSRequestMetrics.Field.AWSRequestID, awsRequestId); return fillInResponseMetadata(awsResponse, response); }
@SuppressWarnings("unchecked") private <T> T fillInResponseMetadata(AmazonWebServiceResponse<T> awsResponse, HttpResponse httpResponse) { final T result = awsResponse.getResult(); if (result instanceof AmazonWebServiceResult<?>) { ((AmazonWebServiceResult) result) .setSdkResponseMetadata(awsResponse.getResponseMetadata()) .setSdkHttpMetadata(SdkHttpMetadata.from(httpResponse)); } return result; }
@Override public String parseErrorCode(HttpResponse response, JsonContent jsonContents) { IonReader reader = ionSystem.newReader(jsonContents.getRawContent()); try { IonType type = reader.next(); if (type != IonType.STRUCT) { throw new SdkClientException(String.format("Can only get error codes from structs (saw %s), request id %s", type, getRequestId(response))); } boolean errorCodeSeen = false; String errorCode = null; String[] annotations = reader.getTypeAnnotations(); for (String annotation : annotations) { if (annotation.startsWith(TYPE_PREFIX)) { if (errorCodeSeen) { throw new SdkClientException(String.format("Multiple error code annotations found for request id %s", getRequestId(response))); } else { errorCodeSeen = true; errorCode = annotation.substring(TYPE_PREFIX.length()); } } } return errorCode; } finally { IOUtils.closeQuietly(reader, log); } }
/** * Parse the error message from the response. * * @return Error Code of exceptional response or null if it can't be determined */ public String parseErrorMessage(HttpResponse httpResponse, JsonNode jsonNode) { // If X_AMZN_ERROR_MESSAGE is present, prefer that. Otherwise check the JSON body. final String headerMessage = httpResponse.getHeader(X_AMZN_ERROR_MESSAGE); if (headerMessage != null) { return headerMessage; } for (String field : errorMessageJsonLocations) { JsonNode value = jsonNode.get(field); if (value != null && value.isTextual()) { return value.asText(); } } return null; }
@Override public String parseErrorCode(HttpResponse response, JsonContent jsonContent) { for (ErrorCodeParser parser : parsers) { String errorCode = parser.parseErrorCode(response, jsonContent); if (errorCode != null) { return errorCode; } } return null; }
/** * Parse the error code from the response. * * @return Error Code of exceptional response or null if it can't be determined */ public String parseErrorCode(HttpResponse response, JsonContent jsonContent) { String errorCodeFromHeader = parseErrorCodeFromHeader(response.getHeaders()); if (errorCodeFromHeader != null) { return errorCodeFromHeader; } else if (jsonContent != null) { return parseErrorCodeFromContents(jsonContent.getJsonNode()); } else { return null; } }
@Override public HttpResponse beforeUnmarshalling(Request<?> request, HttpResponse origHttpResponse) { HttpResponse toReturn = origHttpResponse; for(RequestHandler2 handler : reverseOrderRequestHandlers) { toReturn = handler.beforeUnmarshalling(request, toReturn); } return toReturn; }
public static HttpResponseHandler<AmazonWebServiceResponse<String>> stringResponseHandler() { return responseHandler(new FunctionWithException<HttpResponse, String>() { @Override public String apply(HttpResponse in) throws Exception { return IOUtils.toString(in.getContent()); } }); }
@Test public void handlesErrorsUsingHttpHeader() throws Exception { IonStruct payload = createPayload(); HttpResponse error = createResponse(payload); error.addHeader("x-amzn-ErrorType", ERROR_TYPE); AmazonServiceException exception = handleError(error); assertThat(exception, instanceOf(InvalidParameterException.class)); assertEquals(ERROR_MESSAGE, exception.getErrorMessage()); }
@Test public void handlesErrorsUsingMagicField() throws Exception { IonStruct payload = createPayload(); payload.add("__type", system.newString(ERROR_TYPE)); HttpResponse error = createResponse(payload); AmazonServiceException exception = handleError(error); assertThat(exception, instanceOf(InvalidParameterException.class)); assertEquals(ERROR_MESSAGE, exception.getErrorMessage()); }
@Test public void handlesErrorsUsingAnnotation() throws Exception { IonStruct payload = createPayload(); payload.addTypeAnnotation(ERROR_PREFIX + ERROR_TYPE); HttpResponse error = createResponse(payload); AmazonServiceException exception = handleError(error); assertThat(exception, instanceOf(InvalidParameterException.class)); assertEquals(ERROR_MESSAGE, exception.getErrorMessage()); }
@Test(expected = AmazonClientException.class) public void rejectPayloadsWithMultipleErrorAnnotations() throws Exception { IonStruct payload = createPayload(); payload.addTypeAnnotation(ERROR_PREFIX + ERROR_TYPE); payload.addTypeAnnotation(ERROR_PREFIX + "foo"); HttpResponse error = createResponse(payload); handleError(error); }
@Test public void handlesErrorsWithMutipleAnnotations() throws Exception { IonStruct payload = createPayload(); payload.addTypeAnnotation("foo"); payload.addTypeAnnotation(ERROR_PREFIX + ERROR_TYPE); payload.addTypeAnnotation("bar"); HttpResponse error = createResponse(payload); AmazonServiceException exception = handleError(error); assertThat(exception, instanceOf(InvalidParameterException.class)); assertEquals(ERROR_MESSAGE, exception.getErrorMessage()); }
private static HttpResponse createResponse(IonStruct payload) throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IonWriter writer = system.newBinaryWriter(bytes); payload.writeTo(writer); writer.close(); HttpResponse error = new HttpResponse(new DefaultRequest(NO_SERVICE_NAME), NO_HTTP_REQUEST); error.setContent(new ByteArrayInputStream(bytes.toByteArray())); return error; }