software.amazon.awssdk.http.SdkHttpMethod Java Examples

The following examples show how to use software.amazon.awssdk.http.SdkHttpMethod. 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: AsyncChecksumValidationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum() {
    SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();

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

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

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

    Context.AfterUnmarshalling afterUnmarshallingContext =
        InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse);

    interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum());
}
 
Example #2
Source File: NettyNioAsyncHttpClientSpiVerificationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private SdkHttpFullRequest createRequest(URI endpoint,
                                         String resourcePath,
                                         String body,
                                         SdkHttpMethod method,
                                         Map<String, String> params) {

    String contentLength = body == null ? null : String.valueOf(body.getBytes(UTF_8).length);
    return SdkHttpFullRequest.builder()
                             .uri(endpoint)
                             .method(method)
                             .encodedPath(resourcePath)
                             .applyMutation(b -> params.forEach(b::putRawQueryParameter))
                             .applyMutation(b -> {
                                 b.putHeader("Host", endpoint.getHost());
                                 if (contentLength != null) {
                                     b.putHeader("Content-Length", contentLength);
                                 }
                             }).build();
}
 
Example #3
Source File: SyncChecksumValidationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum() {
    SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();

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

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

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

    Context.AfterUnmarshalling afterUnmarshallingContext =
        InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse);

    interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum());
}
 
Example #4
Source File: EventStreamJsonMarshallerSpec.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
protected FieldSpec operationInfoField() {
    CodeBlock.Builder builder =
        CodeBlock.builder()
                 .add("$T.builder()", OperationInfo.class)
                 .add(".hasExplicitPayloadMember($L)", shapeModel.isHasPayloadMember() ||
                                                       shapeModel.getExplicitEventPayloadMember() != null)
                 .add(".hasPayloadMembers($L)", shapeModel.hasPayloadMembers())
                 // Adding httpMethod to avoid validation failure while creating the SdkHttpFullRequest
                 .add(".httpMethod($T.GET)", SdkHttpMethod.class)
                 .add(".hasEvent(true)")
                 .add(".build()");


    return FieldSpec.builder(ClassName.get(OperationInfo.class), "SDK_OPERATION_BINDING")
                    .addModifiers(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC)
                    .initializer(builder.build())
                    .build();
}
 
Example #5
Source File: NettyNioAsyncHttpClientWireMockTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private SdkHttpFullRequest createRequest(URI uri,
                                     String resourcePath,
                                     String body,
                                     SdkHttpMethod method,
                                     Map<String, String> params) {
    String contentLength = body == null ? null : String.valueOf(body.getBytes(UTF_8).length);
    return SdkHttpFullRequest.builder()
                             .uri(uri)
                             .method(method)
                             .encodedPath(resourcePath)
                             .applyMutation(b -> params.forEach(b::putRawQueryParameter))
                             .applyMutation(b -> {
                                 b.putHeader("Host", uri.getHost());
                                 if (contentLength != null) {
                                     b.putHeader("Content-Length", contentLength);
                                 }
                             }).build();
}
 
Example #6
Source File: NettyNioAsyncHttpClientWireMockTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void canSendContentAndGetThatContentBack() throws Exception {
    String body = randomAlphabetic(50);
    stubFor(any(urlEqualTo("/echo?reversed=true"))
                    .withRequestBody(equalTo(body))
                    .willReturn(aResponse().withBody(reverse(body))));
    URI uri = URI.create("http://localhost:" + mockServer.port());

    SdkHttpRequest request = createRequest(uri, "/echo", body, SdkHttpMethod.POST, singletonMap("reversed", "true"));

    RecordingResponseHandler recorder = new RecordingResponseHandler();
    client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider(body)).responseHandler(recorder).build());

    recorder.completeFuture.get(5, TimeUnit.SECONDS);

    verify(1, postRequestedFor(urlEqualTo("/echo?reversed=true")));

    assertThat(recorder.fullResponseAsString()).isEqualTo(reverse(body));
}
 
Example #7
Source File: ConnectionReaperTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void makeRequest(SdkAsyncHttpClient client) {
    stubFor(WireMock.any(urlPathEqualTo("/")).willReturn(aResponse().withBody(randomAlphabetic(10))));

    URI uri = URI.create("http://localhost:" + mockServer.port());
    client.execute(AsyncExecuteRequest.builder()
                                      .request(SdkHttpRequest.builder()
                                                             .uri(uri)
                                                             .method(SdkHttpMethod.GET)
                                                             .encodedPath("/")
                                                             .putHeader("Host", uri.getHost())
                                                             .build())
                                      .requestContentPublisher(new EmptyPublisher())
                                      .responseHandler(new RecordingResponseHandler())
                                      .build())
          .join();
}
 
Example #8
Source File: AsyncChecksumValidationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void afterUnmarshalling_putObjectRequest_with_SSE_shouldNotValidateChecksum() {
    SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();

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

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

    SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder()
                                                      .putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString())
                                                      .putHeader("x-amz-server-side-encryption-aws-kms-key-id", ENABLE_MD5_CHECKSUM_HEADER_VALUE)
                                                      .uri(URI.create("http://localhost:8080"))
                                                      .method(SdkHttpMethod.PUT)
                                                      .build();

    Context.AfterUnmarshalling afterUnmarshallingContext =
        InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse);

    interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum());
}
 
Example #9
Source File: DefaultPollyPresigner.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void initializePresignedRequest(PresignedRequest.Builder presignedRequest,
                                        ExecutionAttributes execAttrs,
                                        SdkHttpFullRequest signedHttpRequest) {
    List<String> signedHeadersQueryParam = signedHttpRequest.rawQueryParameters().get("X-Amz-SignedHeaders");

    Map<String, List<String>> signedHeaders =
            signedHeadersQueryParam.stream()
                    .flatMap(h -> Stream.of(h.split(";")))
                    .collect(toMap(h -> h, h -> signedHttpRequest.firstMatchingHeader(h)
                            .map(Collections::singletonList)
                            .orElseGet(ArrayList::new)));

    boolean isBrowserExecutable = signedHttpRequest.method() == SdkHttpMethod.GET &&
            (signedHeaders.isEmpty() ||
                    (signedHeaders.size() == 1 && signedHeaders.containsKey("host")));

    presignedRequest.expiration(execAttrs.getAttribute(PRESIGNER_EXPIRATION))
            .isBrowserExecutable(isBrowserExecutable)
            .httpRequest(signedHttpRequest)
            .signedHeaders(signedHeaders);
}
 
Example #10
Source File: RequestAdapterTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void adapt_defaultPortUsed() {
    SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
            .uri(URI.create("http://localhost:80/"))
            .method(SdkHttpMethod.HEAD)
            .build();
    HttpRequest result = h1Adapter.adapt(sdkRequest);
    List<String> hostHeaders = result.headers()
            .getAll(HttpHeaderNames.HOST.toString());
    assertNotNull(hostHeaders);
    assertEquals(1, hostHeaders.size());
    assertEquals("localhost", hostHeaders.get(0));

    sdkRequest = SdkHttpRequest.builder()
            .uri(URI.create("https://localhost:443/"))
            .method(SdkHttpMethod.HEAD)
            .build();
    result = h1Adapter.adapt(sdkRequest);
    hostHeaders = result.headers()
            .getAll(HttpHeaderNames.HOST.toString());
    assertNotNull(hostHeaders);
    assertEquals(1, hostHeaders.size());
    assertEquals("localhost", hostHeaders.get(0));
}
 
Example #11
Source File: RequestAdapterTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void adapt_h1Request_requestIsCorrect() {
    SdkHttpRequest request = SdkHttpRequest.builder()
            .uri(URI.create("http://localhost:12345/foo/bar/baz"))
            .putRawQueryParameter("foo", "bar")
            .putRawQueryParameter("bar", "baz")
            .putHeader("header1", "header1val")
            .putHeader("header2", "header2val")
            .method(SdkHttpMethod.GET)
            .build();

    HttpRequest adapted = h1Adapter.adapt(request);

    assertThat(adapted.method()).isEqualTo(HttpMethod.valueOf("GET"));
    assertThat(adapted.uri()).isEqualTo("/foo/bar/baz?foo=bar&bar=baz");
    assertThat(adapted.protocolVersion()).isEqualTo(HttpVersion.HTTP_1_1);
    assertThat(adapted.headers().getAll("Host")).containsExactly("localhost:12345");
    assertThat(adapted.headers().getAll("header1")).containsExactly("header1val");
    assertThat(adapted.headers().getAll("header2")).containsExactly("header2val");
}
 
Example #12
Source File: RequestAdapterTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void adapt_noPathContainsQueryParams() {
    SdkHttpRequest request = SdkHttpRequest.builder()
            .host("localhost:12345")
            .protocol("http")
            .putRawQueryParameter("foo", "bar")
            .putRawQueryParameter("bar", "baz")
            .putHeader("header1", "header1val")
            .putHeader("header2", "header2val")
            .method(SdkHttpMethod.GET)
            .build();

    HttpRequest adapted = h1Adapter.adapt(request);

    assertThat(adapted.method()).isEqualTo(HttpMethod.valueOf("GET"));
    assertThat(adapted.uri()).isEqualTo("/?foo=bar&bar=baz");
    assertThat(adapted.protocolVersion()).isEqualTo(HttpVersion.HTTP_1_1);
    assertThat(adapted.headers().getAll("Host")).containsExactly("localhost:12345");
}
 
Example #13
Source File: GeneratePreSignUrlInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void copySnapshotRequest_httpsProtocolAddedToEndpoint() {
    SdkHttpFullRequest request = SdkHttpFullRequest.builder()
            .uri(URI.create("https://ec2.us-west-2.amazonaws.com"))
            .method(SdkHttpMethod.POST)
            .build();

    CopySnapshotRequest ec2Request = CopySnapshotRequest.builder()
            .sourceRegion("us-west-2")
            .destinationRegion("us-east-2")
            .build();

    when(mockContext.httpRequest()).thenReturn(request);
    when(mockContext.request()).thenReturn(ec2Request);

    ExecutionAttributes attrs = new ExecutionAttributes();
    attrs.putAttribute(AWS_CREDENTIALS, AwsBasicCredentials.create("foo", "bar"));

    SdkHttpRequest modifiedRequest = INTERCEPTOR.modifyHttpRequest(mockContext, attrs);

    String presignedUrl = modifiedRequest.rawQueryParameters().get("PresignedUrl").get(0);

    assertThat(presignedUrl).startsWith("https://");
}
 
Example #14
Source File: ConnectionPoolMaxConnectionsIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60 * 1000)
public void leasing_a_new_connection_fails_with_connection_pool_timeout() {

    AmazonSyncHttpClient httpClient = HttpTestUtils.testClientBuilder()
                                                   .retryPolicy(RetryPolicy.none())
                                                   .httpClient(ApacheHttpClient.builder()
                                                                               .connectionTimeout(Duration.ofMillis(100))
                                                                               .maxConnections(1)
                                                                               .build())
                                                   .build();

    SdkHttpFullRequest request = server.configureHttpEndpoint(SdkHttpFullRequest.builder())
                                       .method(SdkHttpMethod.GET)
                                       .build();

    // Block the first connection in the pool with this request.
    httpClient.requestExecutionBuilder()
              .request(request)
              .originalRequest(NoopTestRequest.builder().build())
              .executionContext(executionContext(request))
              .execute(combinedSyncResponseHandler(new EmptySdkResponseHandler(), null));

    try {
        // A new connection will be leased here which would fail in
        // ConnectionPoolTimeoutException.
        httpClient.requestExecutionBuilder()
                  .request(request)
                  .originalRequest(NoopTestRequest.builder().build())
                  .executionContext(executionContext(request))
                  .execute(combinedSyncResponseHandler(null, null));
        Assert.fail("Connection pool timeout exception is expected!");
    } catch (SdkClientException e) {
        Assert.assertTrue(e.getCause() instanceof ConnectionPoolTimeoutException);
    }
}
 
Example #15
Source File: Aws4SignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private SdkHttpFullRequest.Builder generateBasicRequest() {
    return SdkHttpFullRequest.builder()
                             .contentStreamProvider(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes()))
                             .method(SdkHttpMethod.POST)
                             .putHeader("Host", "demo.us-east-1.amazonaws.com")
                             .putHeader("x-amz-archive-description", "test  test")
                             .encodedPath("/")
                             .uri(URI.create("http://demo.us-east-1.amazonaws.com"));
}
 
Example #16
Source File: MakeAsyncHttpRequestStage.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private boolean shouldSetContentLength(SdkHttpFullRequest request, SdkHttpContentPublisher requestProvider) {

        if (request.method() == SdkHttpMethod.GET || request.method() == SdkHttpMethod.HEAD ||
            request.firstMatchingHeader(CONTENT_LENGTH).isPresent()) {
            return false;
        }

        return Optional.ofNullable(requestProvider).flatMap(SdkHttpContentPublisher::contentLength).isPresent();
    }
 
Example #17
Source File: ApacheHttpRequestFactoryTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultHttpPortsAreNotInDefaultHostHeader() {
    SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
            .uri(URI.create("http://localhost:80/"))
            .method(SdkHttpMethod.HEAD)
            .build();
    HttpExecuteRequest request = HttpExecuteRequest.builder()
            .request(sdkRequest)
            .build();
    HttpRequestBase result = instance.create(request, requestConfig);
    Header[] hostHeaders = result.getHeaders(HttpHeaders.HOST);
    assertNotNull(hostHeaders);
    assertEquals(1, hostHeaders.length);
    assertEquals("localhost", hostHeaders[0].getValue());

    sdkRequest = SdkHttpRequest.builder()
            .uri(URI.create("https://localhost:443/"))
            .method(SdkHttpMethod.HEAD)
            .build();
    request = HttpExecuteRequest.builder()
            .request(sdkRequest)
            .build();
    result = instance.create(request, requestConfig);
    hostHeaders = result.getHeaders(HttpHeaders.HOST);
    assertNotNull(hostHeaders);
    assertEquals(1, hostHeaders.length);
    assertEquals("localhost", hostHeaders[0].getValue());
}
 
Example #18
Source File: ProtocolUtilsTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void createSdkHttpRequest_NoTrailingOrLeadingSlash_RequestUriAppendedToEndpointPath() {
    SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
        OperationInfo.builder()
                     .httpMethod(SdkHttpMethod.DELETE)
                     .requestUri("baz")
                     .build(), URI.create("http://localhost/foo/bar"));
    assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz");
}
 
Example #19
Source File: ProtocolUtilsTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void createSdkHttpRequest_NoTrailingSlashInEndpointPath_RequestUriAppendedToEndpointPath() {
    SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
        OperationInfo.builder()
                     .httpMethod(SdkHttpMethod.DELETE)
                     .requestUri("/baz")
                     .build(), URI.create("http://localhost/foo/bar"));
    assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz");
}
 
Example #20
Source File: ProtocolUtilsTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void createSdkHttpRequest_RequestUriAppendedToEndpointPath() {
    SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
        OperationInfo.builder()
                     .httpMethod(SdkHttpMethod.DELETE)
                     .requestUri("/baz")
                     .build(), URI.create("http://localhost/foo/bar/"));
    assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz");
}
 
Example #21
Source File: ApacheHttpRequestFactoryTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void ceateSetsHostHeaderByDefault() {
    SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
            .uri(URI.create("http://localhost:12345/"))
            .method(SdkHttpMethod.HEAD)
            .build();
    HttpExecuteRequest request = HttpExecuteRequest.builder()
            .request(sdkRequest)
            .build();
    HttpRequestBase result = instance.create(request, requestConfig);
    Header[] hostHeaders = result.getHeaders(HttpHeaders.HOST);
    assertNotNull(hostHeaders);
    assertEquals(1, hostHeaders.length);
    assertEquals("localhost:12345", hostHeaders[0].getValue());
}
 
Example #22
Source File: SyncStreamingRequestMarshallerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private SdkHttpFullRequest generateBasicRequest() {
    return SdkHttpFullRequest.builder()
                             .contentStreamProvider(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes()))
                             .method(SdkHttpMethod.POST)
                             .putHeader("Host", "demo.us-east-1.amazonaws.com")
                             .putHeader("x-amz-archive-description", "test  test")
                             .encodedPath("/")
                             .uri(URI.create("http://demo.us-east-1.amazonaws.com"))
                             .build();
}
 
Example #23
Source File: AmazonHttpClientSslHandshakeTimeoutIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60 * 1000)
public void testSslHandshakeTimeout() {
    AmazonSyncHttpClient httpClient = HttpTestUtils.testClientBuilder()
                                                   .retryPolicy(RetryPolicy.none())
                                                   .httpClient(ApacheHttpClient.builder()
                                                                           .socketTimeout(CLIENT_SOCKET_TO)
                                                                           .build())
                                                   .build();

    System.out.println("Sending request to localhost...");

    try {
        SdkHttpFullRequest request = server.configureHttpsEndpoint(SdkHttpFullRequest.builder())
                                           .method(SdkHttpMethod.GET)
                                           .build();
        httpClient.requestExecutionBuilder()
                  .request(request)
                  .originalRequest(NoopTestRequest.builder().build())
                  .executionContext(executionContext(request))
                  .execute(combinedSyncResponseHandler(null, new NullErrorResponseHandler()));
        fail("Client-side socket read timeout is expected!");

    } catch (SdkClientException e) {
        /**
         * Http client catches the SocketTimeoutException and throws a
         * ConnectTimeoutException.
         * {@link DefaultHttpClientConnectionOperator#connect(ManagedHttpClientConnection, HttpHost,
         * InetSocketAddress, int, SocketConfig, HttpContext)}
         */
        Assert.assertTrue(e.getCause() instanceof ConnectTimeoutException);

        ConnectTimeoutException cte = (ConnectTimeoutException) e.getCause();
        Assert.assertThat(cte.getMessage(), org.hamcrest.Matchers
                .containsString("Read timed out"));
    }
}
 
Example #24
Source File: ProtocolUtilsTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void createSdkHttpRequest_EndpointWithPathSetCorrectly() {
    SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
        OperationInfo.builder()
                     .httpMethod(SdkHttpMethod.DELETE)
                     .build(), URI.create("http://localhost/foo/bar"));
    assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar");
}
 
Example #25
Source File: PingTimeoutTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<Void> makeRequest(Duration healthCheckPingPeriod) {
    netty = NettyNioAsyncHttpClient.builder()
            .protocol(Protocol.HTTP2)
            .http2Configuration(Http2Configuration.builder().healthCheckPingPeriod(healthCheckPingPeriod).build())
            .build();

    SdkHttpFullRequest request = SdkHttpFullRequest.builder()
            .protocol("http")
            .host("localhost")
            .port(server.port())
            .method(SdkHttpMethod.GET)
            .build();

    AsyncExecuteRequest executeRequest = AsyncExecuteRequest.builder()
            .fullDuplex(false)
            .request(request)
            .requestContentPublisher(new EmptyPublisher())
            .responseHandler(new SdkAsyncHttpResponseHandler() {
                @Override
                public void onHeaders(SdkHttpResponse headers) {
                }

                @Override
                public void onStream(Publisher<ByteBuffer> stream) {
                    stream.subscribe(new Subscriber<ByteBuffer>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Integer.MAX_VALUE);
                        }

                        @Override
                        public void onNext(ByteBuffer byteBuffer) {
                        }

                        @Override
                        public void onError(Throwable t) {
                        }

                        @Override
                        public void onComplete() {
                        }
                    });
                }

                @Override
                public void onError(Throwable error) {
                }
            })
            .build();

    return netty.execute(executeRequest);
}
 
Example #26
Source File: NettyNioAsyncHttpClientWireMockTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void closeMethodClosesOpenedChannels() throws InterruptedException, TimeoutException, ExecutionException {
    String body = randomAlphabetic(10);
    URI uri = URI.create("https://localhost:" + mockServer.httpsPort());
    stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withHeader("Some-Header", "With Value").withBody(body)));

    SdkHttpFullRequest request = createRequest(uri, "/", body, SdkHttpMethod.POST, Collections.emptyMap());
    RecordingResponseHandler recorder = new RecordingResponseHandler();

    CompletableFuture<Boolean> channelClosedFuture = new CompletableFuture<>();
    ChannelFactory<NioSocketChannel> channelFactory = new ChannelFactory<NioSocketChannel>() {
        @Override
        public NioSocketChannel newChannel() {
            return new NioSocketChannel() {
                @Override
                public ChannelFuture close() {
                    ChannelFuture cf = super.close();
                    channelClosedFuture.complete(true);
                    return cf;
                }
            };
        }
    };

    SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder()
            .eventLoopGroup(new SdkEventLoopGroup(new NioEventLoopGroup(1), channelFactory))
            .buildWithDefaults(mapWithTrustAllCerts());

    try {
        customClient.execute(AsyncExecuteRequest.builder()
                .request(request)
                .requestContentPublisher(createProvider(body))
                .responseHandler(recorder).build())
                .join();
    } finally {
        customClient.close();
    }

    assertThat(channelClosedFuture.get(5, TimeUnit.SECONDS)).isTrue();
}
 
Example #27
Source File: RequestAdapterTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void adapt_nonStandardHttpsPort() {
    SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
            .uri(URI.create("https://localhost:8443/"))
            .method(SdkHttpMethod.HEAD)
            .build();
    HttpRequest result = h1Adapter.adapt(sdkRequest);
    List<String> hostHeaders = result.headers()
            .getAll(HttpHeaderNames.HOST.toString());

    assertThat(hostHeaders).containsExactly("localhost:8443");
}
 
Example #28
Source File: ArmeriaSdkHttpClient.java    From curiostack with MIT License 5 votes vote down vote up
private static HttpMethod convert(SdkHttpMethod method) {
  switch (method) {
    case GET:
      return HttpMethod.GET;
    case POST:
      return HttpMethod.POST;
    case PUT:
      return HttpMethod.PUT;
    case DELETE:
      return HttpMethod.DELETE;
    case HEAD:
      return HttpMethod.HEAD;
    case PATCH:
      return HttpMethod.PATCH;
    case OPTIONS:
      return HttpMethod.OPTIONS;
    default:
      try {
        return HttpMethod.valueOf(method.name());
      } catch (IllegalArgumentException unused) {
        throw new IllegalArgumentException(
            "Unknown SdkHttpMethod: "
                + method
                + ". Cannot convert to an Armeria request. This could only practically happen if "
                + "the HTTP standard has new methods added and is very unlikely.");
      }
  }
}
 
Example #29
Source File: RequestAdapterTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void adapt_pathEmpty_setToRoot() {
    SdkHttpRequest request = SdkHttpRequest.builder()
            .uri(URI.create("http://localhost:12345"))
            .method(SdkHttpMethod.GET)
            .build();

    HttpRequest adapted = h1Adapter.adapt(request);

    assertThat(adapted.uri()).isEqualTo("/");
}
 
Example #30
Source File: RequestAdapterTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void adapt_containsQueryParamsRequiringEncoding() {
    SdkHttpRequest request = SdkHttpRequest.builder()
            .uri(URI.create("http://localhost:12345"))
            .putRawQueryParameter("java", "☕")
            .putRawQueryParameter("python", "\uD83D\uDC0D")
            .method(SdkHttpMethod.GET)
            .build();

    HttpRequest adapted = h1Adapter.adapt(request);

    assertThat(adapted.uri()).isEqualTo("/?java=%E2%98%95&python=%F0%9F%90%8D");
}