Search in sources :

Example 16 with HttpExecuteRequest

use of software.amazon.awssdk.http.HttpExecuteRequest in project aws-lambda-powertools-java by awslabs.

the class CloudFormationResponse method send.

/**
 * Forwards a response containing a custom payload to the target resource specified by the event. The payload is
 * formed from the event, context, and response data.
 *
 * @param event        custom CF resource event. Cannot be null.
 * @param context      used to specify when the function and any callbacks have completed execution, or to
 *                     access information from within the Lambda execution environment. Cannot be null.
 * @param responseData response to send, e.g. a list of name-value pairs. If null, an empty success is assumed.
 * @return the response object
 * @throws IOException                     when unable to generate or send the request
 * @throws CustomResourceResponseException when unable to serialize the response payload
 */
public HttpExecuteResponse send(CloudFormationCustomResourceEvent event, Context context, Response responseData) throws IOException, CustomResourceResponseException {
    // no need to explicitly close in-memory stream
    StringInputStream stream = responseBodyStream(event, context, responseData);
    URI uri = URI.create(event.getResponseUrl());
    SdkHttpRequest request = SdkHttpRequest.builder().uri(uri).method(SdkHttpMethod.PUT).headers(headers(stream.available())).build();
    HttpExecuteRequest httpExecuteRequest = HttpExecuteRequest.builder().request(request).contentStreamProvider(() -> stream).build();
    return client.prepareRequest(httpExecuteRequest).call();
}
Also used : HttpExecuteRequest(software.amazon.awssdk.http.HttpExecuteRequest) StringInputStream(software.amazon.awssdk.utils.StringInputStream) SdkHttpRequest(software.amazon.awssdk.http.SdkHttpRequest) URI(java.net.URI)

Example 17 with HttpExecuteRequest

use of software.amazon.awssdk.http.HttpExecuteRequest in project aws-lambda-powertools-java by awslabs.

the class CloudFormationResponseTest method testableCloudFormationResponse.

/**
 * Creates a CloudFormationResponse that does not make actual HTTP requests. The HTTP response body is the request
 * body.
 */
static CloudFormationResponse testableCloudFormationResponse() {
    SdkHttpClient client = mock(SdkHttpClient.class);
    ExecutableHttpRequest executableRequest = mock(ExecutableHttpRequest.class);
    when(client.prepareRequest(any(HttpExecuteRequest.class))).thenAnswer(args -> {
        HttpExecuteRequest request = args.getArgument(0, HttpExecuteRequest.class);
        assertThat(request.contentStreamProvider()).isPresent();
        InputStream inputStream = request.contentStreamProvider().get().newStream();
        HttpExecuteResponse response = mock(HttpExecuteResponse.class);
        when(response.responseBody()).thenReturn(Optional.of(AbortableInputStream.create(inputStream)));
        when(executableRequest.call()).thenReturn(response);
        return executableRequest;
    });
    return new CloudFormationResponse(client);
}
Also used : HttpExecuteRequest(software.amazon.awssdk.http.HttpExecuteRequest) HttpExecuteResponse(software.amazon.awssdk.http.HttpExecuteResponse) AbortableInputStream(software.amazon.awssdk.http.AbortableInputStream) StringInputStream(software.amazon.awssdk.utils.StringInputStream) InputStream(java.io.InputStream) SdkHttpClient(software.amazon.awssdk.http.SdkHttpClient) ExecutableHttpRequest(software.amazon.awssdk.http.ExecutableHttpRequest)

Example 18 with HttpExecuteRequest

use of software.amazon.awssdk.http.HttpExecuteRequest in project aws-greengrass-nucleus by aws-greengrass.

the class DeploymentDocumentDownloader method downloadFromUrl.

private String downloadFromUrl(String deploymentId, String preSignedUrl) throws RetryableDeploymentDocumentDownloadException, DeploymentTaskFailureException {
    HttpExecuteRequest executeRequest = HttpExecuteRequest.builder().request(SdkHttpFullRequest.builder().uri(URI.create(preSignedUrl)).method(SdkHttpMethod.GET).build()).build();
    // url is not logged for security concerns
    logger.atDebug().kv("DeploymentId", deploymentId).log("Making HTTP request to the presigned url");
    try (SdkHttpClient client = httpClientProvider.getSdkHttpClient()) {
        HttpExecuteResponse executeResponse;
        try {
            executeResponse = client.prepareRequest(executeRequest).call();
        } catch (IOException e) {
            throw new RetryableDeploymentDocumentDownloadException("I/O error when making HTTP request with presigned url.", e);
        }
        validateHttpExecuteResponse(executeResponse);
        try (InputStream in = executeResponse.responseBody().get()) {
            // load directly into memory because it will be used for resolving configuration
            return IoUtils.toUtf8String(in);
        } catch (IOException e) {
            throw new RetryableDeploymentDocumentDownloadException("I/O error when reading from HTTP response payload stream.", e);
        }
    }
}
Also used : HttpExecuteRequest(software.amazon.awssdk.http.HttpExecuteRequest) RetryableDeploymentDocumentDownloadException(com.aws.greengrass.deployment.exceptions.RetryableDeploymentDocumentDownloadException) HttpExecuteResponse(software.amazon.awssdk.http.HttpExecuteResponse) InputStream(java.io.InputStream) SdkHttpClient(software.amazon.awssdk.http.SdkHttpClient) IOException(java.io.IOException)

Example 19 with HttpExecuteRequest

use of software.amazon.awssdk.http.HttpExecuteRequest in project aws-greengrass-nucleus by aws-greengrass.

the class GreengrassRepositoryDownloader method download.

@SuppressWarnings({ "PMD.AvoidCatchingGenericException", "PMD.AvoidRethrowingException" })
@Override
protected long download(long rangeStart, long rangeEnd, MessageDigest messageDigest) throws PackageDownloadException, InterruptedException {
    String url = getArtifactDownloadURL(identifier, artifact.getArtifactUri().getSchemeSpecificPart());
    try {
        return RetryUtils.runWithRetry(clientExceptionRetryConfig, () -> {
            try (SdkHttpClient client = getSdkHttpClient()) {
                HttpExecuteRequest executeRequest = HttpExecuteRequest.builder().request(SdkHttpFullRequest.builder().uri(URI.create(url)).method(SdkHttpMethod.GET).putHeader(HTTP_RANGE_HEADER_KEY, String.format(HTTP_RANGE_HEADER_FORMAT, rangeStart, rangeEnd)).build()).build();
                HttpExecuteResponse executeResponse = client.prepareRequest(executeRequest).call();
                int responseCode = executeResponse.httpResponse().statusCode();
                // check response code
                if (responseCode == HttpURLConnection.HTTP_PARTIAL) {
                    try (InputStream inputStream = executeResponse.responseBody().get()) {
                        long downloaded = download(inputStream, messageDigest);
                        if (downloaded == 0) {
                            // Therefore throw IOException to trigger the retry logic.
                            throw new IOException(getErrorString("Failed to read any byte from the stream"));
                        } else {
                            return downloaded;
                        }
                    }
                } else if (responseCode == HttpURLConnection.HTTP_OK) {
                    long length = getContentLengthLong(executeResponse.httpResponse());
                    if (length < rangeEnd) {
                        String errMsg = String.format("Artifact size mismatch. Expected artifact size %d. HTTP contentLength %d", rangeEnd, length);
                        throw new PackageDownloadException(getErrorString(errMsg));
                    }
                    // try to discard the offset number of bytes.
                    try (InputStream inputStream = executeResponse.responseBody().get()) {
                        long byteSkipped = inputStream.skip(rangeStart);
                        // If number of bytes skipped is less than declared, throw error.
                        if (byteSkipped != rangeStart) {
                            throw new PackageDownloadException(getErrorString("Reach the end of the stream"));
                        }
                        long downloaded = download(inputStream, messageDigest);
                        if (downloaded == 0) {
                            // Therefore throw IOException to trigger the retry logic.
                            throw new IOException("Failed to read any byte from the inputStream");
                        } else {
                            return downloaded;
                        }
                    }
                } else {
                    throw new PackageDownloadException(getErrorString("Unable to download Greengrass artifact. HTTP Error: " + responseCode));
                }
            }
        }, "download-artifact", logger);
    } catch (InterruptedException e) {
        throw e;
    } catch (Exception e) {
        throw new PackageDownloadException(getErrorString("Failed to download the artifact"), e);
    }
}
Also used : HttpExecuteRequest(software.amazon.awssdk.http.HttpExecuteRequest) HttpExecuteResponse(software.amazon.awssdk.http.HttpExecuteResponse) InputStream(java.io.InputStream) SdkHttpClient(software.amazon.awssdk.http.SdkHttpClient) PackageDownloadException(com.aws.greengrass.componentmanager.exceptions.PackageDownloadException) IOException(java.io.IOException) PackageLoadingException(com.aws.greengrass.componentmanager.exceptions.PackageLoadingException) PackageDownloadException(com.aws.greengrass.componentmanager.exceptions.PackageDownloadException) IOException(java.io.IOException) SdkClientException(software.amazon.awssdk.core.exception.SdkClientException)

Example 20 with HttpExecuteRequest

use of software.amazon.awssdk.http.HttpExecuteRequest in project aws-sdk-java-v2 by aws.

the class S3PresignerIntegrationTest method getObject_PresignedHttpRequestCanBeInvokedDirectlyBySdk.

@Test
public void getObject_PresignedHttpRequestCanBeInvokedDirectlyBySdk() throws IOException {
    PresignedGetObjectRequest presigned = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)).getObjectRequest(gor -> gor.bucket(testBucket).key(testGetObjectKey).requestPayer(RequestPayer.REQUESTER)));
    assertThat(presigned.isBrowserExecutable()).isFalse();
    // or UrlConnectionHttpClient.builder().build()
    SdkHttpClient httpClient = ApacheHttpClient.builder().build();
    ContentStreamProvider requestPayload = presigned.signedPayload().map(SdkBytes::asContentStreamProvider).orElse(null);
    HttpExecuteRequest request = HttpExecuteRequest.builder().request(presigned.httpRequest()).contentStreamProvider(requestPayload).build();
    HttpExecuteResponse response = httpClient.prepareRequest(request).call();
    assertThat(response.responseBody()).isPresent();
    try (InputStream responseStream = response.responseBody().get()) {
        assertThat(IoUtils.toUtf8String(responseStream)).isEqualTo(testObjectContent);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) BeforeClass(org.junit.BeforeClass) ApacheHttpClient(software.amazon.awssdk.http.apache.ApacheHttpClient) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) CreateMultipartUploadResponse(software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse) SdkBytes(software.amazon.awssdk.core.SdkBytes) PresignedAbortMultipartUploadRequest(software.amazon.awssdk.services.s3.presigner.model.PresignedAbortMultipartUploadRequest) RequestPayer(software.amazon.awssdk.services.s3.model.RequestPayer) S3Presigner(software.amazon.awssdk.services.s3.presigner.S3Presigner) Duration(java.time.Duration) After(org.junit.After) PresignedPutObjectRequest(software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest) Before(org.junit.Before) UploadPartRequest(software.amazon.awssdk.services.s3.model.UploadPartRequest) AfterClass(org.junit.AfterClass) MultipartUpload(software.amazon.awssdk.services.s3.model.MultipartUpload) PresignedGetObjectRequest(software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest) ContentStreamProvider(software.amazon.awssdk.http.ContentStreamProvider) PresignedUploadPartRequest(software.amazon.awssdk.services.s3.presigner.model.PresignedUploadPartRequest) IOException(java.io.IOException) Test(org.junit.Test) PresignedRequest(software.amazon.awssdk.awscore.presigner.PresignedRequest) UUID(java.util.UUID) SdkHttpClient(software.amazon.awssdk.http.SdkHttpClient) CompleteMultipartUploadRequest(software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest) PresignedCompleteMultipartUploadRequest(software.amazon.awssdk.services.s3.presigner.model.PresignedCompleteMultipartUploadRequest) S3TestUtils(software.amazon.awssdk.services.s3.utils.S3TestUtils) Consumer(java.util.function.Consumer) AbortableInputStream(software.amazon.awssdk.http.AbortableInputStream) StringInputStream(software.amazon.awssdk.utils.StringInputStream) PresignedCreateMultipartUploadRequest(software.amazon.awssdk.services.s3.presigner.model.PresignedCreateMultipartUploadRequest) Optional(java.util.Optional) RequestBody(software.amazon.awssdk.core.sync.RequestBody) HttpExecuteResponse(software.amazon.awssdk.http.HttpExecuteResponse) CreateMultipartUploadRequest(software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest) AbortMultipartUploadRequest(software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest) IoUtils(software.amazon.awssdk.utils.IoUtils) InputStream(java.io.InputStream) HttpExecuteRequest(software.amazon.awssdk.http.HttpExecuteRequest) UploadPartResponse(software.amazon.awssdk.services.s3.model.UploadPartResponse) HttpExecuteRequest(software.amazon.awssdk.http.HttpExecuteRequest) HttpExecuteResponse(software.amazon.awssdk.http.HttpExecuteResponse) AbortableInputStream(software.amazon.awssdk.http.AbortableInputStream) StringInputStream(software.amazon.awssdk.utils.StringInputStream) InputStream(java.io.InputStream) PresignedGetObjectRequest(software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest) SdkHttpClient(software.amazon.awssdk.http.SdkHttpClient) ContentStreamProvider(software.amazon.awssdk.http.ContentStreamProvider) Test(org.junit.Test)

Aggregations

HttpExecuteRequest (software.amazon.awssdk.http.HttpExecuteRequest)26 HttpExecuteResponse (software.amazon.awssdk.http.HttpExecuteResponse)11 SdkHttpClient (software.amazon.awssdk.http.SdkHttpClient)11 Test (org.junit.Test)10 IOException (java.io.IOException)8 InputStream (java.io.InputStream)8 SdkHttpRequest (software.amazon.awssdk.http.SdkHttpRequest)7 StringInputStream (software.amazon.awssdk.utils.StringInputStream)7 AbortableInputStream (software.amazon.awssdk.http.AbortableInputStream)5 Duration (java.time.Duration)4 Optional (java.util.Optional)4 SdkHttpFullRequest (software.amazon.awssdk.http.SdkHttpFullRequest)4 IoUtils (software.amazon.awssdk.utils.IoUtils)4 HttpURLConnection (java.net.HttpURLConnection)3 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)3 SdkClientConfiguration (software.amazon.awssdk.core.client.config.SdkClientConfiguration)3 AmazonSyncHttpClient (software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient)3 ContentStreamProvider (software.amazon.awssdk.http.ContentStreamProvider)3 MetricCollector (software.amazon.awssdk.metrics.MetricCollector)3 PackageDownloadException (com.aws.greengrass.componentmanager.exceptions.PackageDownloadException)2