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();
}
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);
}
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);
}
}
}
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);
}
}
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);
}
}
Aggregations