public GetMediaForFragmentListResult unmarshall(JsonUnmarshallerContext context) throws Exception { GetMediaForFragmentListResult getMediaForFragmentListResult = new GetMediaForFragmentListResult(); if (context.isStartOfDocument()) { if (context.getHeader("Content-Type") != null) { context.setCurrentHeader("Content-Type"); getMediaForFragmentListResult.setContentType(context.getUnmarshaller(String.class).unmarshall(context)); } } getMediaForFragmentListResult.setPayload(context.getHttpResponse().getContent()); return getMediaForFragmentListResult; }
public DeleteUserResult unmarshall(JsonUnmarshallerContext context) throws Exception { DeleteUserResult deleteUserResult = new DeleteUserResult(); deleteUserResult.setStatus(context.getHttpResponse().getStatusCode()); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return deleteUserResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("RequestId", targetDepth)) { context.nextToken(); deleteUserResult.setRequestId(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return deleteUserResult; }
/** * @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); } return awsResponse; }
/** * Static factory to create an {@link SdkHttpMetadata} from the details in a {@link * HttpResponse}. */ public static SdkHttpMetadata from(HttpResponse httpResponse) { return new SdkHttpMetadata(httpResponse.getHeaders(), httpResponse.getStatusCode()); }
@Override public AmazonServiceException handle(HttpResponse errorResponse) throws Exception { AmazonServiceException ase = createAse(errorResponse); if (ase == null) { throw new SdkClientException("Unable to unmarshall error response from service"); } ase.setHttpHeaders(errorResponse.getHeaders()); if (StringUtils.isNullOrEmpty(ase.getErrorCode())) { ase.setErrorCode(errorResponse.getStatusCode() + " " + errorResponse.getStatusText()); } return ase; }
private String idString(HttpResponse errorResponse) { StringBuilder idString = new StringBuilder(); try { if (errorResponse.getRequest().getHeaders().containsKey(HEADER_SDK_TRANSACTION_ID)) { idString.append("Invocation Id:").append(errorResponse.getRequest().getHeaders().get(HEADER_SDK_TRANSACTION_ID)); } if (errorResponse.getHeaders().containsKey(X_AMZN_REQUEST_ID_HEADER)) { if (idString.length() > 0) { idString.append(", "); } idString.append("Request Id:").append(errorResponse.getHeaders().get(X_AMZN_REQUEST_ID_HEADER)); } } catch (NullPointerException npe){ log.debug("Error getting Request or Invocation ID from response", npe); } return idString.length() > 0 ? idString.toString() : "Unknown"; }
awsRequestMetrics.addProperty(Field.ServiceName, request.getServiceName()); awsRequestMetrics.addProperty(Field.ServiceEndpoint, request.getEndpoint()); request.addHeader(HEADER_SDK_TRANSACTION_ID, UUID.randomUUID().toString()); int requestCount = 0; long lastBackoffDelay = 0; awsRequestMetrics.addProperty(Field.StatusCode, httpResponse.getStatusCode()); final String redirectedLocation = httpResponse.getHeaders().get("Location"); log.debug("Redirecting to: " + redirectedLocation); request.setEndpoint(null); request.setResourcePath(null); awsRequestMetrics.addProperty(Field.StatusCode, httpResponse.getStatusCode()); awsRequestMetrics.addProperty(Field.RedirectLocation, redirectedLocation); awsRequestMetrics.addProperty(Field.AWSRequestID, null); final AmazonServiceException ase = handleErrorResponse(request, errorResponseHandler, httpResponse); awsRequestMetrics.addProperty(Field.AWSRequestID, ase.getRequestId()); awsRequestMetrics.addProperty(Field.AWSErrorCode, ase.getErrorCode()); awsRequestMetrics.addProperty(Field.StatusCode, ase.getStatusCode()); if (!shouldRetry(request.getOriginalRequest(), if (httpResponse.getRawContent() != null) { httpResponse.getRawContent().close();
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); }
request = new GetJobOutputRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getJobOutputRequest)); request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Glacier"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetJobOutput"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); result.setBody(new LengthCheckInputStream(result.getBody(), Long.parseLong(response.getHttpResponse().getHeaders().get("Content-Length")), com.amazonaws.util.LengthCheckInputStream.INCLUDE_SKIPPED_BYTES));
@Override public AmazonServiceException handle(HttpResponse response) throws Exception { final AmazonServiceException ase = handleAse(response); ase.setStatusCode(response.getStatusCode()); ase.setServiceName(response.getRequest().getServiceName()); awsRequestMetrics.addPropertyWith(AWSRequestMetrics.Field.AWSRequestID, ase.getRequestId()) .addPropertyWith(AWSRequestMetrics.Field.AWSErrorCode, ase.getErrorCode()) .addPropertyWith(AWSRequestMetrics.Field.StatusCode, ase.getStatusCode()); return ase; }
@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); }
log.trace("Parsing service response JSON"); final String crc32Checksum = response.getHeaders().get("x-amz-crc32"); CRC32ChecksumCalculatingInputStream crc32ChecksumInputStream = null; InputStream content = response.getRawContent(); if (content == null) { log.debug("content encoding = " + response.getHeaders().get("Content-Encoding")); if ("gzip".equals(response.getHeaders().get("Content-Encoding"))) { content = new GZIPInputStream(crc32ChecksumInputStream); } else { final JsonUnmarshallerContext unmarshallerContext = new JsonUnmarshallerContext(jsonReader, response); final T result = responseUnmarshaller.unmarshall(unmarshallerContext); response.getHeaders().get("x-amzn-RequestId")); awsResponse.setResponseMetadata(new ResponseMetadata(metadata));
private AmazonServiceException createAse(HttpResponse errorResponse) throws Exception { // Try to parse the error response as XML final Document document = documentFromContent(errorResponse.getContent(), idString(errorResponse)); /* * We need to select which exception unmarshaller is the correct one to * use from all the possible exceptions this operation can throw. * Currently we rely on the unmarshallers to return null if they can't * unmarshall the response, but we might need something a little more * sophisticated in the future. */ for (Unmarshaller<AmazonServiceException, Node> unmarshaller : unmarshallerList) { AmazonServiceException ase = unmarshaller.unmarshall(document); if (ase != null) { ase.setStatusCode(errorResponse.getStatusCode()); return ase; } } return null; }
log.trace("Parsing service response JSON"); String CRC32Checksum = response.getHeaders().get("x-amz-crc32"); jsonParser = jsonFactory.createParser(response.getContent()); registerAdditionalMetadataExpressions(unmarshallerContext); T result = responseUnmarshaller.unmarshall(unmarshallerContext); if (shouldParsePayloadAsJson() && response.getContent() != null) { IOUtils.drainInputStream(response.getContent()); long clientSideCRC = response.getCRC32Checksum(); if (clientSideCRC != serverSideCRC) { throw new CRC32MismatchException( Map<String, String> metadata = unmarshallerContext.getMetadata(); metadata.put(ResponseMetadata.AWS_REQUEST_ID, response.getHeaders().get(X_AMZN_REQUEST_ID_HEADER)); awsResponse.setResponseMetadata(new ResponseMetadata(metadata));
@Override public AmazonServiceException handle(HttpResponse response) throws Exception { JsonContent jsonContent = JsonContent.createJsonContent(response, jsonFactory); String errorCode = errorCodeParser.parseErrorCode(response, jsonContent); AmazonServiceException ase = createException(errorCode, jsonContent); // Jackson has special-casing for 'message' values when deserializing // Throwables, but sometimes the service passes the error message in // other JSON fields - handle it here. if (ase.getErrorMessage() == null) { ase.setErrorMessage(errorMessageParser.parseErrorMessage(response, jsonContent.getJsonNode())); } ase.setErrorCode(errorCode); ase.setServiceName(response.getRequest().getServiceName()); ase.setStatusCode(response.getStatusCode()); ase.setErrorType(getErrorTypeFromStatusCode(response.getStatusCode())); ase.setRawResponse(jsonContent.getRawContent()); String requestId = getRequestIdFromHeaders(response.getHeaders()); if (requestId != null) { ase.setRequestId(requestId); } ase.setHttpHeaders(response.getHeaders()); return ase; }
@Test public void testDefaultErrorResponseHandlerCannotGetContent() throws Exception { List<Unmarshaller<AmazonServiceException, Node>> unmarshallerList = new ArrayList<Unmarshaller<AmazonServiceException, Node>>(); HttpResponse errorResponse = new HttpResponse.Builder() .statusCode(400) .statusText("Error") .content(new InputStream() { @Override public int read() throws IOException { throw new IOException("Test IOException"); } }) .build(); DefaultErrorResponseHandler handler = new DefaultErrorResponseHandler(unmarshallerList); AmazonServiceException e = handler.handle(errorResponse); assertEquals(e.getErrorCode(), errorResponse.getStatusCode() + " " + errorResponse.getStatusText()); assertEquals(e.getStatusCode(), 400); assertEquals(e.getErrorType(), ErrorType.Unknown); }
private AmazonServiceException handleAse(HttpResponse response) throws Exception { final int statusCode = response.getStatusCode(); try { return delegate.handle(response); } catch(InterruptedException e) { throw e; } catch (Exception e) { // If the errorResponseHandler doesn't work, then check for error responses that don't have any content if (statusCode == 413) { AmazonServiceException exception = new AmazonServiceException("Request entity too large"); exception.setServiceName(response.getRequest().getServiceName()); exception.setStatusCode(statusCode); exception.setErrorType(AmazonServiceException.ErrorType.Client); exception.setErrorCode("Request entity too large"); return exception; } else if (statusCode >= 500 && statusCode < 600) { AmazonServiceException exception = new AmazonServiceException(response.getStatusText()); exception.setServiceName(response.getRequest().getServiceName()); exception.setStatusCode(statusCode); exception.setErrorType(AmazonServiceException.ErrorType.Service); exception.setErrorCode(response.getStatusText()); return exception; } else { throw e; } } }
public DeleteThingShadowResult unmarshall(JsonUnmarshallerContext context) throws Exception { DeleteThingShadowResult deleteThingShadowResult = new DeleteThingShadowResult(); java.io.InputStream is = context.getHttpResponse().getContent(); if (is != null) { try { deleteThingShadowResult.setPayload(java.nio.ByteBuffer.wrap(com.amazonaws.util.IOUtils.toByteArray(is))); } finally { com.amazonaws.util.IOUtils.closeQuietly(is, null); } } return deleteThingShadowResult; }
/** * Used to create an {@link newAmazonServiceException} when we failed to * read the error response or parsed the error response as XML. */ private AmazonServiceException newAmazonServiceException(String errmsg, HttpResponse httpResponse, Exception readFailure) { AmazonServiceException exception = new AmazonServiceException(errmsg, readFailure); final int statusCode = httpResponse.getStatusCode(); exception.setErrorCode(statusCode + " " + httpResponse.getStatusText()); exception.setErrorType(AmazonServiceException.ErrorType.Unknown); exception.setStatusCode(statusCode); return exception; }
@Override public InvokeResult unmarshall(JsonUnmarshallerContext context) throws Exception { InvokeResult invokeResult = new InvokeResult(); if (context.getHeader("X-Amz-Function-Error") != null) invokeResult.setFunctionError(context.getHeader("X-Amz-Function-Error")); if (context.getHeader("X-Amz-Log-Result") != null) invokeResult.setLogResult(context.getHeader("X-Amz-Log-Result")); invokeResult.setStatusCode(context.getHttpResponse().getStatusCode()); ByteBuffer payload = EMPTY_BYTEBUFFER; InputStream content = context.getHttpResponse().getContent(); if (content != null) { payload = ByteBuffer.wrap(IOUtils.toByteArray(content)); } invokeResult.setPayload(payload); return invokeResult; }