1 /*
2  * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License").
5  * You may not use this file except in compliance with the License.
6  * A copy of the License is located at
7  *
8  *  http://aws.amazon.com/apache2.0
9  *
10  * or in the "license" file accompanying this file. This file is distributed
11  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12  * express or implied. See the License for the specific language governing
13  * permissions and limitations under the License.
14  */

15
16 package software.amazon.awssdk.services.s3.internal.handlers;
17
18 import java.util.Optional;
19 import software.amazon.awssdk.annotations.SdkInternalApi;
20 import software.amazon.awssdk.core.SdkResponse;
21 import software.amazon.awssdk.core.interceptor.Context;
22 import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
23 import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
24 import software.amazon.awssdk.http.SdkHttpResponse;
25 import software.amazon.awssdk.services.s3.model.GetObjectRequest;
26 import software.amazon.awssdk.services.s3.model.GetObjectResponse;
27
28 /**
29  * Interceptor for {@link GetObjectRequest} messages.
30  */

31 @SdkInternalApi
32 public class GetObjectInterceptor implements ExecutionInterceptor {
33     @Override
34     public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) {
35         SdkResponse response = context.response();
36         if (!(response instanceof GetObjectResponse)) {
37             return response;
38         }
39
40         return fixContentRange(response, context.httpResponse());
41     }
42
43     /**
44      * S3 currently returns content-range in two possible headers: Content-Range or x-amz-content-range based on the x-amz-te
45      * in the request. This will check the x-amz-content-range if the modeled header (Content-Range) wasn't populated.
46      */

47     private SdkResponse fixContentRange(SdkResponse sdkResponse, SdkHttpResponse httpResponse) {
48         // Use the modeled content range header, if the service returned it.
49         GetObjectResponse getObjectResponse = (GetObjectResponse) sdkResponse;
50         if (getObjectResponse.contentRange() != null) {
51             return getObjectResponse;
52         }
53
54         // If the service didn't use the modeled content range header, check the x-amz-content-range header.
55         Optional<String> xAmzContentRange = httpResponse.firstMatchingHeader("x-amz-content-range");
56         if (!xAmzContentRange.isPresent()) {
57             return getObjectResponse;
58         }
59
60         return getObjectResponse.copy(r -> r.contentRange(xAmzContentRange.get()));
61     }
62 }
63