software.amazon.awssdk.core.async.AsyncRequestBody Java Examples

The following examples show how to use software.amazon.awssdk.core.async.AsyncRequestBody. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UploadResource.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Upload a single file part to the requested bucket
 * @param uploadState
 * @param buffer
 * @return
 */
private Mono<CompletedPart> uploadPart(UploadState uploadState, ByteBuffer buffer) {
    final int partNumber = ++uploadState.partCounter;
    log.info("[I218] uploadPart: partNumber={}, contentLength={}",partNumber, buffer.capacity());

    CompletableFuture<UploadPartResponse> request = s3client.uploadPart(UploadPartRequest.builder()
        .bucket(uploadState.bucket)
        .key(uploadState.filekey)
        .partNumber(partNumber)
        .uploadId(uploadState.uploadId)
        .contentLength((long) buffer.capacity())
        .build(), 
        AsyncRequestBody.fromPublisher(Mono.just(buffer)));
    
    return Mono
      .fromFuture(request)
      .map((uploadPartResult) -> {              
          checkResult(uploadPartResult);
          log.info("[I230] uploadPart complete: part={}, etag={}",partNumber,uploadPartResult.eTag());
          return CompletedPart.builder()
            .eTag(uploadPartResult.eTag())
            .partNumber(partNumber)
            .build();
      });
}
 
Example #2
Source File: InterceptorTestUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public static Context.ModifyHttpRequest modifyHttpRequestContext(SdkRequest request, SdkHttpRequest sdkHttpRequest) {
    Optional<RequestBody> requestBody = Optional.of(RequestBody.fromString("helloworld"));
    Optional<AsyncRequestBody> asyncRequestBody = Optional.of(AsyncRequestBody.fromString("helloworld"));

    return new Context.ModifyHttpRequest() {
        @Override
        public SdkHttpRequest httpRequest() {
            return sdkHttpRequest;
        }

        @Override
        public Optional<RequestBody> requestBody() {
            return requestBody;
        }

        @Override
        public Optional<AsyncRequestBody> asyncRequestBody() {
            return asyncRequestBody;
        }

        @Override
        public SdkRequest request() {
            return request;
        }
    };
}
 
Example #3
Source File: S3AsyncClientResource.java    From quarkus-quickstarts with Apache License 2.0 6 votes vote down vote up
@POST
@Path("upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Uni<Response> uploadFile(@MultipartForm FormData formData) throws Exception {

    if (formData.fileName == null || formData.fileName.isEmpty()) {
        return Uni.createFrom().item(Response.status(Status.BAD_REQUEST).build());
    }

    if (formData.mimeType == null || formData.mimeType.isEmpty()) {
        return Uni.createFrom().item(Response.status(Status.BAD_REQUEST).build());
    }

    return Uni.createFrom()
            .completionStage(() -> {
                return s3.putObject(buildPutRequest(formData), AsyncRequestBody.fromFile(uploadToTemp(formData.data)));
            })
            .onItem().ignore().andSwitchTo(Uni.createFrom().item(Response.created(null).build()))
            .onFailure().recoverWithItem(th -> {
                th.printStackTrace();
                return Response.serverError().build();
            });
}
 
Example #4
Source File: S3Resource.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@GET
@Path("async")
@Produces(TEXT_PLAIN)
public CompletionStage<String> testAsyncS3() {
    LOG.info("Testing Async S3 client with bucket: " + ASYNC_BUCKET);
    String keyValue = UUID.randomUUID().toString();

    return S3Utils.createBucketAsync(s3AsyncClient, ASYNC_BUCKET)
            .thenCompose(bucket -> s3AsyncClient.putObject(S3Utils.createPutRequest(ASYNC_BUCKET, keyValue),
                    AsyncRequestBody.fromString(SAMPLE_S3_OBJECT)))
            .thenCompose(resp -> s3AsyncClient.getObject(S3Utils.createGetRequest(ASYNC_BUCKET, keyValue),
                    AsyncResponseTransformer.toBytes()))
            .thenApply(resp -> metadata(resp.response()) + "+" + resp.asUtf8String())
            .exceptionally(th -> {
                LOG.error("Error during async S3 operations", th.getCause());
                return "ERROR";
            });
}
 
Example #5
Source File: EnableChunkedEncodingInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private Context.ModifyHttpRequest context(SdkRequest request) {
    return new Context.ModifyHttpRequest() {
        @Override
        public SdkHttpRequest httpRequest() {
            return null;
        }

        @Override
        public Optional<RequestBody> requestBody() {
            return null;
        }

        @Override
        public Optional<AsyncRequestBody> asyncRequestBody() {
            return null;
        }

        @Override
        public SdkRequest request() {
            return request;
        }
    };
}
 
Example #6
Source File: EndpointAddressInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private Context.ModifyHttpRequest context(SdkRequest request, SdkHttpRequest sdkHttpRequest) {
    return new Context.ModifyHttpRequest() {
        @Override
        public SdkHttpRequest httpRequest() {
            return sdkHttpRequest;
        }

        @Override
        public Optional<RequestBody> requestBody() {
            return null;
        }

        @Override
        public Optional<AsyncRequestBody> asyncRequestBody() {
            return null;
        }

        @Override
        public SdkRequest request() {
            return request;
        }
    };
}
 
Example #7
Source File: S3AsyncStabilityTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void uploadLargeObjectFromFile() {
    RandomTempFile file = null;
    try {
        file = new RandomTempFile((long) 2e+9);
        StabilityTestRunner.newRunner()
                           .testName("S3AsyncStabilityTest.uploadLargeObjectFromFile")
                           .futures(s3NettyClient.putObject(b -> b.bucket(bucketName).key(LARGE_KEY_NAME),
                                                            AsyncRequestBody.fromFile(file)))
                           .run();
    } catch (IOException e) {
        throw new RuntimeException("fail to create test file", e);
    } finally {
        if (file != null) {
            file.delete();
        }
    }
}
 
Example #8
Source File: AsyncClientInterface.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a simple method for operations with streaming input and output members.
 * Streaming input member takes a {@link Path} containing the data to upload and
 * the streaming output member takes a {@link Path} where data will be downloaded to.
 */
private MethodSpec streamingInputOutputFileSimpleMethod(OperationModel opModel) {
    ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType());
    return interfaceMethodSignature(opModel)
        .returns(completableFutureType(getPojoResponseType(opModel)))
        .addJavadoc(opModel.getDocs(model, ClientType.ASYNC, SimpleMethodOverload.FILE))
        .addParameter(requestType, opModel.getInput().getVariableName())
        .addParameter(ClassName.get(Path.class), "sourcePath")
        .addParameter(ClassName.get(Path.class), "destinationPath")
        .addStatement("return $L($L, $T.fromFile(sourcePath), $T.toFile(destinationPath))",
                      opModel.getMethodName(),
                      opModel.getInput().getVariableName(),
                      ClassName.get(AsyncRequestBody.class),
                      ClassName.get(AsyncResponseTransformer.class))
        .build();
}
 
Example #9
Source File: test-query-async-client-class.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Some operation with a streaming input
 *
 * @param streamingInputOperationRequest
 * @param requestBody
 *        Functional interface that can be implemented to produce the request content in a non-blocking manner. The
 *        size of the content is expected to be known up front. See {@link AsyncRequestBody} for specific details on
 *        implementing this interface as well as links to precanned implementations for common scenarios like
 *        uploading from a file. The service documentation for the request content is as follows 'This be a stream'
 * @return A Java Future containing the result of the StreamingInputOperation operation returned by the service.<br/>
 *         The CompletableFuture returned by this method can be completed exceptionally with the following
 *         exceptions.
 *         <ul>
 *         <li>SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
 *         Can be used for catch all scenarios.</li>
 *         <li>SdkClientException If any client side error occurs such as an IO related failure, failure to get
 *         credentials, etc.</li>
 *         <li>QueryException Base class for all service exceptions. Unknown exceptions will be thrown as an
 *         instance of this type.</li>
 *         </ul>
 * @sample QueryAsyncClient.StreamingInputOperation
 * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/query-service-2010-05-08/StreamingInputOperation"
 *      target="_top">AWS API Documentation</a>
 */
@Override
public CompletableFuture<StreamingInputOperationResponse> streamingInputOperation(
    StreamingInputOperationRequest streamingInputOperationRequest, AsyncRequestBody requestBody) {
    try {

        HttpResponseHandler<StreamingInputOperationResponse> responseHandler = protocolFactory
            .createResponseHandler(StreamingInputOperationResponse::builder);

        HttpResponseHandler<AwsServiceException> errorResponseHandler = protocolFactory.createErrorResponseHandler();

        CompletableFuture<StreamingInputOperationResponse> executeFuture = clientHandler
            .execute(new ClientExecutionParams<StreamingInputOperationRequest, StreamingInputOperationResponse>()
                         .withOperationName("StreamingInputOperation")
                         .withMarshaller(
                             AsyncStreamingRequestMarshaller.builder()
                                                            .delegateMarshaller(new StreamingInputOperationRequestMarshaller(protocolFactory))
                                                            .asyncRequestBody(requestBody).build()).withResponseHandler(responseHandler)
                         .withErrorResponseHandler(errorResponseHandler).withAsyncRequestBody(requestBody)
                         .withInput(streamingInputOperationRequest));
        return executeFuture;
    } catch (Throwable t) {
        return CompletableFutureUtils.failedFuture(t);
    }
}
 
Example #10
Source File: BaseEventStreamAsyncAws4Signer.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
protected AsyncRequestBody transformRequestProvider(String headerSignature,
                                                    Aws4SignerRequestParams signerRequestParams,
                                                    Aws4SignerParams signerParams,
                                                    AsyncRequestBody asyncRequestBody) {
    /**
     * Concat trailing empty frame to publisher
     */
    Publisher<ByteBuffer> publisherWithTrailingEmptyFrame = appendEmptyFrame(asyncRequestBody);

    /**
     * Map publisher with signing function
     */
    Publisher<ByteBuffer> publisherWithSignedFrame =
        transformRequestBodyPublisher(publisherWithTrailingEmptyFrame, headerSignature,
                                      signerParams.awsCredentials(), signerRequestParams);

    AsyncRequestBody transformedRequestBody = AsyncRequestBody.fromPublisher(publisherWithSignedFrame);

    return new SigningRequestBodyProvider(transformedRequestBody);
}
 
Example #11
Source File: SignerTestUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public static AsyncRequestBody signAsyncRequest(BaseAsyncAws4Signer signer,
                                                SdkHttpFullRequest request,
                                                AsyncRequestBody asyncRequestBody,
                                                AwsCredentials credentials,
                                                String signingName,
                                                Clock signingDateOverride,
                                                String region) {

    Aws4SignerParams signerParams = Aws4SignerParams.builder()
        .awsCredentials(credentials)
        .signingName(signingName)
        .signingClockOverride(signingDateOverride)
        .signingRegion(Region.of(region))
        .build();

    final Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signerParams);

    return signer.signAsync(request, asyncRequestBody, requestParams, signerParams);
}
 
Example #12
Source File: SigningStage.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Sign the request if the signer if provided and credentials are present.
 */
private SdkHttpFullRequest signRequest(SdkHttpFullRequest request, RequestExecutionContext context) {
    updateInterceptorContext(request, context.executionContext());

    Signer signer = context.signer();

    if (shouldSign(signer)) {
        adjustForClockSkew(context.executionAttributes());

        SdkHttpFullRequest signedRequest = signer.sign(request, context.executionAttributes());

        if (signer instanceof AsyncRequestBodySigner) {
            //Transform request body provider with signing operator
            AsyncRequestBody transformedRequestProvider =
                ((AsyncRequestBodySigner) signer)
                    .signAsyncRequestBody(signedRequest, context.requestProvider(), context.executionAttributes());
            context.requestProvider(transformedRequestProvider);
        }
        updateInterceptorContext(signedRequest, context.executionContext());
        return signedRequest;
    }

    return request;
}
 
Example #13
Source File: S3AsyncOps.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	S3AsyncClient client = S3AsyncClient.create();
    CompletableFuture<PutObjectResponse> future = client.putObject(
            PutObjectRequest.builder()
                            .bucket(BUCKET)
                            .key(KEY)
                            .build(),
            AsyncRequestBody.fromFile(Paths.get("myfile.in"))
    );
    future.whenComplete((resp, err) -> {
        try {
            if (resp != null) {
                System.out.println("my response: " + resp);
            } else {
                // Handle error
                err.printStackTrace();
            }
        } finally {
            // Lets the application shut down. Only close the client when you are completely done with it.
            client.close();
        }
    });

    future.join();
}
 
Example #14
Source File: AsyncChecksumValidationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void modifyAsyncHttpContent_putObjectRequestChecksumEnabled_shouldWrapChecksumRequestBody() {
    ExecutionAttributes executionAttributes = getExecutionAttributes();
    Context.ModifyHttpRequest modifyHttpRequest =
        InterceptorTestUtils.modifyHttpRequestContext(PutObjectRequest.builder().build());
    Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest,
                                                                                     executionAttributes);

    assertThat(asyncRequestBody.isPresent()).isTrue();
    assertThat(executionAttributes.getAttribute(CHECKSUM)).isNotNull();
    assertThat(asyncRequestBody.get()).isExactlyInstanceOf(ChecksumCalculatingAsyncRequestBody.class);
}
 
Example #15
Source File: UploadResource.java    From tutorials with MIT License 5 votes vote down vote up
/**
 *  Standard file upload.
 */
@PostMapping
public Mono<ResponseEntity<UploadResult>> uploadHandler(@RequestHeader HttpHeaders headers, @RequestBody Flux<ByteBuffer> body) {

    long length = headers.getContentLength();
    if (length < 0) {
        throw new UploadFailedException(HttpStatus.BAD_REQUEST.value(), Optional.of("required header missing: Content-Length"));
    }

    String fileKey = UUID.randomUUID().toString();
    Map<String, String> metadata = new HashMap<String, String>();
    MediaType mediaType = headers.getContentType();

    if (mediaType == null) {
        mediaType = MediaType.APPLICATION_OCTET_STREAM;
    }

    log.info("[I95] uploadHandler: mediaType{}, length={}", mediaType, length);
    CompletableFuture<PutObjectResponse> future = s3client
      .putObject(PutObjectRequest.builder()
        .bucket(s3config.getBucket())
        .contentLength(length)
        .key(fileKey.toString())
        .contentType(mediaType.toString())
        .metadata(metadata)
        .build(), 
        AsyncRequestBody.fromPublisher(body));
    
    return Mono.fromFuture(future)
      .map((response) -> {
          checkResult(response);
          return ResponseEntity
            .status(HttpStatus.CREATED)
            .body(new UploadResult(HttpStatus.CREATED, new String[] {fileKey}));
      });
}
 
Example #16
Source File: AsyncChecksumValidationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum_throwExceptionIfInvalid() {
    SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();

    PutObjectResponse response = PutObjectResponse.builder()
                                                  .eTag(INVALID_CHECKSUM)
                                                  .build();

    PutObjectRequest putObjectRequest = PutObjectRequest.builder().build();

    SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder()
                                                      .uri(URI.create("http://localhost:8080"))
                                                      .method(SdkHttpMethod.PUT)
                                                      .build();

    Context.AfterUnmarshalling afterUnmarshallingContext =
        InterceptorContext.builder()
                          .request(putObjectRequest)
                          .httpRequest(sdkHttpRequest)
                          .response(response)
                          .httpResponse(sdkHttpResponse)
                          .asyncRequestBody(AsyncRequestBody.fromString("Test"))
                          .build();

    ExecutionAttributes attributes = getExecutionAttributesWithChecksum();
    interceptor.modifyAsyncHttpContent(afterUnmarshallingContext, attributes);
    assertThatThrownBy(() -> interceptor.afterUnmarshalling(afterUnmarshallingContext, attributes))
        .hasMessageContaining("Data read has a different checksum than expected.");
}
 
Example #17
Source File: AsyncChecksumValidationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void modifyAsyncHttpContent_nonPutObjectRequest_shouldNotModify() {
    ExecutionAttributes executionAttributes = getExecutionAttributes();
    Context.ModifyHttpRequest modifyHttpRequest =
        InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build());
    Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest,
                                                                                     executionAttributes);

    assertThat(asyncRequestBody).isEqualTo(modifyHttpRequest.asyncRequestBody());
}
 
Example #18
Source File: AsyncChecksumValidationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void modifyAsyncHttpContent_putObjectRequest_checksumDisabled_shouldNotModify() {
    ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled();
    Context.ModifyHttpRequest modifyHttpRequest =
        InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build());

    Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest,
                                                                                     executionAttributes);
    assertThat(asyncRequestBody).isEqualTo(modifyHttpRequest.asyncRequestBody());
}
 
Example #19
Source File: AsyncOperationCancelTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamingInputOperation() {
    CompletableFuture<StreamingInputOperationResponse> responseFuture = client.streamingInputOperation(r -> {}, AsyncRequestBody.empty());
    responseFuture.cancel(true);
    assertThat(executeFuture.isCompletedExceptionally()).isTrue();
    assertThat(executeFuture.isCancelled()).isTrue();
}
 
Example #20
Source File: AsyncOperationCancelTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamingInputOperation() {
    CompletableFuture<StreamingInputOperationResponse> responseFuture = client.streamingInputOperation(r -> {}, AsyncRequestBody.empty());
    responseFuture.cancel(true);
    assertThat(executeFuture.isCompletedExceptionally()).isTrue();
    assertThat(executeFuture.isCancelled()).isTrue();
}
 
Example #21
Source File: AsyncClientInterface.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private MethodSpec traditionalMethod(OperationModel opModel) {
    ClassName responsePojoType = getPojoResponseType(opModel);
    ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType());

    MethodSpec.Builder builder = methodSignatureWithReturnType(opModel)
            .addParameter(requestType, opModel.getInput().getVariableName())
            .addJavadoc(opModel.getDocs(model, ClientType.ASYNC));

    if (opModel.hasStreamingInput()) {
        builder.addParameter(ClassName.get(AsyncRequestBody.class), "requestBody");
    } else if (opModel.hasEventStreamInput()) {
        String eventStreamShapeName = EventStreamUtils.getEventStreamInRequest(opModel.getInputShape())
                                                      .getShapeName();
        ClassName shapeClass = ClassName.get(modelPackage, eventStreamShapeName);
        ParameterizedTypeName requestPublisher = ParameterizedTypeName.get(ClassName.get(Publisher.class), shapeClass);
        builder.addParameter(requestPublisher, EVENT_PUBLISHER_PARAM_NAME);
    }

    if (opModel.hasStreamingOutput()) {
        builder.addTypeVariable(STREAMING_TYPE_VARIABLE);
        ParameterizedTypeName asyncResponseHandlerType = ParameterizedTypeName
            .get(ClassName.get(AsyncResponseTransformer.class), responsePojoType, STREAMING_TYPE_VARIABLE);
        builder.addParameter(asyncResponseHandlerType, "asyncResponseTransformer");
    } else if (opModel.hasEventStreamOutput()) {
        builder.addParameter(poetExtensions.eventStreamResponseHandlerType(opModel), "asyncResponseHandler");
    }
    return operationBody(builder, opModel).build();
}
 
Example #22
Source File: AsyncClientInterface.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a simple method for operations with a streaming input member that takes a {@link Path} containing the data
 * to upload.
 */
private MethodSpec streamingInputFileSimpleMethod(OperationModel opModel) {
    ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType());
    return interfaceMethodSignature(opModel)
            .addJavadoc(opModel.getDocs(model, ClientType.ASYNC, SimpleMethodOverload.FILE))
            .addParameter(requestType, opModel.getInput().getVariableName())
            .addParameter(ClassName.get(Path.class), "sourcePath")
            .addStatement("return $L($L, $T.fromFile(sourcePath))", opModel.getMethodName(),
                          opModel.getInput().getVariableName(),
                          ClassName.get(AsyncRequestBody.class))
            .build();
}
 
Example #23
Source File: ChecksumResetsOnRetryTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void asyncPutObject_resetsChecksumOnRetry() {
    stubSuccessAfterOneRetry(r -> r.withHeader("ETag", bodyEtag));

    PutObjectResponse response = s3AsyncClient.putObject(r -> r.bucket("foo").key("bar"), AsyncRequestBody.fromBytes(body)).join();
    assertThat(response.eTag()).isEqualTo(bodyEtag);
}
 
Example #24
Source File: test-async-client-class.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the EventStreamOperationWithOnlyInput operation asynchronously.
 *
 * @param eventStreamOperationWithOnlyInputRequest
 * @return A Java Future containing the result of the EventStreamOperationWithOnlyInput operation returned by the
 *         service.<br/>
 *         The CompletableFuture returned by this method can be completed exceptionally with the following
 *         exceptions.
 *         <ul>
 *         <li>SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
 *         Can be used for catch all scenarios.</li>
 *         <li>SdkClientException If any client side error occurs such as an IO related failure, failure to get
 *         credentials, etc.</li>
 *         <li>JsonException Base class for all service exceptions. Unknown exceptions will be thrown as an instance
 *         of this type.</li>
 *         </ul>
 * @sample JsonAsyncClient.EventStreamOperationWithOnlyInput
 * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/json-service-2010-05-08/EventStreamOperationWithOnlyInput"
 *      target="_top">AWS API Documentation</a>
 */
@Override
public CompletableFuture<EventStreamOperationWithOnlyInputResponse> eventStreamOperationWithOnlyInput(
        EventStreamOperationWithOnlyInputRequest eventStreamOperationWithOnlyInputRequest,
        Publisher<InputEventStreamTwo> requestStream) {
    try {
        eventStreamOperationWithOnlyInputRequest = applySignerOverride(eventStreamOperationWithOnlyInputRequest,
                EventStreamAws4Signer.create());
        JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false)
                .isPayloadJson(true).build();

        HttpResponseHandler<EventStreamOperationWithOnlyInputResponse> responseHandler = protocolFactory
                .createResponseHandler(operationMetadata, EventStreamOperationWithOnlyInputResponse::builder);

        HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory,
                operationMetadata);
        EventStreamTaggedUnionJsonMarshaller eventMarshaller = EventStreamTaggedUnionJsonMarshaller.builder()
                .putMarshaller(InputEvent.class, new InputEventMarshaller(protocolFactory))
                .putMarshaller(InputEventTwo.class, new InputEventTwoMarshaller(protocolFactory)).build();
        SdkPublisher<InputEventStreamTwo> eventPublisher = SdkPublisher.adapt(requestStream);
        Publisher<ByteBuffer> adapted = eventPublisher.map(event -> eventMarshaller.marshall(event)).map(
                AwsClientHandlerUtils::encodeEventStreamRequestToByteBuffer);

        CompletableFuture<EventStreamOperationWithOnlyInputResponse> executeFuture = clientHandler
                .execute(new ClientExecutionParams<EventStreamOperationWithOnlyInputRequest, EventStreamOperationWithOnlyInputResponse>()
                        .withOperationName("EventStreamOperationWithOnlyInput")
                        .withMarshaller(new EventStreamOperationWithOnlyInputRequestMarshaller(protocolFactory))
                        .withAsyncRequestBody(software.amazon.awssdk.core.async.AsyncRequestBody.fromPublisher(adapted))
                        .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler)
                        .withInput(eventStreamOperationWithOnlyInputRequest));
        return executeFuture;
    } catch (Throwable t) {
        return CompletableFutureUtils.failedFuture(t);
    }
}
 
Example #25
Source File: test-async-client-class.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Some operation with a streaming input
 *
 * @param streamingInputOperationRequest
 * @param requestBody
 *        Functional interface that can be implemented to produce the request content in a non-blocking manner. The
 *        size of the content is expected to be known up front. See {@link AsyncRequestBody} for specific details on
 *        implementing this interface as well as links to precanned implementations for common scenarios like
 *        uploading from a file. The service documentation for the request content is as follows 'This be a stream'
 * @return A Java Future containing the result of the StreamingInputOperation operation returned by the service.<br/>
 *         The CompletableFuture returned by this method can be completed exceptionally with the following
 *         exceptions.
 *         <ul>
 *         <li>SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
 *         Can be used for catch all scenarios.</li>
 *         <li>SdkClientException If any client side error occurs such as an IO related failure, failure to get
 *         credentials, etc.</li>
 *         <li>JsonException Base class for all service exceptions. Unknown exceptions will be thrown as an instance
 *         of this type.</li>
 *         </ul>
 * @sample JsonAsyncClient.StreamingInputOperation
 * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/json-service-2010-05-08/StreamingInputOperation"
 *      target="_top">AWS API Documentation</a>
 */
@Override
public CompletableFuture<StreamingInputOperationResponse> streamingInputOperation(
        StreamingInputOperationRequest streamingInputOperationRequest, AsyncRequestBody requestBody) {
    try {
        JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false)
                .isPayloadJson(true).build();

        HttpResponseHandler<StreamingInputOperationResponse> responseHandler = protocolFactory.createResponseHandler(
                operationMetadata, StreamingInputOperationResponse::builder);

        HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory,
                operationMetadata);

        CompletableFuture<StreamingInputOperationResponse> executeFuture = clientHandler
                .execute(new ClientExecutionParams<StreamingInputOperationRequest, StreamingInputOperationResponse>()
                        .withOperationName("StreamingInputOperation")
                        .withMarshaller(
                            AsyncStreamingRequestMarshaller.builder()
                                                           .delegateMarshaller(new StreamingInputOperationRequestMarshaller(protocolFactory))
                                                           .asyncRequestBody(requestBody).build()).withResponseHandler(responseHandler)
                        .withErrorResponseHandler(errorResponseHandler).withAsyncRequestBody(requestBody)
                        .withInput(streamingInputOperationRequest));
        return executeFuture;
    } catch (Throwable t) {
        return CompletableFutureUtils.failedFuture(t);
    }
}
 
Example #26
Source File: BaseAsyncClientHandler.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Invoke the request using the http client. Assumes credentials (or lack thereof) have been
 * configured in the ExecutionContext beforehand.
 **/
private <InputT extends SdkRequest, OutputT> CompletableFuture<OutputT> invoke(
    SdkHttpFullRequest request,
    AsyncRequestBody requestProvider,
    InputT originalRequest,
    ExecutionContext executionContext,
    TransformingAsyncResponseHandler<Response<OutputT>> responseHandler) {
    return client.requestExecutionBuilder()
                 .requestProvider(requestProvider)
                 .request(request)
                 .originalRequest(originalRequest)
                 .executionContext(executionContext)
                 .execute(responseHandler);
}
 
Example #27
Source File: BaseAsyncAws4Signer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public AsyncRequestBody signAsyncRequestBody(SdkHttpFullRequest request, AsyncRequestBody asyncRequestBody,
                                             ExecutionAttributes executionAttributes) {
    Aws4SignerParams signingParams = extractSignerParams(Aws4SignerParams.builder(), executionAttributes)
        .build();
    Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);

    return signAsync(request, asyncRequestBody, requestParams, signingParams);
}
 
Example #28
Source File: BaseAsyncAws4Signer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * This method is only used in test, where clockOverride is passed in signingParams
 */
@SdkTestInternalApi
protected final AsyncRequestBody signAsync(SdkHttpFullRequest request, AsyncRequestBody asyncRequestBody,
                                           Aws4SignerRequestParams requestParams, Aws4SignerParams signingParams) {
    String headerSignature = getHeaderSignature(request);
    return transformRequestProvider(headerSignature, requestParams, signingParams, asyncRequestBody);
}
 
Example #29
Source File: AsyncChecksumValidationInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
                                                         ExecutionAttributes executionAttributes) {
    boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest());

    if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) {
        SdkChecksum checksum = new Md5Checksum();
        executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true);
        executionAttributes.putAttribute(CHECKSUM, checksum);
        return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum));
    }

    return context.asyncRequestBody();
}
 
Example #30
Source File: Aws4EventStreamSignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventStreamSigning() {
    TestVector testVector = generateTestVector();
    SdkHttpFullRequest.Builder request = testVector.httpFullRequest();
    AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret");
    SdkHttpFullRequest signedRequest =
        SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingClock(), "us-east-1");

    AsyncRequestBody transformedPublisher =
        SignerTestUtils.signAsyncRequest(signer, signedRequest, testVector.requestBodyPublisher(),
                                         credentials, "demo", signingClock(), "us-east-1");

    TestSubscriber testSubscriber = TestSubscriber.create();

    Flowable.fromPublisher(transformedPublisher)
            .flatMap(new Function<ByteBuffer, Publisher<?>>() {
                Queue<Message> messages = new LinkedList<>();
                MessageDecoder decoder = new MessageDecoder(message -> messages.offer(message));

                @Override
                public Publisher<?> apply(ByteBuffer byteBuffer) throws Exception {
                    decoder.feed(byteBuffer.array());
                    List<Message> messageList = new ArrayList<>();
                    while (!messages.isEmpty()) {
                        messageList.add(messages.poll());
                    }

                    return Flowable.fromIterable(messageList);
                }
            })
            .subscribe(testSubscriber);

    testSubscriber.assertNoErrors();
    testSubscriber.assertComplete();
    testSubscriber.assertValueSequence(testVector.expectedMessagePublisher().blockingIterable());
}