index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/EmptyPublisher.java | package software.amazon.awssdk.http.crt;
import java.nio.ByteBuffer;
import java.util.Optional;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
public class EmptyPublisher implements SdkHttpContentPublisher {
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
subscriber.onSubscribe(new EmptySubscription(subscriber));
}
@Override
public Optional<Long> contentLength() {
return Optional.of(0L);
}
private static class EmptySubscription implements Subscription {
private final Subscriber subscriber;
private volatile boolean done;
EmptySubscription(Subscriber subscriber) {
this.subscriber = subscriber;
}
@Override
public void request(long l) {
if (!done) {
done = true;
if (l <= 0) {
this.subscriber.onError(new IllegalArgumentException("Demand must be positive"));
} else {
this.subscriber.onComplete();
}
}
}
@Override
public void cancel() {
done = true;
}
}
}
| 1,000 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/ProxyWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.crt.io.EventLoopGroup;
import software.amazon.awssdk.crt.io.HostResolver;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
/**
* Tests for HTTP proxy functionality in the CRT client.
*/
public class ProxyWireMockTest {
private SdkAsyncHttpClient client;
private ProxyConfiguration proxyCfg;
private WireMockServer mockProxy = new WireMockServer(new WireMockConfiguration()
.dynamicPort()
.dynamicHttpsPort()
.enableBrowserProxying(true)); // make the mock proxy actually forward (to the mock server for our test)
private WireMockServer mockServer = new WireMockServer(new WireMockConfiguration()
.dynamicPort()
.dynamicHttpsPort());
@BeforeEach
public void setup() {
mockProxy.start();
mockServer.start();
mockServer.stubFor(get(urlMatching(".*")).willReturn(aResponse().withStatus(200).withBody("hello")));
proxyCfg = ProxyConfiguration.builder()
.host("localhost")
.port(mockProxy.port())
.build();
client = AwsCrtAsyncHttpClient.builder()
.proxyConfiguration(proxyCfg)
.build();
}
@AfterEach
public void teardown() {
mockServer.stop();
mockProxy.stop();
client.close();
EventLoopGroup.closeStaticDefault();
HostResolver.closeStaticDefault();
CrtResource.waitForNoResources();
}
/*
* Note the contrast between this test and the netty connect test. The CRT proxy implementation does not
* do a CONNECT call for requests using http, so by configuring the proxy mock to forward and the server mock
* to return success, we can actually create an end-to-end test.
*
* We have an outstanding request to change this behavior to match https (use a CONNECT call). Once that
* change happens, this test will break and need to be updated to be more like the netty one.
*/
@Test
public void proxyConfigured_httpGet() throws Throwable {
CompletableFuture<Boolean> streamReceived = new CompletableFuture<>();
AtomicReference<SdkHttpResponse> response = new AtomicReference<>(null);
AtomicReference<Throwable> error = new AtomicReference<>(null);
Subscriber<ByteBuffer> subscriber = CrtHttpClientTestUtils.createDummySubscriber();
SdkAsyncHttpResponseHandler handler = CrtHttpClientTestUtils.createTestResponseHandler(response, streamReceived, error, subscriber);
URI uri = URI.create("http://localhost:" + mockServer.port());
SdkHttpRequest request = CrtHttpClientTestUtils.createRequest(uri, "/server/test", null, SdkHttpMethod.GET, emptyMap());
CompletableFuture future = client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new EmptyPublisher())
.build());
future.get(60, TimeUnit.SECONDS);
assertThat(error.get()).isNull();
assertThat(streamReceived.get(60, TimeUnit.SECONDS)).isTrue();
assertThat(response.get().statusCode()).isEqualTo(200);
}
}
| 1,001 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/CrtHttpClientTestUtils.java | package software.amazon.awssdk.http.crt;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.Collections.emptyMap;
public class CrtHttpClientTestUtils {
static Subscriber<ByteBuffer> createDummySubscriber() {
return new Subscriber<ByteBuffer>() {
@Override
public void onSubscribe(Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(ByteBuffer byteBuffer) {
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
};
}
static SdkAsyncHttpResponseHandler createTestResponseHandler(AtomicReference<SdkHttpResponse> response,
CompletableFuture<Boolean> streamReceived,
AtomicReference<Throwable> error,
Subscriber<ByteBuffer> subscriber) {
return new SdkAsyncHttpResponseHandler() {
@Override
public void onHeaders(SdkHttpResponse headers) {
response.compareAndSet(null, headers);
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
stream.subscribe(subscriber);
streamReceived.complete(true);
}
@Override
public void onError(Throwable t) {
error.compareAndSet(null, t);
}
};
}
public static SdkHttpFullRequest createRequest(URI endpoint) {
return createRequest(endpoint, "/", null, SdkHttpMethod.GET, emptyMap());
}
static SdkHttpFullRequest createRequest(URI endpoint,
String resourcePath,
byte[] body,
SdkHttpMethod method,
Map<String, String> params) {
String contentLength = (body == null) ? null : String.valueOf(body.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();
}
}
| 1,002 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/AwsCrtHttpClientWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.http.HttpTestUtils.createProvider;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.PROTOCOL;
import static software.amazon.awssdk.http.crt.CrtHttpClientTestUtils.createRequest;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.crt.Log;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.RecordingResponseHandler;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.utils.AttributeMap;
public class AwsCrtHttpClientWireMockTest {
@Rule
public WireMockRule mockServer = new WireMockRule(wireMockConfig()
.dynamicPort());
@BeforeClass
public static void setup() {
System.setProperty("aws.crt.debugnative", "true");
Log.initLoggingToStdout(Log.LogLevel.Warn);
}
@AfterClass
public static void tearDown() {
// Verify there is no resource leak.
CrtResource.waitForNoResources();
}
@Test
public void closeClient_reuse_throwException() throws Exception {
SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.create();
client.close();
assertThatThrownBy(() -> makeSimpleRequest(client)).hasMessageContaining("is closed");
}
@Test
public void invalidProtocol_shouldThrowException() {
AttributeMap attributeMap = AttributeMap.builder()
.put(PROTOCOL, Protocol.HTTP2)
.build();
assertThatThrownBy(() -> AwsCrtAsyncHttpClient.builder().buildWithDefaults(attributeMap))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void sendRequest_withCollector_shouldCollectMetrics() throws Exception {
try (SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.builder().maxConcurrency(10).build()) {
RecordingResponseHandler recorder = makeSimpleRequest(client);
MetricCollection metrics = recorder.collector().collect();
assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("AwsCommonRuntime");
assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(10);
assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES)).containsExactly(0);
assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY)).containsExactly(1);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0);
}
}
@Test
public void sharedEventLoopGroup_closeOneClient_shouldNotAffectOtherClients() throws Exception {
try (SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.create()) {
makeSimpleRequest(client);
}
try (SdkAsyncHttpClient anotherClient = AwsCrtAsyncHttpClient.create()) {
makeSimpleRequest(anotherClient);
}
}
/**
* Make a simple async request and wait for it to finish.
*
* @param client Client to make request with.
*/
private RecordingResponseHandler makeSimpleRequest(SdkAsyncHttpClient client) throws Exception {
String body = randomAlphabetic(10);
URI uri = URI.create("http://localhost:" + mockServer.port());
stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body)));
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder()
.request(request)
.requestContentPublisher(createProvider(""))
.responseHandler(recorder)
.metricCollector(recorder.collector())
.build());
recorder.completeFuture().get(5, TimeUnit.SECONDS);
return recorder;
}
}
| 1,003 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/SdkTestHttpContentPublisher.java | package software.amazon.awssdk.http.crt;
import java.nio.ByteBuffer;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
public class SdkTestHttpContentPublisher implements SdkHttpContentPublisher {
private final byte[] body;
private final AtomicReference<Subscriber<? super ByteBuffer>> subscriber = new AtomicReference<>(null);
private final AtomicBoolean complete = new AtomicBoolean(false);
public SdkTestHttpContentPublisher(byte[] body) {
this.body = body;
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
boolean wasFirstSubscriber = subscriber.compareAndSet(null, s);
SdkTestHttpContentPublisher publisher = this;
if (wasFirstSubscriber) {
s.onSubscribe(new Subscription() {
@Override
public void request(long n) {
publisher.request(n);
}
@Override
public void cancel() {
// Do nothing
}
});
} else {
s.onError(new RuntimeException("Only allow one subscriber"));
}
}
protected void request(long n) {
// Send the whole body if they request >0 ByteBuffers
if (n > 0 && !complete.get()) {
complete.set(true);
subscriber.get().onNext(ByteBuffer.wrap(body));
subscriber.get().onComplete();
}
}
@Override
public Optional<Long> contentLength() {
return Optional.of((long)body.length);
}
}
| 1,004 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/H1ServerBehaviorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.crt.Log;
import software.amazon.awssdk.http.SdkAsyncHttpClientH1TestSuite;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Testing the scenario where h1 server sends 5xx errors.
*/
public class H1ServerBehaviorTest extends SdkAsyncHttpClientH1TestSuite {
@BeforeAll
public static void beforeAll() {
System.setProperty("aws.crt.debugnative", "true");
Log.initLoggingToStdout(Log.LogLevel.Warn);
}
@AfterAll
public static void afterAll() {
CrtResource.waitForNoResources();
}
@Override
protected SdkAsyncHttpClient setupClient() {
return AwsCrtAsyncHttpClient.builder()
.buildWithDefaults(AttributeMap.builder().put(TRUST_ALL_CERTIFICATES, true).build());
}
}
| 1,005 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/CrtHttpProxyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URISyntaxException;
import software.amazon.awssdk.http.HttpProxyTestSuite;
import software.amazon.awssdk.http.proxy.TestProxySetting;
public class CrtHttpProxyTest extends HttpProxyTestSuite {
@Override
protected void assertProxyConfiguration(TestProxySetting userSetProxySettings,
TestProxySetting expectedProxySettings,
Boolean useSystemProperty, Boolean useEnvironmentVariable,
String protocol) throws URISyntaxException {
ProxyConfiguration.Builder proxyBuilder = ProxyConfiguration.builder();
if (userSetProxySettings != null) {
String hostName = userSetProxySettings.getHost();
Integer portNumber = userSetProxySettings.getPort();
String userName = userSetProxySettings.getUserName();
String password = userSetProxySettings.getPassword();
if (hostName != null) {
proxyBuilder.host(hostName);
}
if (portNumber != null) {
proxyBuilder.port(portNumber);
}
if (userName != null) {
proxyBuilder.username(userName);
}
if (password != null) {
proxyBuilder.password(password);
}
}
if (!"http".equals(protocol)) {
proxyBuilder.scheme(protocol);
}
if (useSystemProperty != null) {
proxyBuilder.useSystemPropertyValues(useSystemProperty);
}
if (useEnvironmentVariable != null) {
proxyBuilder.useEnvironmentVariableValues(useEnvironmentVariable);
}
ProxyConfiguration proxyConfiguration = proxyBuilder.build();
assertThat(proxyConfiguration.host()).isEqualTo(expectedProxySettings.getHost());
assertThat(proxyConfiguration.port()).isEqualTo(expectedProxySettings.getPort());
assertThat(proxyConfiguration.username()).isEqualTo(expectedProxySettings.getUserName());
assertThat(proxyConfiguration.password()).isEqualTo(expectedProxySettings.getPassword());
}
}
| 1,006 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/ProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Random;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link ProxyConfiguration}.
*/
public class ProxyConfigurationTest {
private static final Random RNG = new Random();
private static final String TEST_HOST = "foo.com";
private static final int TEST_PORT = 7777;
private static final String TEST_USER = "testuser";
private static final String TEST_PASSWORD = "123";
@BeforeEach
public void setup() {
clearProxyProperties();
}
@AfterAll
public static void cleanup() {
clearProxyProperties();
}
@Test
void build_setsAllProperties() {
verifyAllPropertiesSet(allPropertiesSetConfig());
}
@Test
void build_systemPropertyDefault_Http() {
setHttpProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder().build();
assertThat(config.host()).isEqualTo(TEST_HOST);
assertThat(config.port()).isEqualTo(TEST_PORT);
assertThat(config.username()).isEqualTo(TEST_USER);
assertThat(config.password()).isEqualTo(TEST_PASSWORD);
assertThat(config.scheme()).isNull();
}
@Test
void build_systemPropertyDefault_Https() {
setHttpsProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder()
.scheme("https")
.build();
assertThat(config.host()).isEqualTo(TEST_HOST);
assertThat(config.port()).isEqualTo(TEST_PORT);
assertThat(config.username()).isEqualTo(TEST_USER);
assertThat(config.password()).isEqualTo(TEST_PASSWORD);
assertThat(config.scheme()).isEqualTo("https");
}
@Test
void build_systemPropertyEnabled_Http() {
setHttpProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder().useSystemPropertyValues(Boolean.TRUE).build();
assertThat(config.host()).isEqualTo(TEST_HOST);
assertThat(config.port()).isEqualTo(TEST_PORT);
assertThat(config.username()).isEqualTo(TEST_USER);
assertThat(config.password()).isEqualTo(TEST_PASSWORD);
assertThat(config.scheme()).isNull();
}
@Test
void build_systemPropertyEnabled_Https() {
setHttpsProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder()
.scheme("https")
.useSystemPropertyValues(Boolean.TRUE).build();
assertThat(config.host()).isEqualTo(TEST_HOST);
assertThat(config.port()).isEqualTo(TEST_PORT);
assertThat(config.username()).isEqualTo(TEST_USER);
assertThat(config.password()).isEqualTo(TEST_PASSWORD);
assertThat(config.scheme()).isEqualTo("https");
}
@Test
void build_systemPropertyDisabled() {
setHttpProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder()
.host("localhost")
.port(8888)
.username("username")
.password("password")
.useSystemPropertyValues(Boolean.FALSE).build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(8888);
assertThat(config.username()).isEqualTo("username");
assertThat(config.password()).isEqualTo("password");
assertThat(config.scheme()).isNull();
}
@Test
void build_systemPropertyOverride() {
setHttpProxyProperties();
ProxyConfiguration config = ProxyConfiguration.builder()
.host("localhost")
.port(8888)
.username("username")
.password("password")
.build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(8888);
assertThat(config.username()).isEqualTo("username");
assertThat(config.password()).isEqualTo("password");
assertThat(config.scheme()).isNull();
}
@Test
void toBuilder_roundTrip_producesExactCopy() {
ProxyConfiguration original = allPropertiesSetConfig();
ProxyConfiguration copy = original.toBuilder().build();
assertThat(copy).isEqualTo(original);
}
@Test
void toBuilderModified_doesNotModifySource() {
ProxyConfiguration original = allPropertiesSetConfig();
ProxyConfiguration modified = setAllPropertiesToRandomValues(original.toBuilder()).build();
assertThat(original).isNotEqualTo(modified);
}
private ProxyConfiguration allPropertiesSetConfig() {
return setAllPropertiesToRandomValues(ProxyConfiguration.builder()).build();
}
private ProxyConfiguration.Builder setAllPropertiesToRandomValues(ProxyConfiguration.Builder builder) {
Stream.of(builder.getClass().getDeclaredMethods())
.filter(m -> m.getParameterCount() == 1 && m.getReturnType().equals(ProxyConfiguration.Builder.class))
.forEach(m -> {
try {
m.setAccessible(true);
setRandomValue(builder, m);
} catch (Exception e) {
throw new RuntimeException("Could not create random proxy config", e);
}
});
return builder;
}
private void setRandomValue(Object o, Method setter) throws InvocationTargetException, IllegalAccessException {
Class<?> paramClass = setter.getParameterTypes()[0];
if (String.class.equals(paramClass)) {
setter.invoke(o, randomString());
} else if (int.class.equals(paramClass)) {
setter.invoke(o, RNG.nextInt());
} else if (Boolean.class.equals(paramClass)) {
setter.invoke(o, RNG.nextBoolean());
} else {
throw new RuntimeException("Don't know how create random value for type " + paramClass);
}
}
private void verifyAllPropertiesSet(ProxyConfiguration cfg) {
boolean hasNullProperty = Stream.of(cfg.getClass().getDeclaredMethods())
.filter(m -> !m.getReturnType().equals(Void.class) && m.getParameterCount() == 0)
.anyMatch(m -> {
m.setAccessible(true);
try {
return m.invoke(cfg) == null;
} catch (Exception e) {
return true;
}
});
if (hasNullProperty) {
throw new RuntimeException("Given configuration has unset property");
}
}
private String randomString() {
String alpha = "abcdefghijklmnopqrstuwxyz";
StringBuilder sb = new StringBuilder(16);
for (int i = 0; i < 16; ++i) {
sb.append(alpha.charAt(RNG.nextInt(16)));
}
return sb.toString();
}
private void setHttpProxyProperties() {
System.setProperty("http.proxyHost", TEST_HOST);
System.setProperty("http.proxyPort", Integer.toString(TEST_PORT));
System.setProperty("http.proxyUser", TEST_USER);
System.setProperty("http.proxyPassword", TEST_PASSWORD);
}
private void setHttpsProxyProperties() {
System.setProperty("https.proxyHost", TEST_HOST);
System.setProperty("https.proxyPort", Integer.toString(TEST_PORT));
System.setProperty("https.proxyUser", TEST_USER);
System.setProperty("https.proxyPassword", TEST_PASSWORD);
}
private static void clearProxyProperties() {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
System.clearProperty("http.proxyUser");
System.clearProperty("http.proxyPassword");
System.clearProperty("https.proxyHost");
System.clearProperty("https.proxyPort");
System.clearProperty("https.proxyUser");
System.clearProperty("https.proxyPassword");
}
}
| 1,007 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/TcpKeepAliveConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Duration;
import org.junit.jupiter.api.Test;
public class TcpKeepAliveConfigurationTest {
@Test
public void builder_allPropertiesSet() {
TcpKeepAliveConfiguration tcpKeepAliveConfiguration =
TcpKeepAliveConfiguration.builder()
.keepAliveInterval(Duration.ofMinutes(1))
.keepAliveTimeout(Duration.ofSeconds(1))
.build();
assertThat(tcpKeepAliveConfiguration.keepAliveInterval()).isEqualTo(Duration.ofMinutes(1));
assertThat(tcpKeepAliveConfiguration.keepAliveTimeout()).isEqualTo(Duration.ofSeconds(1));
}
@Test
public void builder_nullKeepAliveTimeout_shouldThrowException() {
assertThatThrownBy(() ->
TcpKeepAliveConfiguration.builder()
.keepAliveInterval(Duration.ofMinutes(1))
.build())
.hasMessageContaining("keepAliveTimeout");
}
@Test
public void builder_nullKeepAliveInterval_shouldThrowException() {
assertThatThrownBy(() ->
TcpKeepAliveConfiguration.builder()
.keepAliveTimeout(Duration.ofSeconds(1))
.build())
.hasMessageContaining("keepAliveInterval");
}
@Test
public void builder_nonPositiveKeepAliveTimeout_shouldThrowException() {
assertThatThrownBy(() ->
TcpKeepAliveConfiguration.builder()
.keepAliveInterval(Duration.ofMinutes(1))
.keepAliveTimeout(Duration.ofSeconds(0))
.build())
.hasMessageContaining("keepAliveTimeout");
}
@Test
public void builder_nonPositiveKeepAliveInterval_shouldThrowException() {
assertThatThrownBy(() ->
TcpKeepAliveConfiguration.builder()
.keepAliveInterval(Duration.ofMinutes(0))
.keepAliveTimeout(Duration.ofSeconds(1))
.build())
.hasMessageContaining("keepAliveInterval");
}
}
| 1,008 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/AwsCrtHttpClientSpiVerificationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.binaryEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static java.util.Collections.emptyMap;
import static org.apache.commons.codec.digest.DigestUtils.sha256Hex;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.http.HttpTestUtils.createProvider;
import static software.amazon.awssdk.http.crt.CrtHttpClientTestUtils.createRequest;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.crt.http.HttpException;
import software.amazon.awssdk.http.RecordingResponseHandler;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.utils.Logger;
public class AwsCrtHttpClientSpiVerificationTest {
private static final Logger log = Logger.loggerFor(AwsCrtHttpClientSpiVerificationTest.class);
private static final int TEST_BODY_LEN = 1024;
@Rule
public WireMockRule mockServer = new WireMockRule(wireMockConfig()
.dynamicPort()
.dynamicHttpsPort());
private static SdkAsyncHttpClient client;
@BeforeClass
public static void setup() throws Exception {
client = AwsCrtAsyncHttpClient.builder()
.connectionHealthConfiguration(b -> b.minimumThroughputInBps(4068L)
.minimumThroughputTimeout(Duration.ofSeconds(3)))
.build();
}
@AfterClass
public static void tearDown() {
client.close();
CrtResource.waitForNoResources();
}
private byte[] generateRandomBody(int size) {
byte[] randomData = new byte[size];
new Random().nextBytes(randomData);
return randomData;
}
@Test
public void signalsErrorViaOnErrorAndFuture() throws Exception {
stubFor(any(urlEqualTo("/")).willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
CompletableFuture<Boolean> errorSignaled = new CompletableFuture<>();
SdkAsyncHttpResponseHandler handler = new TestResponseHandler() {
@Override
public void onError(Throwable error) {
errorSignaled.complete(true);
}
};
SdkHttpRequest request = CrtHttpClientTestUtils.createRequest(URI.create("http://localhost:" + mockServer.port()));
CompletableFuture<Void> executeFuture = client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new EmptyPublisher())
.build());
assertThat(errorSignaled.get(1, TimeUnit.SECONDS)).isTrue();
assertThatThrownBy(executeFuture::join).hasCauseInstanceOf(IOException.class).hasRootCauseInstanceOf(HttpException.class);
}
@Test
public void requestFailed_connectionTimeout_shouldWrapException() {
try (SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.builder().connectionTimeout(Duration.ofNanos(1)).build()) {
URI uri = URI.create("http://localhost:" + mockServer.port());
stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build());
assertThatThrownBy(() -> recorder.completeFuture().get(5, TimeUnit.SECONDS)).hasCauseInstanceOf(IOException.class)
.hasRootCauseInstanceOf(HttpException.class);
}
}
@Test
public void requestFailed_notRetryable_shouldNotWrapException() {
try (SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.builder().build()) {
URI uri = URI.create("http://localhost:" + mockServer.port());
// make it invalid by doing a non-zero content length with no request body...
Map<String, List<String>> headers = new HashMap<>();
headers.put("host", Collections.singletonList(uri.getHost()));
List<String> contentLengthValues = new LinkedList<>();
contentLengthValues.add("1");
headers.put("content-length", contentLengthValues);
SdkHttpRequest request = createRequest(uri).toBuilder().headers(headers).build();
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(new EmptyPublisher()).responseHandler(recorder).build());
// invalid request should have returned an HttpException and not an IOException.
assertThatThrownBy(() -> recorder.completeFuture().get(5, TimeUnit.SECONDS))
.hasCauseInstanceOf(HttpException.class).hasMessageContaining("does not match the previously declared length");
}
}
@Test
public void callsOnStreamForEmptyResponseContent() throws Exception {
stubFor(any(urlEqualTo("/")).willReturn(aResponse().withStatus(204).withHeader("foo", "bar")));
CompletableFuture<Boolean> streamReceived = new CompletableFuture<>();
AtomicReference<SdkHttpResponse> response = new AtomicReference<>(null);
SdkAsyncHttpResponseHandler handler = new TestResponseHandler() {
@Override
public void onHeaders(SdkHttpResponse headers) {
response.compareAndSet(null, headers);
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
super.onStream(stream);
streamReceived.complete(true);
}
};
SdkHttpRequest request = CrtHttpClientTestUtils.createRequest(URI.create("http://localhost:" + mockServer.port()));
CompletableFuture<Void> future = client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new EmptyPublisher())
.build());
future.get(60, TimeUnit.SECONDS);
assertThat(streamReceived.get(1, TimeUnit.SECONDS)).isTrue();
assertThat(response.get() != null).isTrue();
assertThat(response.get().statusCode() == 204).isTrue();
assertThat(response.get().headers().get("foo").isEmpty()).isFalse();
}
@Test
public void testGetRequest() throws Exception {
String path = "/testGetRequest";
byte[] body = generateRandomBody(TEST_BODY_LEN);
String expectedBodyHash = sha256Hex(body).toUpperCase();
stubFor(any(urlEqualTo(path)).willReturn(aResponse().withStatus(200)
.withHeader("Content-Length", Integer.toString(TEST_BODY_LEN))
.withHeader("foo", "bar")
.withBody(body)));
CompletableFuture<Boolean> streamReceived = new CompletableFuture<>();
AtomicReference<SdkHttpResponse> response = new AtomicReference<>(null);
Sha256BodySubscriber bodySha256Subscriber = new Sha256BodySubscriber();
AtomicReference<Throwable> error = new AtomicReference<>(null);
SdkAsyncHttpResponseHandler handler = new SdkAsyncHttpResponseHandler() {
@Override
public void onHeaders(SdkHttpResponse headers) {
response.compareAndSet(null, headers);
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
stream.subscribe(bodySha256Subscriber);
streamReceived.complete(true);
}
@Override
public void onError(Throwable t) {
error.compareAndSet(null, t);
}
};
URI uri = URI.create("http://localhost:" + mockServer.port());
SdkHttpRequest request = CrtHttpClientTestUtils.createRequest(uri, path, null, SdkHttpMethod.GET, emptyMap());
CompletableFuture future = client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new EmptyPublisher())
.build());
future.get(60, TimeUnit.SECONDS);
assertThat(error.get()).isNull();
assertThat(streamReceived.get(1, TimeUnit.SECONDS)).isTrue();
assertThat(bodySha256Subscriber.getFuture().get(60, TimeUnit.SECONDS)).isEqualTo(expectedBodyHash);
assertThat(response.get().statusCode()).isEqualTo(200);
assertThat(response.get().headers().get("foo").isEmpty()).isFalse();
}
private void makePutRequest(String path, byte[] reqBody, int expectedStatus) throws Exception {
CompletableFuture<Boolean> streamReceived = new CompletableFuture<>();
AtomicReference<SdkHttpResponse> response = new AtomicReference<>(null);
AtomicReference<Throwable> error = new AtomicReference<>(null);
Subscriber<ByteBuffer> subscriber = CrtHttpClientTestUtils.createDummySubscriber();
SdkAsyncHttpResponseHandler handler = CrtHttpClientTestUtils.createTestResponseHandler(response,
streamReceived, error, subscriber);
URI uri = URI.create("http://localhost:" + mockServer.port());
SdkHttpRequest request = CrtHttpClientTestUtils.createRequest(uri, path, reqBody, SdkHttpMethod.PUT, emptyMap());
CompletableFuture future = client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new SdkTestHttpContentPublisher(reqBody))
.build());
future.get(60, TimeUnit.SECONDS);
assertThat(error.get()).isNull();
assertThat(streamReceived.get(60, TimeUnit.SECONDS)).isTrue();
assertThat(response.get().statusCode()).isEqualTo(expectedStatus);
}
@Test
public void testPutRequest() throws Exception {
String pathExpect200 = "/testPutRequest/return_200_on_exact_match";
byte[] expectedBody = generateRandomBody(TEST_BODY_LEN);
stubFor(any(urlEqualTo(pathExpect200)).withRequestBody(binaryEqualTo(expectedBody)).willReturn(aResponse().withStatus(200)));
makePutRequest(pathExpect200, expectedBody, 200);
String pathExpect404 = "/testPutRequest/return_404_always";
byte[] randomBody = generateRandomBody(TEST_BODY_LEN);
stubFor(any(urlEqualTo(pathExpect404)).willReturn(aResponse().withStatus(404)));
makePutRequest(pathExpect404, randomBody, 404);
}
private static class TestResponseHandler implements SdkAsyncHttpResponseHandler {
@Override
public void onHeaders(SdkHttpResponse headers) {
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
stream.subscribe(new DrainingSubscriber<>());
}
@Override
public void onError(Throwable error) {
}
}
private static class DrainingSubscriber<T> implements Subscriber<T> {
private Subscription subscription;
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
this.subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(T t) {
this.subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
}
}
| 1,009 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/Sha256BodySubscriber.java | package software.amazon.awssdk.http.crt;
import static org.apache.commons.codec.binary.Hex.encodeHexString;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CompletableFuture;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
public class Sha256BodySubscriber implements Subscriber<ByteBuffer> {
private MessageDigest digest;
private CompletableFuture<String> future;
public Sha256BodySubscriber() throws NoSuchAlgorithmException {
digest = MessageDigest.getInstance("SHA-256");
future = new CompletableFuture<>();
}
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(ByteBuffer byteBuffer) {
digest.update(byteBuffer);
}
@Override
public void onError(Throwable t) {
future.completeExceptionally(t);
}
@Override
public void onComplete() {
future.complete(encodeHexString(digest.digest()).toUpperCase());
}
public CompletableFuture<String> getFuture() {
return future;
}
}
| 1,010 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/internal/CrtRequestExecutorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.http.HttpTestUtils.createProvider;
import static software.amazon.awssdk.http.crt.CrtHttpClientTestUtils.createRequest;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.crt.CrtRuntimeException;
import software.amazon.awssdk.crt.http.HttpClientConnection;
import software.amazon.awssdk.crt.http.HttpClientConnectionManager;
import software.amazon.awssdk.crt.http.HttpException;
import software.amazon.awssdk.crt.http.HttpRequest;
import software.amazon.awssdk.http.SdkCancellationException;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.crt.internal.response.CrtResponseAdapter;
import software.amazon.awssdk.utils.CompletableFutureUtils;
@RunWith(MockitoJUnitRunner.class)
public class CrtRequestExecutorTest {
private CrtRequestExecutor requestExecutor;
@Mock
private HttpClientConnectionManager connectionManager;
@Mock
private SdkAsyncHttpResponseHandler responseHandler;
@Mock
private HttpClientConnection httpClientConnection;
@Before
public void setup() {
requestExecutor = new CrtRequestExecutor();
}
@After
public void teardown() {
Mockito.reset(connectionManager, responseHandler, httpClientConnection);
}
@Test
public void acquireConnectionThrowException_shouldInvokeOnError() {
RuntimeException exception = new RuntimeException("error");
CrtRequestContext context = CrtRequestContext.builder()
.crtConnPool(connectionManager)
.request(AsyncExecuteRequest.builder()
.responseHandler(responseHandler)
.build())
.build();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.completeExceptionally(exception);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).hasMessageContaining("An exception occurred when acquiring a connection");
assertThat(actualException).hasCause(exception);
assertThat(executeFuture).hasFailedWithThrowableThat().hasCause(exception).isInstanceOf(IOException.class);
}
@Test
public void makeRequestThrowException_shouldInvokeOnError() {
CrtRuntimeException exception = new CrtRuntimeException("");
CrtRequestContext context = crtRequestContext();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.complete(httpClientConnection);
Mockito.when(httpClientConnection.makeRequest(Mockito.any(HttpRequest.class), Mockito.any(CrtResponseAdapter.class)))
.thenThrow(exception);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).hasMessageContaining("An exception occurred when making the request");
assertThat(actualException).hasCause(exception);
assertThat(executeFuture).hasFailedWithThrowableThat().hasCause(exception).isInstanceOf(IOException.class);
}
@Test
public void makeRequest_success() {
CrtRequestContext context = crtRequestContext();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.complete(httpClientConnection);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
Mockito.verifyNoMoreInteractions(responseHandler);
}
@Test
public void cancelRequest_shouldInvokeOnError() {
CrtRequestContext context = CrtRequestContext.builder()
.crtConnPool(connectionManager)
.request(AsyncExecuteRequest.builder()
.responseHandler(responseHandler)
.build())
.build();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
executeFuture.cancel(true);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).hasMessageContaining("The request was cancelled");
assertThat(actualException).isInstanceOf(SdkCancellationException.class);
}
@Test
public void execute_AcquireConnectionFailure_shouldAlwaysWrapIOException() {
CrtRequestContext context = crtRequestContext();
RuntimeException exception = new RuntimeException("some failure");
CompletableFuture<HttpClientConnection> completableFuture = CompletableFutureUtils.failedFuture(exception);
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
assertThatThrownBy(executeFuture::join).hasCauseInstanceOf(IOException.class).hasRootCause(exception);
}
@Test
public void executeRequest_failedOfIllegalStateException_shouldWrapIOException() {
IllegalStateException exception = new IllegalStateException("connection closed");
CrtRequestContext context = crtRequestContext();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.complete(httpClientConnection);
Mockito.when(httpClientConnection.makeRequest(Mockito.any(HttpRequest.class), Mockito.any(CrtResponseAdapter.class)))
.thenThrow(exception);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).hasMessageContaining("An exception occurred when making the request").hasCause(exception);
assertThatThrownBy(executeFuture::join).hasCauseInstanceOf(IOException.class).hasRootCause(exception);
}
@Test
public void executeRequest_failedOfRetryableHttpException_shouldWrapIOException() {
HttpException exception = new HttpException(0x080a); // AWS_ERROR_HTTP_CONNECTION_CLOSED
CrtRequestContext context = crtRequestContext();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.complete(httpClientConnection);
Mockito.when(httpClientConnection.makeRequest(Mockito.any(HttpRequest.class), Mockito.any(CrtResponseAdapter.class)))
.thenThrow(exception);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).hasCause(exception);
assertThatThrownBy(executeFuture::join).hasCauseInstanceOf(IOException.class).hasRootCause(exception);
}
@Test
public void executeRequest_failedOfNonRetryableHttpException_shouldNotWrapIOException() {
HttpException exception = new HttpException(0x0801); // AWS_ERROR_HTTP_HEADER_NOT_FOUND
CrtRequestContext context = crtRequestContext();
CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>();
Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture);
completableFuture.complete(httpClientConnection);
Mockito.when(httpClientConnection.makeRequest(Mockito.any(HttpRequest.class), Mockito.any(CrtResponseAdapter.class)))
.thenThrow(exception);
CompletableFuture<Void> executeFuture = requestExecutor.execute(context);
ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class);
Mockito.verify(responseHandler).onError(argumentCaptor.capture());
Exception actualException = argumentCaptor.getValue();
assertThat(actualException).isEqualTo(exception);
assertThatThrownBy(executeFuture::join).hasCause(exception);
}
private CrtRequestContext crtRequestContext() {
SdkHttpFullRequest request = createRequest(URI.create("http://localhost"));
return CrtRequestContext.builder()
.readBufferSize(2000)
.crtConnPool(connectionManager)
.request(AsyncExecuteRequest.builder()
.request(request)
.requestContentPublisher(createProvider(""))
.responseHandler(responseHandler)
.build())
.build();
}
}
| 1,011 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/internal/AwsCrtConfigurationUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt.internal;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static software.amazon.awssdk.crt.io.TlsCipherPreference.TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05;
import static software.amazon.awssdk.crt.io.TlsCipherPreference.TLS_CIPHER_SYSTEM_DEFAULT;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.crt.io.TlsCipherPreference;
class AwsCrtConfigurationUtilsTest {
@ParameterizedTest
@MethodSource("cipherPreferences")
void resolveCipherPreference_pqNotSupported_shouldFallbackToSystemDefault(Boolean preferPqTls,
TlsCipherPreference tlsCipherPreference) {
Assumptions.assumeFalse(TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05.isSupported());
assertThat(AwsCrtConfigurationUtils.resolveCipherPreference(preferPqTls)).isEqualTo(tlsCipherPreference);
}
@Test
void resolveCipherPreference_pqSupported_shouldHonor() {
Assumptions.assumeTrue(TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05.isSupported());
assertThat(AwsCrtConfigurationUtils.resolveCipherPreference(true)).isEqualTo(TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05);
}
private static Stream<Arguments> cipherPreferences() {
return Stream.of(
Arguments.of(null, TLS_CIPHER_SYSTEM_DEFAULT),
Arguments.of(false, TLS_CIPHER_SYSTEM_DEFAULT),
Arguments.of(true, TLS_CIPHER_SYSTEM_DEFAULT)
);
}
}
| 1,012 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/ConnectionHealthConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.crtcore.CrtConnectionHealthConfiguration;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Configuration that defines health checks for all connections established by
* the {@link ConnectionHealthConfiguration}.
*
*/
@SdkPublicApi
public final class ConnectionHealthConfiguration extends CrtConnectionHealthConfiguration
implements ToCopyableBuilder<ConnectionHealthConfiguration.Builder, ConnectionHealthConfiguration> {
private ConnectionHealthConfiguration(DefaultBuilder builder) {
super(builder);
}
public static Builder builder() {
return new DefaultBuilder();
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
/**
* A builder for {@link ConnectionHealthConfiguration}.
*
* <p>All implementations of this interface are mutable and not thread safe.</p>
*/
public interface Builder extends CrtConnectionHealthConfiguration.Builder,
CopyableBuilder<Builder, ConnectionHealthConfiguration> {
@Override
Builder minimumThroughputInBps(Long minimumThroughputInBps);
@Override
Builder minimumThroughputTimeout(Duration minimumThroughputTimeout);
@Override
ConnectionHealthConfiguration build();
}
/**
* An SDK-internal implementation of {@link Builder}.
*/
private static final class DefaultBuilder extends
CrtConnectionHealthConfiguration.DefaultBuilder<DefaultBuilder> implements Builder {
private DefaultBuilder() {
}
private DefaultBuilder(ConnectionHealthConfiguration configuration) {
super(configuration);
}
@Override
public ConnectionHealthConfiguration build() {
return new ConnectionHealthConfiguration(this);
}
}
}
| 1,013 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/AwsCrtSdkHttpService.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpService;
/**
* Service binding for the AWS common runtime HTTP client implementation. Allows SDK to pick this up automatically from the
* classpath.
*
*/
@SdkPublicApi
public class AwsCrtSdkHttpService implements SdkAsyncHttpService {
@Override
public SdkAsyncHttpClient.Builder createAsyncHttpClientFactory() {
return AwsCrtAsyncHttpClient.builder();
}
}
| 1,014 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/ProxyConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.crtcore.CrtProxyConfiguration;
import software.amazon.awssdk.utils.ProxySystemSetting;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Proxy configuration for {@link AwsCrtAsyncHttpClient}. This class is used to configure an HTTPS or HTTP proxy to be used by the
* {@link AwsCrtAsyncHttpClient}.
*
* @see AwsCrtAsyncHttpClient.Builder#proxyConfiguration(ProxyConfiguration)
*/
@SdkPublicApi
public final class ProxyConfiguration extends CrtProxyConfiguration
implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> {
private ProxyConfiguration(DefaultBuilder builder) {
super(builder);
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Builder for {@link ProxyConfiguration}.
*/
public interface Builder extends CrtProxyConfiguration.Builder, CopyableBuilder<Builder, ProxyConfiguration> {
/**
* Set the hostname of the proxy.
*
* @param host The proxy host.
* @return This object for method chaining.
*/
@Override
Builder host(String host);
/**
* Set the port that the proxy expects connections on.
*
* @param port The proxy port.
* @return This object for method chaining.
*/
@Override
Builder port(int port);
/**
* The HTTP scheme to use for connecting to the proxy. Valid values are {@code http} and {@code https}.
* <p>
* The client defaults to {@code http} if none is given.
*
* @param scheme The proxy scheme.
* @return This object for method chaining.
*/
@Override
Builder scheme(String scheme);
/**
* The username to use for basic proxy authentication
* <p>
* If not set, the client will not use basic authentication
*
* @param username The basic authentication username.
* @return This object for method chaining.
*/
@Override
Builder username(String username);
/**
* The password to use for basic proxy authentication
* <p>
* If not set, the client will not use basic authentication
*
* @param password The basic authentication password.
* @return This object for method chaining.
*/
@Override
Builder password(String password);
/**
* The option whether to use system property values from {@link ProxySystemSetting} if any of the config options are
* missing. The value is set to "true" by default which means SDK will automatically use system property values if
* options
* are not provided during building the {@link ProxyConfiguration} object. To disable this behaviour, set this
* value to
* false.
*
* @param useSystemPropertyValues The option whether to use system property values
* @return This object for method chaining.
*/
@Override
Builder useSystemPropertyValues(Boolean useSystemPropertyValues);
@Override
Builder useEnvironmentVariableValues(Boolean useEnvironmentVariableValues);
@Override
ProxyConfiguration build();
}
private static final class DefaultBuilder extends CrtProxyConfiguration.DefaultBuilder<DefaultBuilder> implements Builder {
private DefaultBuilder(ProxyConfiguration proxyConfiguration) {
super(proxyConfiguration);
}
private DefaultBuilder() {
}
@Override
public ProxyConfiguration build() {
return new ProxyConfiguration(this);
}
}
} | 1,015 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/TcpKeepAliveConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Validate;
/**
* Configuration that defines keep-alive options for all connections established by
* the {@link TcpKeepAliveConfiguration}.
*/
@SdkPublicApi
public final class TcpKeepAliveConfiguration {
private final Duration keepAliveInterval;
private final Duration keepAliveTimeout;
private TcpKeepAliveConfiguration(DefaultTcpKeepAliveConfigurationBuilder builder) {
this.keepAliveInterval = Validate.isPositive(builder.keepAliveInterval,
"keepAliveInterval");
this.keepAliveTimeout = Validate.isPositive(builder.keepAliveTimeout,
"keepAliveTimeout");
}
/**
* @return number of seconds between TCP keepalive packets being sent to the peer
*/
public Duration keepAliveInterval() {
return keepAliveInterval;
}
/**
* @return number of seconds to wait for a keepalive response before considering the connection timed out
*/
public Duration keepAliveTimeout() {
return keepAliveTimeout;
}
public static Builder builder() {
return new DefaultTcpKeepAliveConfigurationBuilder();
}
/**
* A builder for {@link TcpKeepAliveConfiguration}.
*
* <p>All implementations of this interface are mutable and not thread safe.</p>
*/
public interface Builder {
/**
* Sets the Duration between TCP keepalive packets being sent to the peer
* @param keepAliveInterval Duration between TCP keepalive packets being sent to the peer
* @return Builder
*/
Builder keepAliveInterval(Duration keepAliveInterval);
/**
* Sets the Duration to wait for a keepalive response before considering the connection timed out
* @param keepAliveTimeout Duration to wait for a keepalive response before considering the connection timed out
* @return Builder
*/
Builder keepAliveTimeout(Duration keepAliveTimeout);
TcpKeepAliveConfiguration build();
}
/**
* An SDK-internal implementation of {@link Builder}.
*/
private static final class DefaultTcpKeepAliveConfigurationBuilder implements Builder {
private Duration keepAliveInterval;
private Duration keepAliveTimeout;
private DefaultTcpKeepAliveConfigurationBuilder() {
}
/**
* Sets the Duration between TCP keepalive packets being sent to the peer
* @param keepAliveInterval Duration between TCP keepalive packets being sent to the peer
* @return Builder
*/
@Override
public Builder keepAliveInterval(Duration keepAliveInterval) {
this.keepAliveInterval = keepAliveInterval;
return this;
}
/**
* Sets the Duration to wait for a keepalive response before considering the connection timed out
* @param keepAliveTimeout Duration to wait for a keepalive response before considering the connection timed out
* @return Builder
*/
@Override
public Builder keepAliveTimeout(Duration keepAliveTimeout) {
this.keepAliveTimeout = keepAliveTimeout;
return this;
}
@Override
public TcpKeepAliveConfiguration build() {
return new TcpKeepAliveConfiguration(this);
}
}
}
| 1,016 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/AwsCrtAsyncHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt;
import static software.amazon.awssdk.crtcore.CrtConfigurationUtils.resolveHttpMonitoringOptions;
import static software.amazon.awssdk.crtcore.CrtConfigurationUtils.resolveProxy;
import static software.amazon.awssdk.http.HttpMetric.HTTP_CLIENT_NAME;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.PROTOCOL;
import static software.amazon.awssdk.http.crt.internal.AwsCrtConfigurationUtils.buildSocketOptions;
import static software.amazon.awssdk.http.crt.internal.AwsCrtConfigurationUtils.resolveCipherPreference;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.net.URI;
import java.time.Duration;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.crt.http.HttpClientConnectionManager;
import software.amazon.awssdk.crt.http.HttpClientConnectionManagerOptions;
import software.amazon.awssdk.crt.http.HttpMonitoringOptions;
import software.amazon.awssdk.crt.http.HttpProxyOptions;
import software.amazon.awssdk.crt.io.ClientBootstrap;
import software.amazon.awssdk.crt.io.SocketOptions;
import software.amazon.awssdk.crt.io.TlsContext;
import software.amazon.awssdk.crt.io.TlsContextOptions;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.crt.internal.CrtRequestContext;
import software.amazon.awssdk.http.crt.internal.CrtRequestExecutor;
import software.amazon.awssdk.metrics.NoOpMetricCollector;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link SdkAsyncHttpClient} that uses the AWS Common Runtime (CRT) Http Client to communicate with
* Http Web Services. This client is asynchronous and uses non-blocking IO.
*
* <p>This can be created via {@link #builder()}</p>
* {@snippet :
SdkAsyncHttpClient client = AwsCrtAsyncHttpClient.builder()
.maxConcurrency(100)
.connectionTimeout(Duration.ofSeconds(1))
.connectionMaxIdleTime(Duration.ofSeconds(5))
.build();
* }
*
*/
@SdkPublicApi
public final class AwsCrtAsyncHttpClient implements SdkAsyncHttpClient {
private static final Logger log = Logger.loggerFor(AwsCrtAsyncHttpClient.class);
private static final String AWS_COMMON_RUNTIME = "AwsCommonRuntime";
private static final long DEFAULT_STREAM_WINDOW_SIZE = 16L * 1024L * 1024L; // 16 MB
private final Map<URI, HttpClientConnectionManager> connectionPools = new ConcurrentHashMap<>();
private final LinkedList<CrtResource> ownedSubResources = new LinkedList<>();
private final ClientBootstrap bootstrap;
private final SocketOptions socketOptions;
private final TlsContext tlsContext;
private final HttpProxyOptions proxyOptions;
private final HttpMonitoringOptions monitoringOptions;
private final long maxConnectionIdleInMilliseconds;
private final long readBufferSize;
private final int maxConnectionsPerEndpoint;
private boolean isClosed = false;
private AwsCrtAsyncHttpClient(DefaultBuilder builder, AttributeMap config) {
if (config.get(PROTOCOL) == Protocol.HTTP2) {
throw new UnsupportedOperationException("HTTP/2 is not supported in AwsCrtAsyncHttpClient yet. Use "
+ "NettyNioAsyncHttpClient instead.");
}
try (ClientBootstrap clientBootstrap = new ClientBootstrap(null, null);
SocketOptions clientSocketOptions = buildSocketOptions(builder.tcpKeepAliveConfiguration,
config.get(SdkHttpConfigurationOption.CONNECTION_TIMEOUT));
TlsContextOptions clientTlsContextOptions =
TlsContextOptions.createDefaultClient()
.withCipherPreference(resolveCipherPreference(builder.postQuantumTlsEnabled))
.withVerifyPeer(!config.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES));
TlsContext clientTlsContext = new TlsContext(clientTlsContextOptions)) {
this.bootstrap = registerOwnedResource(clientBootstrap);
this.socketOptions = registerOwnedResource(clientSocketOptions);
this.tlsContext = registerOwnedResource(clientTlsContext);
this.readBufferSize = builder.readBufferSize == null ? DEFAULT_STREAM_WINDOW_SIZE : builder.readBufferSize;
this.maxConnectionsPerEndpoint = config.get(SdkHttpConfigurationOption.MAX_CONNECTIONS);
this.monitoringOptions = resolveHttpMonitoringOptions(builder.connectionHealthConfiguration).orElse(null);
this.maxConnectionIdleInMilliseconds = config.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT).toMillis();
this.proxyOptions = resolveProxy(builder.proxyConfiguration, tlsContext).orElse(null);
}
}
/**
* Marks a Native CrtResource as owned by the current Java Object.
*
* @param subresource The Resource to own.
* @param <T> The CrtResource Type
* @return The CrtResource passed in
*/
private <T extends CrtResource> T registerOwnedResource(T subresource) {
if (subresource != null) {
subresource.addRef();
ownedSubResources.push(subresource);
}
return subresource;
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Create a {@link AwsCrtAsyncHttpClient} client with the default configuration
*
* @return an {@link SdkAsyncHttpClient}
*/
public static SdkAsyncHttpClient create() {
return new DefaultBuilder().build();
}
@Override
public String clientName() {
return AWS_COMMON_RUNTIME;
}
private HttpClientConnectionManager createConnectionPool(URI uri) {
log.debug(() -> "Creating ConnectionPool for: URI:" + uri + ", MaxConns: " + maxConnectionsPerEndpoint);
HttpClientConnectionManagerOptions options = new HttpClientConnectionManagerOptions()
.withClientBootstrap(bootstrap)
.withSocketOptions(socketOptions)
.withTlsContext(tlsContext)
.withUri(uri)
.withWindowSize(readBufferSize)
.withMaxConnections(maxConnectionsPerEndpoint)
.withManualWindowManagement(true)
.withProxyOptions(proxyOptions)
.withMonitoringOptions(monitoringOptions)
.withMaxConnectionIdleInMilliseconds(maxConnectionIdleInMilliseconds);
return HttpClientConnectionManager.create(options);
}
/*
* Callers of this function MUST account for the addRef() on the pool before returning.
* Every execution path consuming the return value must guarantee an associated close().
* Currently this function is only used by execute(), which guarantees a matching close
* via the try-with-resources block.
*
* This guarantees that a returned pool will not get closed (by closing the http client) during
* the time it takes to submit a request to the pool. Acquisition requests submitted to the pool will
* be properly failed if the http client is closed before the acquisition completes.
*
* This additional complexity means we only have to keep a lock for the scope of this function, as opposed to
* the scope of calling execute(). This function will almost always just be a hash lookup and the return of an
* existing pool. If we add all of execute() to the scope, we include, at minimum a JNI call to the native
* pool implementation.
*/
private HttpClientConnectionManager getOrCreateConnectionPool(URI uri) {
synchronized (this) {
if (isClosed) {
throw new IllegalStateException("Client is closed. No more requests can be made with this client.");
}
HttpClientConnectionManager connPool = connectionPools.computeIfAbsent(uri, this::createConnectionPool);
connPool.addRef();
return connPool;
}
}
@Override
public CompletableFuture<Void> execute(AsyncExecuteRequest asyncRequest) {
paramNotNull(asyncRequest, "asyncRequest");
paramNotNull(asyncRequest.request(), "SdkHttpRequest");
paramNotNull(asyncRequest.requestContentPublisher(), "RequestContentPublisher");
paramNotNull(asyncRequest.responseHandler(), "ResponseHandler");
asyncRequest.metricCollector()
.filter(metricCollector -> !(metricCollector instanceof NoOpMetricCollector))
.ifPresent(metricCollector -> metricCollector.reportMetric(HTTP_CLIENT_NAME, clientName()));
/*
* See the note on getOrCreateConnectionPool()
*
* In particular, this returns a ref-counted object and calling getOrCreateConnectionPool
* increments the ref count by one. We add a try-with-resources to release our ref
* once we have successfully submitted a request. In this way, we avoid a race condition
* when close/shutdown is called from another thread while this function is executing (ie.
* we have a pool and no one can destroy it underneath us until we've finished submitting the
* request)
*/
try (HttpClientConnectionManager crtConnPool = getOrCreateConnectionPool(poolKey(asyncRequest))) {
CrtRequestContext context = CrtRequestContext.builder()
.crtConnPool(crtConnPool)
.readBufferSize(readBufferSize)
.request(asyncRequest)
.build();
return new CrtRequestExecutor().execute(context);
}
}
private URI poolKey(AsyncExecuteRequest asyncRequest) {
SdkHttpRequest sdkRequest = asyncRequest.request();
return invokeSafely(() -> new URI(sdkRequest.protocol(), null, sdkRequest.host(),
sdkRequest.port(), null, null, null));
}
@Override
public void close() {
synchronized (this) {
if (isClosed) {
return;
}
connectionPools.values().forEach(pool -> IoUtils.closeQuietly(pool, log.logger()));
ownedSubResources.forEach(r -> IoUtils.closeQuietly(r, log.logger()));
ownedSubResources.clear();
isClosed = true;
}
}
/**
* Builder that allows configuration of the AWS CRT HTTP implementation.
*/
public interface Builder extends SdkAsyncHttpClient.Builder<AwsCrtAsyncHttpClient.Builder> {
/**
* The Maximum number of allowed concurrent requests. For HTTP/1.1 this is the same as max connections.
* @param maxConcurrency maximum concurrency per endpoint
* @return The builder of the method chaining.
*/
Builder maxConcurrency(Integer maxConcurrency);
/**
* Configures the number of unread bytes that can be buffered in the
* client before we stop reading from the underlying TCP socket and wait for the Subscriber
* to read more data.
*
* @param readBufferSize The number of bytes that can be buffered.
* @return The builder of the method chaining.
*/
Builder readBufferSizeInBytes(Long readBufferSize);
/**
* Sets the http proxy configuration to use for this client.
* @param proxyConfiguration The http proxy configuration to use
* @return The builder of the method chaining.
*/
Builder proxyConfiguration(ProxyConfiguration proxyConfiguration);
/**
* Sets the http proxy configuration to use for this client.
*
* @param proxyConfigurationBuilderConsumer The consumer of the proxy configuration builder object.
* @return the builder for method chaining.
*/
Builder proxyConfiguration(Consumer<ProxyConfiguration.Builder> proxyConfigurationBuilderConsumer);
/**
* Configure the health checks for all connections established by this client.
*
* <p>
* You can set a throughput threshold for a connection to be considered healthy.
* If a connection falls below this threshold ({@link ConnectionHealthConfiguration#minimumThroughputInBps()
* }) for the configurable amount
* of time ({@link ConnectionHealthConfiguration#minimumThroughputTimeout()}),
* then the connection is considered unhealthy and will be shut down.
*
* <p>
* By default, monitoring options are disabled. You can enable {@code healthChecks} by providing this configuration
* and specifying the options for monitoring for the connection manager.
* @param healthChecksConfiguration The health checks config to use
* @return The builder of the method chaining.
*/
Builder connectionHealthConfiguration(ConnectionHealthConfiguration healthChecksConfiguration);
/**
* A convenience method that creates an instance of the {@link ConnectionHealthConfiguration} builder, avoiding the
* need to create one manually via {@link ConnectionHealthConfiguration#builder()}.
*
* @param healthChecksConfigurationBuilder The health checks config builder to use
* @return The builder of the method chaining.
* @see #connectionHealthConfiguration(ConnectionHealthConfiguration)
*/
Builder connectionHealthConfiguration(Consumer<ConnectionHealthConfiguration.Builder>
healthChecksConfigurationBuilder);
/**
* Configure the maximum amount of time that a connection should be allowed to remain open while idle.
* @param connectionMaxIdleTime the maximum amount of connection idle time
* @return The builder of the method chaining.
*/
Builder connectionMaxIdleTime(Duration connectionMaxIdleTime);
/**
* The amount of time to wait when initially establishing a connection before giving up and timing out.
* @param connectionTimeout timeout
* @return The builder of the method chaining.
*/
Builder connectionTimeout(Duration connectionTimeout);
/**
* Configure whether to enable {@code tcpKeepAlive} and relevant configuration for all connections established by this
* client.
*
* <p>
* By default, tcpKeepAlive is disabled. You can enable {@code tcpKeepAlive} by providing this configuration
* and specifying periodic TCP keepalive packet intervals and timeouts. This may be required for certain connections for
* longer durations than default socket timeouts.
*
* @param tcpKeepAliveConfiguration The TCP keep-alive configuration to use
* @return The builder of the method chaining.
*/
Builder tcpKeepAliveConfiguration(TcpKeepAliveConfiguration tcpKeepAliveConfiguration);
/**
* Configure whether to enable {@code tcpKeepAlive} and relevant configuration for all connections established by this
* client.
*
* <p>
* A convenience method that creates an instance of the {@link TcpKeepAliveConfiguration} builder, avoiding the
* need to create one manually via {@link TcpKeepAliveConfiguration#builder()}.
*
* @param tcpKeepAliveConfigurationBuilder The TCP keep-alive configuration builder to use
* @return The builder of the method chaining.
* @see #tcpKeepAliveConfiguration(TcpKeepAliveConfiguration)
*/
Builder tcpKeepAliveConfiguration(Consumer<TcpKeepAliveConfiguration.Builder>
tcpKeepAliveConfigurationBuilder);
/**
* Configure whether to enable a hybrid post-quantum key exchange option for the Transport Layer Security (TLS) network
* encryption protocol when communicating with services that support Post Quantum TLS. If Post Quantum cipher suites are
* not supported on the platform, the SDK will use the default TLS cipher suites.
*
* <p>
* See <a href="https://docs.aws.amazon.com/kms/latest/developerguide/pqtls.html">Using hybrid post-quantum TLS with AWS KMS</a>
*
* <p>
* It's disabled by default.
*
* @param postQuantumTlsEnabled whether to prefer Post Quantum TLS
* @return The builder of the method chaining.
*/
Builder postQuantumTlsEnabled(Boolean postQuantumTlsEnabled);
}
/**
* Factory that allows more advanced configuration of the AWS CRT HTTP implementation. Use {@link #builder()} to
* configure and construct an immutable instance of the factory.
*/
private static final class DefaultBuilder implements Builder {
private final AttributeMap.Builder standardOptions = AttributeMap.builder();
private Long readBufferSize;
private ProxyConfiguration proxyConfiguration;
private ConnectionHealthConfiguration connectionHealthConfiguration;
private TcpKeepAliveConfiguration tcpKeepAliveConfiguration;
private Boolean postQuantumTlsEnabled;
private DefaultBuilder() {
}
@Override
public SdkAsyncHttpClient build() {
return new AwsCrtAsyncHttpClient(this, standardOptions.build()
.merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS));
}
@Override
public SdkAsyncHttpClient buildWithDefaults(AttributeMap serviceDefaults) {
return new AwsCrtAsyncHttpClient(this, standardOptions.build()
.merge(serviceDefaults)
.merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS));
}
@Override
public Builder maxConcurrency(Integer maxConcurrency) {
Validate.isPositiveOrNull(maxConcurrency, "maxConcurrency");
standardOptions.put(SdkHttpConfigurationOption.MAX_CONNECTIONS, maxConcurrency);
return this;
}
@Override
public Builder readBufferSizeInBytes(Long readBufferSize) {
Validate.isPositiveOrNull(readBufferSize, "readBufferSize");
this.readBufferSize = readBufferSize;
return this;
}
@Override
public Builder proxyConfiguration(ProxyConfiguration proxyConfiguration) {
this.proxyConfiguration = proxyConfiguration;
return this;
}
@Override
public Builder connectionHealthConfiguration(ConnectionHealthConfiguration monitoringOptions) {
this.connectionHealthConfiguration = monitoringOptions;
return this;
}
@Override
public Builder connectionHealthConfiguration(Consumer<ConnectionHealthConfiguration.Builder>
configurationBuilder) {
ConnectionHealthConfiguration.Builder builder = ConnectionHealthConfiguration.builder();
configurationBuilder.accept(builder);
return connectionHealthConfiguration(builder.build());
}
@Override
public Builder connectionMaxIdleTime(Duration connectionMaxIdleTime) {
Validate.isPositive(connectionMaxIdleTime, "connectionMaxIdleTime");
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT, connectionMaxIdleTime);
return this;
}
@Override
public Builder connectionTimeout(Duration connectionTimeout) {
Validate.isPositive(connectionTimeout, "connectionTimeout");
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, connectionTimeout);
return this;
}
@Override
public Builder tcpKeepAliveConfiguration(TcpKeepAliveConfiguration tcpKeepAliveConfiguration) {
this.tcpKeepAliveConfiguration = tcpKeepAliveConfiguration;
return this;
}
@Override
public Builder tcpKeepAliveConfiguration(Consumer<TcpKeepAliveConfiguration.Builder>
tcpKeepAliveConfigurationBuilder) {
TcpKeepAliveConfiguration.Builder builder = TcpKeepAliveConfiguration.builder();
tcpKeepAliveConfigurationBuilder.accept(builder);
return tcpKeepAliveConfiguration(builder.build());
}
@Override
public Builder postQuantumTlsEnabled(Boolean postQuantumTlsEnabled) {
this.postQuantumTlsEnabled = postQuantumTlsEnabled;
return this;
}
@Override
public Builder proxyConfiguration(Consumer<ProxyConfiguration.Builder> proxyConfigurationBuilderConsumer) {
ProxyConfiguration.Builder builder = ProxyConfiguration.builder();
proxyConfigurationBuilderConsumer.accept(builder);
return proxyConfiguration(builder.build());
}
}
}
| 1,017 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/CrtRequestExecutor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt.internal;
import static software.amazon.awssdk.http.HttpMetric.AVAILABLE_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.CONCURRENCY_ACQUIRE_DURATION;
import static software.amazon.awssdk.http.HttpMetric.LEASED_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.MAX_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.PENDING_CONCURRENCY_ACQUIRES;
import static software.amazon.awssdk.utils.NumericUtils.saturatedCast;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.CrtRuntimeException;
import software.amazon.awssdk.crt.http.HttpClientConnection;
import software.amazon.awssdk.crt.http.HttpClientConnectionManager;
import software.amazon.awssdk.crt.http.HttpException;
import software.amazon.awssdk.crt.http.HttpManagerMetrics;
import software.amazon.awssdk.crt.http.HttpRequest;
import software.amazon.awssdk.crt.http.HttpStreamResponseHandler;
import software.amazon.awssdk.http.SdkCancellationException;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.crt.internal.request.CrtRequestAdapter;
import software.amazon.awssdk.http.crt.internal.response.CrtResponseAdapter;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.NoOpMetricCollector;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public final class CrtRequestExecutor {
private static final Logger log = Logger.loggerFor(CrtRequestExecutor.class);
public CompletableFuture<Void> execute(CrtRequestContext executionContext) {
// go ahead and get a reference to the metricCollector since multiple futures will
// need it regardless.
MetricCollector metricCollector = executionContext.metricCollector();
boolean shouldPublishMetrics = metricCollector != null && !(metricCollector instanceof NoOpMetricCollector);
long acquireStartTime = 0;
if (shouldPublishMetrics) {
// go ahead and get acquireStartTime for the concurrency timer as early as possible,
// so it's as accurate as possible, but only do it in a branch since clock_gettime()
// results in a full sys call barrier (multiple mutexes and a hw interrupt).
acquireStartTime = System.nanoTime();
}
CompletableFuture<Void> requestFuture = createExecutionFuture(executionContext.sdkRequest());
// When a Connection is ready from the Connection Pool, schedule the Request on the connection
CompletableFuture<HttpClientConnection> httpClientConnectionCompletableFuture =
executionContext.crtConnPool().acquireConnection();
long finalAcquireStartTime = acquireStartTime;
httpClientConnectionCompletableFuture.whenComplete((crtConn, throwable) -> {
AsyncExecuteRequest asyncRequest = executionContext.sdkRequest();
if (shouldPublishMetrics) {
reportMetrics(executionContext, metricCollector, finalAcquireStartTime);
}
// If we didn't get a connection for some reason, fail the request
if (throwable != null) {
reportFailure(crtConn,
new IOException("An exception occurred when acquiring a connection", throwable),
requestFuture,
asyncRequest.responseHandler());
return;
}
executeRequest(executionContext, requestFuture, crtConn, asyncRequest);
});
return requestFuture;
}
private static void reportMetrics(CrtRequestContext executionContext, MetricCollector metricCollector,
long acquireStartTime) {
long acquireCompletionTime = System.nanoTime();
Duration acquireTimeTaken = Duration.ofNanos(acquireCompletionTime - acquireStartTime);
metricCollector.reportMetric(CONCURRENCY_ACQUIRE_DURATION, acquireTimeTaken);
HttpClientConnectionManager connManager = executionContext.crtConnPool();
HttpManagerMetrics managerMetrics = connManager.getManagerMetrics();
// currently this executor only handles HTTP 1.1. Until H2 is added, the max concurrency settings are 1:1 with TCP
// connections. When H2 is added, this code needs to be updated to handle stream multiplexing
metricCollector.reportMetric(MAX_CONCURRENCY, connManager.getMaxConnections());
metricCollector.reportMetric(AVAILABLE_CONCURRENCY, saturatedCast(managerMetrics.getAvailableConcurrency()));
metricCollector.reportMetric(LEASED_CONCURRENCY, saturatedCast(managerMetrics.getLeasedConcurrency()));
metricCollector.reportMetric(PENDING_CONCURRENCY_ACQUIRES, saturatedCast(managerMetrics.getPendingConcurrencyAcquires()));
}
private void executeRequest(CrtRequestContext executionContext,
CompletableFuture<Void> requestFuture,
HttpClientConnection crtConn,
AsyncExecuteRequest asyncRequest) {
HttpRequest crtRequest = CrtRequestAdapter.toCrtRequest(executionContext);
HttpStreamResponseHandler crtResponseHandler =
CrtResponseAdapter.toCrtResponseHandler(crtConn, requestFuture, asyncRequest.responseHandler());
// Submit the request on the connection
try {
crtConn.makeRequest(crtRequest, crtResponseHandler).activate();
} catch (HttpException e) {
Throwable toThrow = e;
if (HttpClientConnection.isErrorRetryable(e)) {
// IOExceptions get retried, and if the CRT says this error is retryable,
// it's semantically an IOException anyway.
toThrow = new IOException(e);
}
reportFailure(crtConn,
toThrow,
requestFuture,
asyncRequest.responseHandler());
} catch (IllegalStateException | CrtRuntimeException e) {
// CRT throws IllegalStateException if the connection is closed
reportFailure(crtConn, new IOException("An exception occurred when making the request", e),
requestFuture,
asyncRequest.responseHandler());
}
}
/**
* Create the execution future and set up the cancellation logic.
* @return The created execution future.
*/
private CompletableFuture<Void> createExecutionFuture(AsyncExecuteRequest request) {
CompletableFuture<Void> future = new CompletableFuture<>();
future.whenComplete((r, t) -> {
if (t == null) {
return;
}
// TODO: Aborting request once it's supported in CRT
if (future.isCancelled()) {
request.responseHandler().onError(new SdkCancellationException("The request was cancelled"));
}
});
return future;
}
/**
* Notify the provided response handler and future of the failure.
*/
private void reportFailure(HttpClientConnection crtConn,
Throwable cause,
CompletableFuture<Void> executeFuture,
SdkAsyncHttpResponseHandler responseHandler) {
if (crtConn != null) {
crtConn.close();
}
try {
responseHandler.onError(cause);
} catch (Exception e) {
log.error(() -> "SdkAsyncHttpResponseHandler " + responseHandler + " threw an exception in onError. It will be "
+ "ignored.", e);
}
executeFuture.completeExceptionally(cause);
}
}
| 1,018 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/CrtRequestContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.http.HttpClientConnectionManager;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.metrics.MetricCollector;
@SdkInternalApi
public final class CrtRequestContext {
private final AsyncExecuteRequest request;
private final long readBufferSize;
private final HttpClientConnectionManager crtConnPool;
private final MetricCollector metricCollector;
private CrtRequestContext(Builder builder) {
this.request = builder.request;
this.readBufferSize = builder.readBufferSize;
this.crtConnPool = builder.crtConnPool;
this.metricCollector = request.metricCollector().orElse(null);
}
public static Builder builder() {
return new Builder();
}
public AsyncExecuteRequest sdkRequest() {
return request;
}
public long readBufferSize() {
return readBufferSize;
}
public HttpClientConnectionManager crtConnPool() {
return crtConnPool;
}
public MetricCollector metricCollector() {
return metricCollector;
}
public static class Builder {
private AsyncExecuteRequest request;
private long readBufferSize;
private HttpClientConnectionManager crtConnPool;
private Builder() {
}
public Builder request(AsyncExecuteRequest request) {
this.request = request;
return this;
}
public Builder readBufferSize(long readBufferSize) {
this.readBufferSize = readBufferSize;
return this;
}
public Builder crtConnPool(HttpClientConnectionManager crtConnPool) {
this.crtConnPool = crtConnPool;
return this;
}
public CrtRequestContext build() {
return new CrtRequestContext(this);
}
}
}
| 1,019 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/AwsCrtConfigurationUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt.internal;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.io.SocketOptions;
import software.amazon.awssdk.crt.io.TlsCipherPreference;
import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient;
import software.amazon.awssdk.http.crt.TcpKeepAliveConfiguration;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.NumericUtils;
@SdkInternalApi
public final class AwsCrtConfigurationUtils {
private static final Logger log = Logger.loggerFor(AwsCrtAsyncHttpClient.class);
private AwsCrtConfigurationUtils() {
}
public static SocketOptions buildSocketOptions(TcpKeepAliveConfiguration tcpKeepAliveConfiguration,
Duration connectionTimeout) {
SocketOptions clientSocketOptions = new SocketOptions();
if (connectionTimeout != null) {
clientSocketOptions.connectTimeoutMs = NumericUtils.saturatedCast(connectionTimeout.toMillis());
}
if (tcpKeepAliveConfiguration != null) {
clientSocketOptions.keepAliveIntervalSecs =
NumericUtils.saturatedCast(tcpKeepAliveConfiguration.keepAliveInterval().getSeconds());
clientSocketOptions.keepAliveTimeoutSecs =
NumericUtils.saturatedCast(tcpKeepAliveConfiguration.keepAliveTimeout().getSeconds());
}
return clientSocketOptions;
}
public static TlsCipherPreference resolveCipherPreference(Boolean postQuantumTlsEnabled) {
TlsCipherPreference defaultTls = TlsCipherPreference.TLS_CIPHER_SYSTEM_DEFAULT;
if (postQuantumTlsEnabled == null || !postQuantumTlsEnabled) {
return defaultTls;
}
// TODO: change this to the new PQ TLS Policy that stays up to date when it's ready
TlsCipherPreference pqTls = TlsCipherPreference.TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05;
if (!pqTls.isSupported()) {
log.warn(() -> "Hybrid post-quantum cipher suites are not supported on this platform. The SDK will use the system "
+ "default cipher suites instead");
return defaultTls;
}
return pqTls;
}
}
| 1,020 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/response/CrtResponseAdapter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt.internal.response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.CRT;
import software.amazon.awssdk.crt.http.HttpClientConnection;
import software.amazon.awssdk.crt.http.HttpException;
import software.amazon.awssdk.crt.http.HttpHeader;
import software.amazon.awssdk.crt.http.HttpHeaderBlock;
import software.amazon.awssdk.crt.http.HttpStream;
import software.amazon.awssdk.crt.http.HttpStreamResponseHandler;
import software.amazon.awssdk.http.HttpStatusFamily;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.async.SimplePublisher;
/**
* Implements the CrtHttpStreamHandler API and converts CRT callbacks into calls to SDK AsyncExecuteRequest methods
*/
@SdkInternalApi
public final class CrtResponseAdapter implements HttpStreamResponseHandler {
private static final Logger log = Logger.loggerFor(CrtResponseAdapter.class);
private final HttpClientConnection connection;
private final CompletableFuture<Void> completionFuture;
private final SdkAsyncHttpResponseHandler responseHandler;
private final SimplePublisher<ByteBuffer> responsePublisher = new SimplePublisher<>();
private final SdkHttpResponse.Builder responseBuilder = SdkHttpResponse.builder();
private CrtResponseAdapter(HttpClientConnection connection,
CompletableFuture<Void> completionFuture,
SdkAsyncHttpResponseHandler responseHandler) {
this.connection = Validate.paramNotNull(connection, "connection");
this.completionFuture = Validate.paramNotNull(completionFuture, "completionFuture");
this.responseHandler = Validate.paramNotNull(responseHandler, "responseHandler");
}
public static HttpStreamResponseHandler toCrtResponseHandler(HttpClientConnection crtConn,
CompletableFuture<Void> requestFuture,
SdkAsyncHttpResponseHandler responseHandler) {
return new CrtResponseAdapter(crtConn, requestFuture, responseHandler);
}
@Override
public void onResponseHeaders(HttpStream stream, int responseStatusCode, int headerType, HttpHeader[] nextHeaders) {
if (headerType == HttpHeaderBlock.MAIN.getValue()) {
for (HttpHeader h : nextHeaders) {
responseBuilder.appendHeader(h.getName(), h.getValue());
}
}
}
@Override
public void onResponseHeadersDone(HttpStream stream, int headerType) {
if (headerType == HttpHeaderBlock.MAIN.getValue()) {
responseBuilder.statusCode(stream.getResponseStatusCode());
responseHandler.onHeaders(responseBuilder.build());
responseHandler.onStream(responsePublisher);
}
}
@Override
public int onResponseBody(HttpStream stream, byte[] bodyBytesIn) {
CompletableFuture<Void> writeFuture = responsePublisher.send(ByteBuffer.wrap(bodyBytesIn));
if (writeFuture.isDone() && !writeFuture.isCompletedExceptionally()) {
// Optimization: If write succeeded immediately, return non-zero to avoid the extra call back into the CRT.
return bodyBytesIn.length;
}
writeFuture.whenComplete((result, failure) -> {
if (failure != null) {
failResponseHandlerAndFuture(stream, failure);
return;
}
stream.incrementWindow(bodyBytesIn.length);
});
return 0;
}
@Override
public void onResponseComplete(HttpStream stream, int errorCode) {
if (errorCode == CRT.AWS_CRT_SUCCESS) {
onSuccessfulResponseComplete(stream);
} else {
onFailedResponseComplete(stream, new HttpException(errorCode));
}
}
private void onSuccessfulResponseComplete(HttpStream stream) {
responsePublisher.complete().whenComplete((result, failure) -> {
if (failure != null) {
failResponseHandlerAndFuture(stream, failure);
return;
}
if (HttpStatusFamily.of(responseBuilder.statusCode()) == HttpStatusFamily.SERVER_ERROR) {
connection.shutdown();
}
connection.close();
stream.close();
completionFuture.complete(null);
});
}
private void onFailedResponseComplete(HttpStream stream, HttpException error) {
log.debug(() -> "HTTP response encountered an error.", error);
Throwable toThrow = error;
if (HttpClientConnection.isErrorRetryable(error)) {
// IOExceptions get retried, and if the CRT says this error is retryable,
// it's semantically an IOException anyway.
toThrow = new IOException(error);
}
responsePublisher.error(toThrow);
failResponseHandlerAndFuture(stream, toThrow);
}
private void failResponseHandlerAndFuture(HttpStream stream, Throwable error) {
callResponseHandlerOnError(error);
completionFuture.completeExceptionally(error);
connection.shutdown();
connection.close();
stream.close();
}
private void callResponseHandlerOnError(Throwable error) {
try {
responseHandler.onError(error);
} catch (RuntimeException e) {
log.warn(() -> "Exception raised from SdkAsyncHttpResponseHandler#onError.", e);
}
}
}
| 1,021 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/request/CrtRequestBodyAdapter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt.internal.request;
import java.nio.ByteBuffer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.http.HttpRequestBodyStream;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber;
import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult;
@SdkInternalApi
final class CrtRequestBodyAdapter implements HttpRequestBodyStream {
private final SdkHttpContentPublisher requestPublisher;
private final ByteBufferStoringSubscriber requestBodySubscriber;
CrtRequestBodyAdapter(SdkHttpContentPublisher requestPublisher, long readLimit) {
this.requestPublisher = requestPublisher;
this.requestBodySubscriber = new ByteBufferStoringSubscriber(readLimit);
requestPublisher.subscribe(requestBodySubscriber);
}
@Override
public boolean sendRequestBody(ByteBuffer bodyBytesOut) {
return requestBodySubscriber.transferTo(bodyBytesOut) == TransferResult.END_OF_STREAM;
}
@Override
public long getLength() {
return requestPublisher.contentLength().orElse(0L);
}
}
| 1,022 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/main/java/software/amazon/awssdk/http/crt/internal/request/CrtRequestAdapter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.crt.internal.request;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.http.HttpHeader;
import software.amazon.awssdk.crt.http.HttpRequest;
import software.amazon.awssdk.http.Header;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.crt.internal.CrtRequestContext;
@SdkInternalApi
public final class CrtRequestAdapter {
private CrtRequestAdapter() {
}
public static HttpRequest toCrtRequest(CrtRequestContext request) {
AsyncExecuteRequest sdkExecuteRequest = request.sdkRequest();
SdkHttpRequest sdkRequest = sdkExecuteRequest.request();
String method = sdkRequest.method().name();
String encodedPath = sdkRequest.encodedPath();
if (encodedPath == null || encodedPath.isEmpty()) {
encodedPath = "/";
}
String encodedQueryString = sdkRequest.encodedQueryParameters()
.map(value -> "?" + value)
.orElse("");
HttpHeader[] crtHeaderArray = asArray(createHttpHeaderList(sdkRequest.getUri(), sdkExecuteRequest));
return new HttpRequest(method,
encodedPath + encodedQueryString,
crtHeaderArray,
new CrtRequestBodyAdapter(sdkExecuteRequest.requestContentPublisher(),
request.readBufferSize()));
}
private static HttpHeader[] asArray(List<HttpHeader> crtHeaderList) {
return crtHeaderList.toArray(new HttpHeader[0]);
}
private static List<HttpHeader> createHttpHeaderList(URI uri, AsyncExecuteRequest sdkExecuteRequest) {
SdkHttpRequest sdkRequest = sdkExecuteRequest.request();
// worst case we may add 3 more headers here
List<HttpHeader> crtHeaderList = new ArrayList<>(sdkRequest.numHeaders() + 3);
// Set Host Header if needed
if (!sdkRequest.firstMatchingHeader(Header.HOST).isPresent()) {
crtHeaderList.add(new HttpHeader(Header.HOST, uri.getHost()));
}
// Add Connection Keep Alive Header to reuse this Http Connection as long as possible
if (!sdkRequest.firstMatchingHeader(Header.CONNECTION).isPresent()) {
crtHeaderList.add(new HttpHeader(Header.CONNECTION, Header.KEEP_ALIVE_VALUE));
}
// Set Content-Length if needed
Optional<Long> contentLength = sdkExecuteRequest.requestContentPublisher().contentLength();
if (!sdkRequest.firstMatchingHeader(Header.CONTENT_LENGTH).isPresent() && contentLength.isPresent()) {
crtHeaderList.add(new HttpHeader(Header.CONTENT_LENGTH, Long.toString(contentLength.get())));
}
// Add the rest of the Headers
sdkRequest.forEachHeader((key, value) -> {
value.stream().map(val -> new HttpHeader(key, val)).forEach(crtHeaderList::add);
});
return crtHeaderList;
}
}
| 1,023 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URISyntaxException;
import java.util.Optional;
import java.util.Set;
import software.amazon.awssdk.http.HttpProxyTestSuite;
import software.amazon.awssdk.http.proxy.TestProxySetting;
public class NettyProxyConfigurationTest extends HttpProxyTestSuite {
@Override
protected void assertProxyConfiguration(TestProxySetting userSetProxySettings, TestProxySetting expectedProxySettings,
Boolean useSystemProperty, Boolean useEnvironmentVariable, String protocol) throws URISyntaxException {
ProxyConfiguration.Builder builder = ProxyConfiguration.builder();
if (userSetProxySettings != null) {
String hostName = userSetProxySettings.getHost();
Integer portNumber = userSetProxySettings.getPort();
String userName = userSetProxySettings.getUserName();
String password = userSetProxySettings.getPassword();
Set<String> nonProxyHosts = userSetProxySettings.getNonProxyHosts();
Optional.ofNullable(hostName).ifPresent(builder::host);
Optional.ofNullable(portNumber).ifPresent(builder::port);
Optional.ofNullable(userName).ifPresent(builder::username);
Optional.ofNullable(password).ifPresent(builder::password);
if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) {
builder.nonProxyHosts(nonProxyHosts);
}
}
if (!"http".equals(protocol)) {
builder.scheme(protocol);
}
if (useSystemProperty != null) {
builder.useSystemPropertyValues(useSystemProperty);
}
if (useEnvironmentVariable != null) {
builder.useEnvironmentVariableValues(useEnvironmentVariable);
}
ProxyConfiguration proxyConfiguration = builder.build();
assertThat(proxyConfiguration.host()).isEqualTo(expectedProxySettings.getHost());
assertThat(proxyConfiguration.port()).isEqualTo(expectedProxySettings.getPort());
assertThat(proxyConfiguration.username()).isEqualTo(expectedProxySettings.getUserName());
assertThat(proxyConfiguration.password()).isEqualTo(expectedProxySettings.getPassword());
assertThat(proxyConfiguration.nonProxyHosts()).isEqualTo(expectedProxySettings.getNonProxyHosts());
}
}
| 1,024 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/SdkEventLoopGroupTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.epoll.EpollDatagramChannel;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.channel.socket.oio.OioDatagramChannel;
import io.netty.channel.socket.oio.OioSocketChannel;
import org.junit.Test;
public class SdkEventLoopGroupTest {
@Test
public void creatingUsingBuilder() {
SdkEventLoopGroup sdkEventLoopGroup = SdkEventLoopGroup.builder().numberOfThreads(1).build();
assertThat(sdkEventLoopGroup.channelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.datagramChannelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.eventLoopGroup()).isNotNull();
}
@Test
public void creatingUsingStaticMethod_A() {
SdkEventLoopGroup sdkEventLoopGroup = SdkEventLoopGroup.create(new NioEventLoopGroup(), NioSocketChannel::new);
assertThat(sdkEventLoopGroup.channelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.datagramChannelFactory().newChannel()).isInstanceOf(NioDatagramChannel.class);
assertThat(sdkEventLoopGroup.eventLoopGroup()).isNotNull();
}
@Test
public void creatingUsingStaticMethod_B() {
SdkEventLoopGroup sdkEventLoopGroup = SdkEventLoopGroup.create(new OioEventLoopGroup(), OioSocketChannel::new);
assertThat(sdkEventLoopGroup.channelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.datagramChannelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.datagramChannelFactory().newChannel()).isInstanceOf(OioDatagramChannel.class);
assertThat(sdkEventLoopGroup.eventLoopGroup()).isNotNull();
}
@Test
public void notProvidingChannelFactory_channelFactoryResolved() {
SdkEventLoopGroup sdkEventLoopGroup = SdkEventLoopGroup.create(new NioEventLoopGroup());
assertThat(sdkEventLoopGroup.channelFactory()).isNotNull();
assertThat(sdkEventLoopGroup.datagramChannelFactory().newChannel()).isInstanceOf(NioDatagramChannel.class);
}
@Test(expected = IllegalArgumentException.class)
public void notProvidingChannelFactory_unknownEventLoopGroup() {
SdkEventLoopGroup.create(new DefaultEventLoopGroup());
}
}
| 1,025 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/Http2MetricsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.Http2StreamFrame;
import io.netty.util.ReferenceCountUtil;
import java.net.URI;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.Http2Metric;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricCollector;
public class Http2MetricsTest {
private static final int H2_DEFAULT_WINDOW_SIZE = 65535;
private static final int SERVER_MAX_CONCURRENT_STREAMS = 2;
private static final int SERVER_INITIAL_WINDOW_SIZE = 65535 * 2;
private static final TestHttp2Server SERVER = new TestHttp2Server();
@BeforeAll
public static void setup() throws InterruptedException {
SERVER.start();
}
@AfterAll
public static void teardown() throws InterruptedException {
SERVER.stop();
}
@Test
public void maxClientStreamsLowerThanServerMaxStreamsReportClientMaxStreams() {
try (SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder()
.protocol(Protocol.HTTP2)
.maxConcurrency(10)
.http2Configuration(c -> c.maxStreams(1L)
.initialWindowSize(65535 * 3))
.build()) {
MetricCollector metricCollector = MetricCollector.create("test");
client.execute(createExecuteRequest(metricCollector)).join();
MetricCollection metrics = metricCollector.collect();
assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("NettyNio");
assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(10);
assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY).get(0)).isBetween(0, 1);
assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES).get(0)).isBetween(0, 1);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0);
assertThat(metrics.metricValues(HttpMetric.CONCURRENCY_ACQUIRE_DURATION).get(0)).isPositive();
// The stream window doesn't get initialized with the connection
// initial setting and the update appears to be asynchronous so
// this may be the default window size just based on when the
// stream window was queried or if this is the first time the
// stream is used (i.e. not previously pooled)
assertThat(metrics.metricValues(Http2Metric.LOCAL_STREAM_WINDOW_SIZE_IN_BYTES).get(0)).isIn(H2_DEFAULT_WINDOW_SIZE, 65535 * 3);
assertThat(metrics.metricValues(Http2Metric.REMOTE_STREAM_WINDOW_SIZE_IN_BYTES)).containsExactly(SERVER_INITIAL_WINDOW_SIZE);
}
}
@Test
public void maxClientStreamsHigherThanServerMaxStreamsReportServerMaxStreams() {
try (SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder()
.protocol(Protocol.HTTP2)
.maxConcurrency(10)
.http2Configuration(c -> c.maxStreams(3L)
.initialWindowSize(65535 * 3))
.build()) {
MetricCollector metricCollector = MetricCollector.create("test");
client.execute(createExecuteRequest(metricCollector)).join();
MetricCollection metrics = metricCollector.collect();
assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("NettyNio");
assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(10);
assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY).get(0)).isBetween(0, 1);
assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES).get(0)).isBetween(0, 1);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY).get(0)).isIn(0, 2, 3);
assertThat(metrics.metricValues(HttpMetric.CONCURRENCY_ACQUIRE_DURATION).get(0)).isPositive();
// The stream window doesn't get initialized with the connection
// initial setting and the update appears to be asynchronous so
// this may be the default window size just based on when the
// stream window was queried or if this is the first time the
// stream is used (i.e. not previously pooled)
assertThat(metrics.metricValues(Http2Metric.LOCAL_STREAM_WINDOW_SIZE_IN_BYTES).get(0)).isIn(H2_DEFAULT_WINDOW_SIZE, 65535 * 3);
assertThat(metrics.metricValues(Http2Metric.REMOTE_STREAM_WINDOW_SIZE_IN_BYTES)).containsExactly(SERVER_INITIAL_WINDOW_SIZE);
}
}
private AsyncExecuteRequest createExecuteRequest(MetricCollector metricCollector) {
URI uri = URI.create("http://localhost:" + SERVER.port());
SdkHttpRequest request = createRequest(uri);
return AsyncExecuteRequest.builder()
.request(request)
.requestContentPublisher(new EmptyPublisher())
.responseHandler(new RecordingResponseHandler())
.metricCollector(metricCollector)
.build();
}
private SdkHttpFullRequest createRequest(URI uri) {
return SdkHttpFullRequest.builder()
.uri(uri)
.method(SdkHttpMethod.GET)
.encodedPath("/")
.putHeader("Host", uri.getHost())
.putHeader("Content-Length", "0")
.build();
}
private static final class TestHttp2Server extends ChannelInitializer<SocketChannel> {
private ServerBootstrap bootstrap;
private ServerSocketChannel channel;
private TestHttp2Server() {
}
public void start() throws InterruptedException {
bootstrap = new ServerBootstrap()
.channel(NioServerSocketChannel.class)
.group(new NioEventLoopGroup())
.childHandler(this)
.localAddress(0)
.childOption(ChannelOption.SO_KEEPALIVE, true);
channel = ((ServerSocketChannel) bootstrap.bind().await().channel());
}
public int port() {
return channel.localAddress().getPort();
}
public void stop() throws InterruptedException {
channel.close().await();
}
@Override
protected void initChannel(SocketChannel ch) {
Http2FrameCodec codec = Http2FrameCodecBuilder.forServer()
.initialSettings(new Http2Settings()
.maxConcurrentStreams(SERVER_MAX_CONCURRENT_STREAMS)
.initialWindowSize(SERVER_INITIAL_WINDOW_SIZE))
.build();
ch.pipeline().addLast(codec);
ch.pipeline().addLast(new SuccessfulHandler());
}
}
private static class SuccessfulHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (!(msg instanceof Http2Frame)) {
ctx.fireChannelRead(msg);
return;
}
ReferenceCountUtil.release(msg);
boolean isEnd = isEndFrame(msg);
if (isEnd) {
ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers().status("204"), true)
.stream(((Http2StreamFrame) msg).stream()));
}
}
private boolean isEndFrame(Object msg) {
if (msg instanceof Http2HeadersFrame) {
return ((Http2HeadersFrame) msg).isEndStream();
}
if (msg instanceof Http2DataFrame) {
return ((Http2DataFrame) msg).isEndStream();
}
return false;
}
}
}
| 1,026 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClientNonBlockingDnsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static java.util.Collections.singletonMap;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.StringUtils.reverse;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.assertCanReceiveBasicRequest;
import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.createProvider;
import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.createRequest;
import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.makeSimpleRequest;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.assertj.core.api.Condition;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.utils.AttributeMap;
@RunWith(MockitoJUnitRunner.class)
public class NettyNioAsyncHttpClientNonBlockingDnsTest {
private final RecordingNetworkTrafficListener wiremockTrafficListener = new RecordingNetworkTrafficListener();
private static final SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder()
.useNonBlockingDnsResolver(true)
.buildWithDefaults(
AttributeMap.builder()
.put(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES, true)
.build());
@Rule
public WireMockRule mockServer = new WireMockRule(wireMockConfig()
.dynamicPort()
.dynamicHttpsPort()
.networkTrafficListener(wiremockTrafficListener));
@Before
public void methodSetup() {
wiremockTrafficListener.reset();
}
@AfterClass
public static void tearDown() throws Exception {
client.close();
}
@Test
public void canSendContentAndGetThatContentBackNonBlockingDns() 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));
}
@Test
public void defaultThreadFactoryUsesHelpfulName() throws Exception {
// Make a request to ensure a thread is primed
makeSimpleRequest(client, mockServer);
String expectedPattern = "aws-java-sdk-NettyEventLoop-\\d+-\\d+";
assertThat(Thread.getAllStackTraces().keySet())
.areAtLeast(1, new Condition<>(t -> t.getName().matches(expectedPattern),
"Matches default thread pattern: `%s`", expectedPattern));
}
@Test
public void canMakeBasicRequestOverHttp() throws Exception {
String smallBody = randomAlphabetic(10);
URI uri = URI.create("http://localhost:" + mockServer.port());
assertCanReceiveBasicRequest(client, uri, smallBody);
}
@Test
public void canMakeBasicRequestOverHttps() throws Exception {
String smallBody = randomAlphabetic(10);
URI uri = URI.create("https://localhost:" + mockServer.httpsPort());
assertCanReceiveBasicRequest(client, uri, smallBody);
}
@Test
public void canHandleLargerPayloadsOverHttp() throws Exception {
String largishBody = randomAlphabetic(25000);
URI uri = URI.create("http://localhost:" + mockServer.port());
assertCanReceiveBasicRequest(client, uri, largishBody);
}
@Test
public void canHandleLargerPayloadsOverHttps() throws Exception {
String largishBody = randomAlphabetic(25000);
URI uri = URI.create("https://localhost:" + mockServer.httpsPort());
assertCanReceiveBasicRequest(client, uri, largishBody);
}
@Test
public void requestContentOnlyEqualToContentLengthHeaderFromProvider() throws InterruptedException, ExecutionException, TimeoutException, IOException {
final String content = randomAlphabetic(32);
final String streamContent = content + reverse(content);
stubFor(any(urlEqualTo("/echo?reversed=true"))
.withRequestBody(equalTo(content))
.willReturn(aResponse().withBody(reverse(content))));
URI uri = URI.create("http://localhost:" + mockServer.port());
SdkHttpFullRequest request = createRequest(uri, "/echo", streamContent, SdkHttpMethod.POST, singletonMap("reversed", "true"));
request = request.toBuilder().putHeader("Content-Length", Integer.toString(content.length())).build();
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider(streamContent)).responseHandler(recorder).build());
recorder.completeFuture.get(5, TimeUnit.SECONDS);
// HTTP servers will stop processing the request as soon as it reads
// bytes equal to 'Content-Length' so we need to inspect the raw
// traffic to ensure that there wasn't anything after that.
assertThat(wiremockTrafficListener.requests().toString()).endsWith(content);
}
}
| 1,027 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClientSpiVerificationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.Rule;
import org.junit.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Verify the behavior of {@link NettyNioAsyncHttpClient} is consistent with the SPI.
*/
public class NettyNioAsyncHttpClientSpiVerificationTest {
@Rule
public WireMockRule mockServer = new WireMockRule(wireMockConfig()
.dynamicPort()
.dynamicHttpsPort());
private static SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder().buildWithDefaults(mapWithTrustAllCerts());
@AfterClass
public static void tearDown() throws Exception {
client.close();
}
// CONNECTION_RESET_BY_PEER does not work on JDK 11. See https://github.com/tomakehurst/wiremock/issues/1009
@Test
public void signalsErrorViaOnErrorAndFuture() throws Exception {
stubFor(any(urlEqualTo("/")).willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
CompletableFuture<Boolean> errorSignaled = new CompletableFuture<>();
SdkAsyncHttpResponseHandler handler = new TestResponseHandler() {
@Override
public void onError(Throwable error) {
errorSignaled.complete(true);
}
};
SdkHttpRequest request = createRequest(URI.create("http://localhost:" + mockServer.port()));
CompletableFuture<Void> executeFuture = client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new EmptyPublisher())
.build());
assertThat(errorSignaled.get(1, TimeUnit.SECONDS)).isTrue();
assertThatThrownBy(executeFuture::join).hasCauseInstanceOf(IOException.class);
}
@Test
public void callsOnStreamForEmptyResponseContent() throws Exception {
stubFor(any(urlEqualTo("/")).willReturn(aResponse().withStatus(204).withHeader("foo", "bar")));
CompletableFuture<Boolean> streamReceived = new CompletableFuture<>();
SdkAsyncHttpResponseHandler handler = new TestResponseHandler() {
@Override
public void onStream(Publisher<ByteBuffer> stream) {
super.onStream(stream);
streamReceived.complete(true);
}
};
SdkHttpRequest request = createRequest(URI.create("http://localhost:" + mockServer.port()));
client.execute(AsyncExecuteRequest.builder()
.request(request)
.responseHandler(handler)
.requestContentPublisher(new EmptyPublisher())
.build());
assertThat(streamReceived.get(1, TimeUnit.SECONDS)).isTrue();
}
private static AttributeMap mapWithTrustAllCerts() {
return AttributeMap.builder()
.put(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES, true)
.build();
}
private SdkHttpFullRequest createRequest(URI endpoint) {
return createRequest(endpoint, "/", null, SdkHttpMethod.GET, emptyMap());
}
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();
}
private static class TestResponseHandler implements SdkAsyncHttpResponseHandler {
@Override
public void onHeaders(SdkHttpResponse headers) {
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
stream.subscribe(new DrainingSubscriber<>());
}
@Override
public void onError(Throwable error) {
}
}
private static class DrainingSubscriber<T> implements Subscriber<T> {
private Subscription subscription;
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
this.subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(T t) {
this.subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
}
}
| 1,028 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClientWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.RandomStringUtils.randomAscii;
import static org.apache.commons.lang3.StringUtils.reverse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.assertCanReceiveBasicRequest;
import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.createProvider;
import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.createRequest;
import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.makeSimpleRequest;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFactory;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslProvider;
import io.netty.util.AttributeKey;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.net.ssl.TrustManagerFactory;
import org.assertj.core.api.Condition;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.HttpTestUtils;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SimpleHttpContentPublisher;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration;
import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPool;
import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPoolMap;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.utils.AttributeMap;
@RunWith(MockitoJUnitRunner.class)
public class NettyNioAsyncHttpClientWireMockTest {
private final RecordingNetworkTrafficListener wiremockTrafficListener = new RecordingNetworkTrafficListener();
@Rule
public WireMockRule mockServer = new WireMockRule(wireMockConfig()
.dynamicPort()
.dynamicHttpsPort()
.networkTrafficListener(wiremockTrafficListener));
private static SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder().buildWithDefaults(mapWithTrustAllCerts());
@Before
public void methodSetup() {
wiremockTrafficListener.reset();
}
@AfterClass
public static void tearDown() throws Exception {
client.close();
}
@Test
public void defaultConnectionIdleTimeout() {
try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder().build()) {
assertThat(client.configuration().idleTimeoutMillis()).isEqualTo(5000);
}
}
@Test
public void defaultTlsHandshakeTimeout() {
try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.create()) {
assertThat(client.configuration().tlsHandshakeTimeout().toMillis()).isEqualTo(5000);
}
}
@Test
public void noTlsTimeout_hasConnectTimeout_shouldResolveToConnectTimeout() {
Duration connectTimeout = Duration.ofSeconds(1);
try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder()
.connectionTimeout(connectTimeout)
.build()) {
assertThat(client.configuration().tlsHandshakeTimeout()).isEqualTo(connectTimeout);
}
Duration timeoutOverride = Duration.ofSeconds(2);
try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder()
.connectionTimeout(timeoutOverride)
.build()) {
assertThat(client.configuration().tlsHandshakeTimeout()).isEqualTo(timeoutOverride);
}
}
@Test
public void tlsTimeoutConfigured_shouldHonor() {
Duration connectTimeout = Duration.ofSeconds(1);
Duration tlsTimeout = Duration.ofSeconds(3);
try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder()
.tlsNegotiationTimeout(tlsTimeout)
.connectionTimeout(connectTimeout)
.build()) {
assertThat(client.configuration().tlsHandshakeTimeout()).isEqualTo(tlsTimeout);
}
try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder()
.connectionTimeout(connectTimeout)
.tlsNegotiationTimeout(tlsTimeout)
.build()) {
assertThat(client.configuration().tlsHandshakeTimeout()).isEqualTo(tlsTimeout);
}
}
@Test
public void overrideConnectionIdleTimeout_shouldHonor() {
try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder()
.connectionMaxIdleTime(Duration.ofMillis(1000))
.build()) {
assertThat(client.configuration().idleTimeoutMillis()).isEqualTo(1000);
}
}
@Test
public void invalidMaxPendingConnectionAcquireConfig_shouldPropagateException() {
try (SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder()
.maxConcurrency(1)
.maxPendingConnectionAcquires(0)
.build()) {
assertThatThrownBy(() -> makeSimpleRequest(customClient, mockServer)).hasMessageContaining("java.lang"
+ ".IllegalArgumentException: maxPendingAcquires: 0 (expected: >= 1)");
}
}
@Test
public void customFactoryIsUsed() throws Exception {
ThreadFactory threadFactory = spy(new CustomThreadFactory());
SdkAsyncHttpClient customClient =
NettyNioAsyncHttpClient.builder()
.eventLoopGroupBuilder(SdkEventLoopGroup.builder()
.threadFactory(threadFactory))
.build();
makeSimpleRequest(customClient, mockServer);
customClient.close();
Mockito.verify(threadFactory, atLeastOnce()).newThread(Mockito.any());
}
@Test
public void openSslBeingUsed() throws Exception {
try (SdkAsyncHttpClient customClient =
NettyNioAsyncHttpClient.builder()
.sslProvider(SslProvider.OPENSSL)
.build()) {
makeSimpleRequest(customClient, mockServer);
}
}
@Test
public void defaultJdkSslProvider() throws Exception {
try (SdkAsyncHttpClient customClient =
NettyNioAsyncHttpClient.builder()
.sslProvider(SslProvider.JDK)
.build()) {
makeSimpleRequest(customClient, mockServer);
customClient.close();
}
}
@Test
public void defaultThreadFactoryUsesHelpfulName() throws Exception {
// Make a request to ensure a thread is primed
makeSimpleRequest(client, mockServer);
String expectedPattern = "aws-java-sdk-NettyEventLoop-\\d+-\\d+";
assertThat(Thread.getAllStackTraces().keySet())
.areAtLeast(1, new Condition<>(t -> t.getName().matches(expectedPattern),
"Matches default thread pattern: `%s`", expectedPattern));
}
@Test
public void customThreadCountIsRespected() throws Exception {
final int threadCount = 10;
ThreadFactory threadFactory = spy(new CustomThreadFactory());
SdkAsyncHttpClient customClient =
NettyNioAsyncHttpClient.builder()
.eventLoopGroupBuilder(SdkEventLoopGroup.builder()
.threadFactory(threadFactory)
.numberOfThreads(threadCount))
.build();
// Have to make enough requests to prime the threads
for (int i = 0; i < threadCount + 1; i++) {
makeSimpleRequest(customClient, mockServer);
}
customClient.close();
Mockito.verify(threadFactory, times(threadCount)).newThread(Mockito.any());
}
@Test
public void customEventLoopGroup_NotClosedWhenClientIsClosed() throws Exception {
ThreadFactory threadFactory = spy(new CustomThreadFactory());
// Cannot use DefaultEventLoopGroupFactory because the concrete
// implementation it creates is platform-dependent and could be a final
// (i.e. non-spyable) class.
EventLoopGroup eventLoopGroup = spy(new NioEventLoopGroup(0, threadFactory));
SdkAsyncHttpClient customClient =
NettyNioAsyncHttpClient.builder()
.eventLoopGroup(SdkEventLoopGroup.create(eventLoopGroup, NioSocketChannel::new))
.build();
makeSimpleRequest(customClient, mockServer);
customClient.close();
Mockito.verify(threadFactory, atLeastOnce()).newThread(Mockito.any());
Mockito.verify(eventLoopGroup, never()).shutdownGracefully();
}
@Test
public void customChannelFactoryIsUsed() throws Exception {
ChannelFactory channelFactory = mock(ChannelFactory.class);
when(channelFactory.newChannel()).thenAnswer((Answer<NioSocketChannel>) invocationOnMock -> new NioSocketChannel());
EventLoopGroup customEventLoopGroup = new NioEventLoopGroup();
SdkAsyncHttpClient customClient =
NettyNioAsyncHttpClient.builder()
.eventLoopGroup(SdkEventLoopGroup.create(customEventLoopGroup, channelFactory))
.build();
makeSimpleRequest(customClient, mockServer);
customClient.close();
Mockito.verify(channelFactory, atLeastOnce()).newChannel();
assertThat(customEventLoopGroup.isShuttingDown()).isFalse();
customEventLoopGroup.shutdownGracefully().awaitUninterruptibly();
}
@Test
public void closeClient_shouldCloseUnderlyingResources() {
SdkEventLoopGroup eventLoopGroup = SdkEventLoopGroup.builder().build();
SdkChannelPool channelPool = mock(SdkChannelPool.class);
SdkChannelPoolMap<URI, SdkChannelPool> sdkChannelPoolMap = new SdkChannelPoolMap<URI, SdkChannelPool>() {
@Override
protected SdkChannelPool newPool(URI key) {
return channelPool;
}
};
sdkChannelPoolMap.get(URI.create("http://blah"));
NettyConfiguration nettyConfiguration = new NettyConfiguration(AttributeMap.empty());
SdkAsyncHttpClient customerClient =
new NettyNioAsyncHttpClient(eventLoopGroup, sdkChannelPoolMap, nettyConfiguration);
customerClient.close();
assertThat(eventLoopGroup.eventLoopGroup().isShuttingDown()).isTrue();
assertThat(eventLoopGroup.eventLoopGroup().isTerminated()).isTrue();
assertThat(sdkChannelPoolMap).isEmpty();
Mockito.verify(channelPool).close();
}
@Test
public void responseConnectionReused_shouldReleaseChannel() throws Exception {
ChannelFactory channelFactory = mock(ChannelFactory.class);
EventLoopGroup customEventLoopGroup = new NioEventLoopGroup(1);
NioSocketChannel channel = new NioSocketChannel();
when(channelFactory.newChannel()).thenAnswer((Answer<NioSocketChannel>) invocationOnMock -> channel);
SdkEventLoopGroup eventLoopGroup = SdkEventLoopGroup.create(customEventLoopGroup, channelFactory);
NettyNioAsyncHttpClient customClient =
(NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder()
.eventLoopGroup(eventLoopGroup)
.maxConcurrency(1)
.build();
makeSimpleRequest(customClient, mockServer);
verifyChannelRelease(channel);
assertThat(channel.isShutdown()).isFalse();
customClient.close();
eventLoopGroup.eventLoopGroup().shutdownGracefully().awaitUninterruptibly();
}
@Test
public void connectionInactive_shouldReleaseChannel() throws Exception {
ChannelFactory channelFactory = mock(ChannelFactory.class);
EventLoopGroup customEventLoopGroup = new NioEventLoopGroup(1);
NioSocketChannel channel = new NioSocketChannel();
when(channelFactory.newChannel()).thenAnswer((Answer<NioSocketChannel>) invocationOnMock -> channel);
SdkEventLoopGroup eventLoopGroup = SdkEventLoopGroup.create(customEventLoopGroup, channelFactory);
NettyNioAsyncHttpClient customClient =
(NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder()
.eventLoopGroup(eventLoopGroup)
.maxConcurrency(1)
.build();
String body = randomAlphabetic(10);
URI uri = URI.create("http://localhost:" + mockServer.port());
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body)
.withStatus(500)
.withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
customClient.execute(AsyncExecuteRequest.builder()
.request(request)
.requestContentPublisher(createProvider(""))
.responseHandler(recorder).build());
verifyChannelRelease(channel);
assertThat(channel.isShutdown()).isTrue();
customClient.close();
eventLoopGroup.eventLoopGroup().shutdownGracefully().awaitUninterruptibly();
}
@Test
public void responseConnectionClosed_shouldCloseAndReleaseChannel() throws Exception {
ChannelFactory channelFactory = mock(ChannelFactory.class);
EventLoopGroup customEventLoopGroup = new NioEventLoopGroup(1);
NioSocketChannel channel = new NioSocketChannel();
when(channelFactory.newChannel()).thenAnswer((Answer<NioSocketChannel>) invocationOnMock -> channel);
URI uri = URI.create("http://localhost:" + mockServer.port());
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
SdkEventLoopGroup eventLoopGroup = SdkEventLoopGroup.create(customEventLoopGroup, channelFactory);
NettyNioAsyncHttpClient customClient =
(NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder()
.eventLoopGroup(eventLoopGroup)
.maxConcurrency(1)
.build();
String body = randomAlphabetic(10);
stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body)
.withStatus(500)
.withHeader("Connection", "close")
));
customClient.execute(AsyncExecuteRequest.builder()
.request(request)
.requestContentPublisher(createProvider(""))
.responseHandler(recorder).build());
recorder.completeFuture.get(5, TimeUnit.SECONDS);
verifyChannelRelease(channel);
assertThat(channel.isShutdown()).isTrue();
customClient.close();
eventLoopGroup.eventLoopGroup().shutdownGracefully().awaitUninterruptibly();
}
@Test
public void builderUsesProvidedTrustManagersProvider() throws Exception {
WireMockServer selfSignedServer = HttpTestUtils.createSelfSignedServer();
TrustManagerFactory managerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
managerFactory.init(HttpTestUtils.getSelfSignedKeyStore());
try (SdkAsyncHttpClient netty = NettyNioAsyncHttpClient.builder()
.tlsTrustManagersProvider(managerFactory::getTrustManagers)
.build()) {
selfSignedServer.start();
URI uri = URI.create("https://localhost:" + selfSignedServer.httpsPort());
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
netty.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build());
recorder.completeFuture.get(5, TimeUnit.SECONDS);
} finally {
selfSignedServer.stop();
}
}
@Test
public void canMakeBasicRequestOverHttp() throws Exception {
String smallBody = randomAlphabetic(10);
URI uri = URI.create("http://localhost:" + mockServer.port());
assertCanReceiveBasicRequest(client, uri, smallBody);
}
@Test
public void canMakeBasicRequestOverHttps() throws Exception {
String smallBody = randomAlphabetic(10);
URI uri = URI.create("https://localhost:" + mockServer.httpsPort());
assertCanReceiveBasicRequest(client, uri, smallBody);
}
@Test
public void canHandleLargerPayloadsOverHttp() throws Exception {
String largishBody = randomAlphabetic(25000);
URI uri = URI.create("http://localhost:" + mockServer.port());
assertCanReceiveBasicRequest(client, uri, largishBody);
}
@Test
public void canHandleLargerPayloadsOverHttps() throws Exception {
String largishBody = randomAlphabetic(25000);
URI uri = URI.create("https://localhost:" + mockServer.httpsPort());
assertCanReceiveBasicRequest(client, uri, largishBody);
}
@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));
}
@Test
public void requestContentOnlyEqualToContentLengthHeaderFromProvider() throws InterruptedException, ExecutionException, TimeoutException, IOException {
final String content = randomAlphabetic(32);
final String streamContent = content + reverse(content);
stubFor(any(urlEqualTo("/echo?reversed=true"))
.withRequestBody(equalTo(content))
.willReturn(aResponse().withBody(reverse(content))));
URI uri = URI.create("http://localhost:" + mockServer.port());
SdkHttpFullRequest request = createRequest(uri, "/echo", streamContent, SdkHttpMethod.POST, singletonMap("reversed", "true"));
request = request.toBuilder().putHeader("Content-Length", Integer.toString(content.length())).build();
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider(streamContent)).responseHandler(recorder).build());
recorder.completeFuture.get(5, TimeUnit.SECONDS);
// HTTP servers will stop processing the request as soon as it reads
// bytes equal to 'Content-Length' so we need to inspect the raw
// traffic to ensure that there wasn't anything after that.
assertThat(wiremockTrafficListener.requests().toString()).endsWith(content);
}
@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();
}
@Test
public void execute_requestByteBufferWithNonZeroPosition_shouldHonor() throws Exception {
String body = randomAlphabetic(70);
byte[] content = randomAscii(100).getBytes();
ByteBuffer requestContent = ByteBuffer.wrap(content);
requestContent.position(95);
String expected = new String(content, 95, 5);
URI uri = URI.create("http://localhost:" + mockServer.port());
stubFor(post(urlPathEqualTo("/"))
.withRequestBody(equalTo(expected)).willReturn(aResponse().withBody(body)));
SdkHttpRequest request = createRequest(uri, "/", expected, SdkHttpMethod.POST, emptyMap());
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(new SimpleHttpContentPublisher(requestContent)).responseHandler(recorder).build());
recorder.completeFuture.get(5, TimeUnit.SECONDS);
verify(postRequestedFor(urlPathEqualTo("/")).withRequestBody(equalTo(expected)));
}
// Needs to be a non-anon class in order to spy
public static class CustomThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
return new Thread(r);
}
}
@Test
public void testExceptionMessageChanged_WhenPendingAcquireQueueIsFull() throws Exception {
String expectedErrorMsg = "Maximum pending connection acquisitions exceeded.";
SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder()
.maxConcurrency(1)
.maxPendingConnectionAcquires(1)
.build();
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
futures.add(makeSimpleRequestAndReturnResponseHandler(customClient, 1000).completeFuture);
}
assertThatThrownBy(() -> CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join())
.hasMessageContaining(expectedErrorMsg);
customClient.close();
}
@Test
public void testExceptionMessageChanged_WhenConnectionTimeoutErrorEncountered() throws Exception {
String expectedErrorMsg = "Acquire operation took longer than the configured maximum time. This indicates that a request "
+ "cannot get a connection from the pool within the specified maximum time.";
SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder()
.maxConcurrency(1)
.connectionTimeout(Duration.ofMillis(1))
.connectionAcquisitionTimeout(Duration.ofMillis(1))
.build();
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < 2; i++) {
futures.add(makeSimpleRequestAndReturnResponseHandler(customClient, 1000).completeFuture);
}
assertThatThrownBy(() -> CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join())
.hasMessageContaining(expectedErrorMsg);
customClient.close();
}
@Test
public void createNettyClient_ReadWriteTimeoutCanBeZero() throws Exception {
SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder()
.readTimeout(Duration.ZERO)
.writeTimeout(Duration.ZERO)
.build();
makeSimpleRequest(customClient, mockServer);
customClient.close();
}
@Test
public void createNettyClient_tlsNegotiationTimeoutNotPositive_shouldThrowException() throws Exception {
assertThatThrownBy(() -> NettyNioAsyncHttpClient.builder()
.tlsNegotiationTimeout(Duration.ZERO)
.build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("must be positive");
assertThatThrownBy(() -> NettyNioAsyncHttpClient.builder()
.tlsNegotiationTimeout(Duration.ofSeconds(-1))
.build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("must be positive");
}
@Test
public void metricsAreCollectedWhenMaxPendingConnectionAcquisitionsAreExceeded() throws Exception {
SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder()
.maxConcurrency(1)
.maxPendingConnectionAcquires(1)
.build();
List<RecordingResponseHandler> handlers = new ArrayList<>();
for (int i = 0; i < 10; i++) {
handlers.add(makeSimpleRequestAndReturnResponseHandler(customClient, 1000));
}
for (RecordingResponseHandler handler : handlers) {
try {
handler.executionFuture.join();
} catch (Exception e) {
// Ignored.
}
MetricCollection metrics = handler.collector.collect();
assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("NettyNio");
assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(1);
assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES)).allSatisfy(a -> assertThat(a).isBetween(0, 9));
assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY)).allSatisfy(a -> assertThat(a).isBetween(0, 1));
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).allSatisfy(a -> assertThat(a).isBetween(0, 1));
}
customClient.close();
}
@Test
public void metricsAreCollectedForSuccessfulCalls() throws Exception {
SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder()
.maxConcurrency(10)
.build();
RecordingResponseHandler handler = makeSimpleRequestAndReturnResponseHandler(customClient);
handler.executionFuture.get(10, TimeUnit.SECONDS);
Thread.sleep(5_000);
MetricCollection metrics = handler.collector.collect();
assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("NettyNio");
assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(10);
assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES).get(0)).isBetween(0, 1);
assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY).get(0)).isBetween(0, 1);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY).get(0)).isBetween(0, 1);
customClient.close();
}
@Test
public void metricsAreCollectedForClosedClientCalls() throws Exception {
SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder()
.maxConcurrency(10)
.build();
customClient.close();
RecordingResponseHandler handler = makeSimpleRequestAndReturnResponseHandler(customClient);
try {
handler.executionFuture.get(10, TimeUnit.SECONDS);
} catch (Exception e) {
// Expected
}
MetricCollection metrics = handler.collector.collect();
assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("NettyNio");
assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(10);
assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES)).containsExactly(0);
assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY)).containsExactly(0);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY).get(0)).isBetween(0, 1);
}
private void verifyChannelRelease(Channel channel) throws InterruptedException {
Thread.sleep(1000);
assertThat(channel.attr(AttributeKey.valueOf("channelPool")).get()).isNull();
}
private RecordingResponseHandler makeSimpleRequestAndReturnResponseHandler(SdkAsyncHttpClient client) throws Exception {
return makeSimpleRequestAndReturnResponseHandler(client, null);
}
private RecordingResponseHandler makeSimpleRequestAndReturnResponseHandler(SdkAsyncHttpClient client, Integer delayInMillis)
throws Exception {
String body = randomAlphabetic(10);
URI uri = URI.create("http://localhost:" + mockServer.port());
stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body).withFixedDelay(delayInMillis)));
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
recorder.executionFuture = client.execute(AsyncExecuteRequest.builder()
.request(request)
.requestContentPublisher(createProvider(""))
.responseHandler(recorder)
.metricCollector(recorder.collector)
.build());
return recorder;
}
private static AttributeMap mapWithTrustAllCerts() {
return AttributeMap.builder()
.put(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES, true)
.build();
}
}
| 1,029 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/RecordingNetworkTrafficListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
/**
* Simple implementation of {@link WiremockNetworkTrafficListener} to record all requests received as a string for later
* verification.
*/
public class RecordingNetworkTrafficListener implements WiremockNetworkTrafficListener {
private final StringBuilder requests = new StringBuilder();
@Override
public void opened(Socket socket) {
}
@Override
public void incoming(Socket socket, ByteBuffer byteBuffer) {
requests.append(StandardCharsets.UTF_8.decode(byteBuffer));
}
@Override
public void outgoing(Socket socket, ByteBuffer byteBuffer) {
}
@Override
public void closed(Socket socket) {
}
public void reset() {
requests.setLength(0);
}
public StringBuilder requests() {
return requests;
}
} | 1,030 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/ProxyWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import java.io.IOException;
import java.util.concurrent.CompletionException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
/**
* Tests for HTTP proxy functionality in the Netty client.
*/
public class ProxyWireMockTest {
private static SdkAsyncHttpClient client;
private static ProxyConfiguration proxyCfg;
private static WireMockServer mockServer = new WireMockServer(new WireMockConfiguration()
.dynamicPort()
.dynamicHttpsPort());
private static WireMockServer mockProxy = new WireMockServer(new WireMockConfiguration()
.dynamicPort()
.dynamicHttpsPort());
@BeforeClass
public static void setup() {
mockProxy.start();
mockServer.start();
mockServer.stubFor(get(urlPathEqualTo("/")).willReturn(aResponse().withStatus(200).withBody("hello")));
proxyCfg = ProxyConfiguration.builder()
.host("localhost")
.port(mockProxy.port())
.build();
}
@AfterClass
public static void teardown() {
mockServer.stop();
mockProxy.stop();
}
@After
public void methodTeardown() {
if (client != null) {
client.close();
}
client = null;
}
@Test(expected = IOException.class)
public void proxyConfigured_attemptsToConnect() throws Throwable {
AsyncExecuteRequest req = AsyncExecuteRequest.builder()
.request(testSdkRequest())
.responseHandler(mock(SdkAsyncHttpResponseHandler.class))
.build();
client = NettyNioAsyncHttpClient.builder()
.proxyConfiguration(proxyCfg)
.build();
try {
client.execute(req).join();
} catch (CompletionException e) {
Throwable cause = e.getCause();
// WireMock doesn't allow for mocking the CONNECT method so it will just return a 404, causing the client
// to throw an exception.
assertThat(e.getCause().getMessage()).isEqualTo("Could not connect to proxy");
throw cause;
}
}
@Test
public void proxyConfigured_hostInNonProxySet_doesNotConnect() {
RecordingResponseHandler responseHandler = new RecordingResponseHandler();
AsyncExecuteRequest req = AsyncExecuteRequest.builder()
.request(testSdkRequest())
.responseHandler(responseHandler)
.requestContentPublisher(new EmptyPublisher())
.build();
ProxyConfiguration cfg = proxyCfg.toBuilder()
.nonProxyHosts(Stream.of("localhost").collect(Collectors.toSet()))
.build();
client = NettyNioAsyncHttpClient.builder()
.proxyConfiguration(cfg)
.build();
client.execute(req).join();
responseHandler.completeFuture.join();
assertThat(responseHandler.fullResponseAsString()).isEqualTo("hello");
}
@Test
public void proxyConfigured_hostInNonProxySet_nonBlockingDns_doesNotConnect() {
RecordingResponseHandler responseHandler = new RecordingResponseHandler();
AsyncExecuteRequest req = AsyncExecuteRequest.builder()
.request(testSdkRequest())
.responseHandler(responseHandler)
.requestContentPublisher(new EmptyPublisher())
.build();
ProxyConfiguration cfg = proxyCfg.toBuilder()
.nonProxyHosts(Stream.of("localhost").collect(Collectors.toSet()))
.build();
client = NettyNioAsyncHttpClient.builder()
.proxyConfiguration(cfg)
.useNonBlockingDnsResolver(true)
.build();
client.execute(req).join();
responseHandler.completeFuture.join();
assertThat(responseHandler.fullResponseAsString()).isEqualTo("hello");
}
private SdkHttpFullRequest testSdkRequest() {
return SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("http")
.host("localhost")
.port(mockServer.port())
.putHeader("host", "localhost")
.build();
}
}
| 1,031 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/Http2ConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class Http2ConfigurationTest {
@Rule
public ExpectedException expected = ExpectedException.none();
@Test
public void builder_returnsInstance() {
assertThat(Http2Configuration.builder()).isNotNull();
}
@Test
public void build_buildsCorrectConfig() {
long maxStreams = 1;
int initialWindowSize = 2;
Http2Configuration config = Http2Configuration.builder()
.maxStreams(maxStreams)
.initialWindowSize(initialWindowSize)
.build();
assertThat(config.maxStreams()).isEqualTo(maxStreams);
assertThat(config.initialWindowSize()).isEqualTo(initialWindowSize);
}
@Test
public void builder_toBuilder_roundTrip() {
Http2Configuration config1 = Http2Configuration.builder()
.maxStreams(7L)
.initialWindowSize(42)
.build();
Http2Configuration config2 = config1.toBuilder().build();
assertThat(config1).isEqualTo(config2);
}
@Test
public void builder_maxStream_nullValue_doesNotThrow() {
Http2Configuration.builder().maxStreams(null);
}
@Test
public void builder_maxStream_negative_throws() {
expected.expect(IllegalArgumentException.class);
Http2Configuration.builder().maxStreams(-1L);
}
@Test
public void builder_maxStream_0_throws() {
expected.expect(IllegalArgumentException.class);
Http2Configuration.builder().maxStreams(0L);
}
@Test
public void builder_initialWindowSize_nullValue_doesNotThrow() {
Http2Configuration.builder().initialWindowSize(null);
}
@Test
public void builder_initialWindowSize_negative_throws() {
expected.expect(IllegalArgumentException.class);
Http2Configuration.builder().initialWindowSize(-1);
}
@Test
public void builder_initialWindowSize_0_throws() {
expected.expect(IllegalArgumentException.class);
Http2Configuration.builder().initialWindowSize(0);
}
}
| 1,032 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/SdkTestHttpContentPublisher.java | package software.amazon.awssdk.http.nio.netty;
import java.nio.ByteBuffer;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
public class SdkTestHttpContentPublisher implements SdkHttpContentPublisher {
private final byte[] body;
private final AtomicReference<Subscriber<? super ByteBuffer>> subscriber = new AtomicReference<>(null);
private final AtomicBoolean complete = new AtomicBoolean(false);
private final AtomicInteger cancelled = new AtomicInteger(0);
public SdkTestHttpContentPublisher(byte[] body) {
this.body = body;
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
boolean wasFirstSubscriber = subscriber.compareAndSet(null, s);
SdkTestHttpContentPublisher publisher = this;
if (wasFirstSubscriber) {
s.onSubscribe(new Subscription() {
@Override
public void request(long n) {
publisher.request(n);
}
@Override
public void cancel() {
cancelled.incrementAndGet();
// Do nothing
}
});
} else {
s.onError(new RuntimeException("Only allow one subscriber"));
}
}
protected void request(long n) {
// Send the whole body if they request >0 ByteBuffers
if (n > 0 && !complete.get()) {
complete.set(true);
subscriber.get().onNext(ByteBuffer.wrap(body));
subscriber.get().onComplete();
}
}
@Override
public Optional<Long> contentLength() {
return Optional.of((long)body.length);
}
}
| 1,033 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClientTestUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.emptyMap;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.tomakehurst.wiremock.WireMockServer;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
public class NettyNioAsyncHttpClientTestUtils {
/**
* Make a simple async request and wait for it to fiish.
*
* @param client Client to make request with.
*/
public static void makeSimpleRequest(SdkAsyncHttpClient client, WireMockServer mockServer) throws Exception {
String body = randomAlphabetic(10);
URI uri = URI.create("http://localhost:" + mockServer.port());
stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body)));
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build());
recorder.completeFuture.get(5, TimeUnit.SECONDS);
}
public static SdkHttpContentPublisher createProvider(String body) {
Stream<ByteBuffer> chunks = splitStringBySize(body).stream()
.map(chunk -> ByteBuffer.wrap(chunk.getBytes(UTF_8)));
return new SdkHttpContentPublisher() {
@Override
public Optional<Long> contentLength() {
return Optional.of(Long.valueOf(body.length()));
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
s.onSubscribe(new Subscription() {
@Override
public void request(long n) {
chunks.forEach(s::onNext);
s.onComplete();
}
@Override
public void cancel() {
}
});
}
};
}
public static SdkHttpFullRequest createRequest(URI uri) {
return createRequest(uri, "/", null, SdkHttpMethod.GET, emptyMap());
}
public static 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();
}
public static void assertCanReceiveBasicRequest(SdkAsyncHttpClient client, URI uri, String body) throws Exception {
stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withHeader("Some-Header", "With Value").withBody(body)));
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build());
recorder.completeFuture.get(5, TimeUnit.SECONDS);
assertThat(recorder.responses).hasOnlyOneElementSatisfying(
headerResponse -> {
assertThat(headerResponse.headers()).containsKey("Some-Header");
assertThat(headerResponse.statusCode()).isEqualTo(200);
});
assertThat(recorder.fullResponseAsString()).isEqualTo(body);
verify(1, getRequestedFor(urlMatching("/")));
}
private static Collection<String> splitStringBySize(String str) {
if (isBlank(str)) {
return Collections.emptyList();
}
ArrayList<String> split = new ArrayList<>();
for (int i = 0; i <= str.length() / 1000; i++) {
split.add(str.substring(i * 1000, Math.min((i + 1) * 1000, str.length())));
}
return split;
}
}
| 1,034 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/ClientTlsAuthTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
abstract class ClientTlsAuthTestBase {
protected static final String STORE_PASSWORD = "password";
protected static final String CLIENT_STORE_TYPE = "pkcs12";
protected static final String TEST_KEY_STORE = "/software/amazon/awssdk/http/netty/server-keystore";
protected static final String CLIENT_KEY_STORE = "/software/amazon/awssdk/http/netty/client1.p12";
protected static Path tempDir;
protected static Path serverKeyStore;
protected static Path clientKeyStore;
@BeforeAll
public static void setUp() throws IOException {
tempDir = Files.createTempDirectory(ClientTlsAuthTestBase.class.getSimpleName());
copyCertsToTmpDir();
}
@AfterAll
public static void teardown() throws IOException {
Files.deleteIfExists(serverKeyStore);
Files.deleteIfExists(clientKeyStore);
Files.deleteIfExists(tempDir);
}
private static void copyCertsToTmpDir() throws IOException {
InputStream sksStream = ClientTlsAuthTestBase.class.getResourceAsStream(TEST_KEY_STORE);
Path sks = copyToTmpDir(sksStream, "server-keystore");
InputStream cksStream = ClientTlsAuthTestBase.class.getResourceAsStream(CLIENT_KEY_STORE);
Path cks = copyToTmpDir(cksStream, "client1.p12");
serverKeyStore = sks;
clientKeyStore = cks;
}
private static Path copyToTmpDir(InputStream srcStream, String name) throws IOException {
Path dst = tempDir.resolve(name);
Files.copy(srcStream, dst);
return dst;
}
}
| 1,035 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyClientTlsAuthTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import java.io.IOException;
import java.util.concurrent.CompletionException;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.FileStoreTlsKeyManagersProvider;
import software.amazon.awssdk.http.HttpTestUtils;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.TlsKeyManagersProvider;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Tests to ensure that Netty layer can perform TLS client authentication.
*/
public class NettyClientTlsAuthTest extends ClientTlsAuthTestBase {
private static final AttributeMap DEFAULTS = AttributeMap.builder()
.put(TRUST_ALL_CERTIFICATES, true)
.build();
@Rule
public ExpectedException thrown = ExpectedException.none();
private static WireMockServer mockProxy;
private static ProxyConfiguration proxyCfg;
private static TlsKeyManagersProvider keyManagersProvider;
private SdkAsyncHttpClient netty;
@BeforeClass
public static void setUp() throws IOException {
ClientTlsAuthTestBase.setUp();
// Will be used by both client and server to trust the self-signed
// cert they present to each other
System.setProperty("javax.net.ssl.trustStore", serverKeyStore.toAbsolutePath().toString());
System.setProperty("javax.net.ssl.trustStorePassword", STORE_PASSWORD);
System.setProperty("javax.net.ssl.trustStoreType", "jks");
mockProxy = new WireMockServer(new WireMockConfiguration()
.dynamicHttpsPort()
.needClientAuth(true)
.keystorePath(serverKeyStore.toAbsolutePath().toString())
.keystorePassword(STORE_PASSWORD));
mockProxy.start();
mockProxy.stubFor(get(urlPathMatching(".*")).willReturn(aResponse().withStatus(200).withBody("hello")));
proxyCfg = ProxyConfiguration.builder()
.scheme("https")
.host("localhost")
.port(mockProxy.httpsPort())
.build();
keyManagersProvider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, STORE_PASSWORD);
}
@AfterClass
public static void teardown() throws IOException {
ClientTlsAuthTestBase.teardown();
mockProxy.stop();
System.clearProperty("javax.net.ssl.trustStore");
System.clearProperty("javax.net.ssl.trustStorePassword");
System.clearProperty("javax.net.ssl.trustStoreType");
}
@After
public void methodTeardown() {
if (netty != null) {
netty.close();
}
netty = null;
}
@Test
public void builderUsesProvidedKeyManagersProvider() {
TlsKeyManagersProvider mockKeyManagersProvider = mock(TlsKeyManagersProvider.class);
netty = NettyNioAsyncHttpClient.builder()
.proxyConfiguration(proxyCfg)
.tlsKeyManagersProvider(mockKeyManagersProvider)
.buildWithDefaults(DEFAULTS);
try {
sendRequest(netty, new RecordingResponseHandler());
} catch (Exception ignored) {
}
verify(mockKeyManagersProvider).keyManagers();
}
@Test
public void proxyRequest_ableToAuthenticate() {
thrown.expectCause(instanceOf(IOException.class));
thrown.expectMessage("Could not connect to proxy");
netty = NettyNioAsyncHttpClient.builder()
.proxyConfiguration(proxyCfg)
.tlsKeyManagersProvider(keyManagersProvider)
.buildWithDefaults(DEFAULTS);
sendRequest(netty, new RecordingResponseHandler());
}
@Test
public void proxyRequest_noKeyManagerGiven_notAbleToSendConnect() throws Throwable {
thrown.expectCause(instanceOf(IOException.class));
thrown.expectMessage("Unable to send CONNECT request to proxy");
netty = NettyNioAsyncHttpClient.builder()
.proxyConfiguration(proxyCfg)
.buildWithDefaults(DEFAULTS);
sendRequest(netty, new RecordingResponseHandler());
}
@Test
public void proxyRequest_keyStoreSystemPropertiesConfigured_ableToAuthenticate() throws Throwable {
thrown.expectCause(instanceOf(IOException.class));
thrown.expectMessage("Could not connect to proxy");
System.setProperty("javax.net.ssl.keyStore", clientKeyStore.toAbsolutePath().toString());
System.setProperty("javax.net.ssl.keyStoreType", CLIENT_STORE_TYPE);
System.setProperty("javax.net.ssl.keyStorePassword", STORE_PASSWORD);
netty = NettyNioAsyncHttpClient.builder()
.proxyConfiguration(proxyCfg)
.buildWithDefaults(DEFAULTS);
try {
sendRequest(netty, new RecordingResponseHandler());
} finally {
System.clearProperty("javax.net.ssl.keyStore");
System.clearProperty("javax.net.ssl.keyStoreType");
System.clearProperty("javax.net.ssl.keyStorePassword");
}
}
@Test
public void nonProxy_noKeyManagerGiven_shouldThrowException() {
netty = NettyNioAsyncHttpClient.builder()
.buildWithDefaults(DEFAULTS);
assertThatThrownBy(() -> HttpTestUtils.sendGetRequest(mockProxy.httpsPort(), netty).join())
.isInstanceOf(CompletionException.class)
.hasMessageContaining("SSL")
.hasRootCauseInstanceOf(SSLException.class);
}
@Test
public void builderUsesProvidedKeyManagersProviderNonBlockingDns() {
TlsKeyManagersProvider mockKeyManagersProvider = mock(TlsKeyManagersProvider.class);
netty = NettyNioAsyncHttpClient.builder()
.useNonBlockingDnsResolver(true)
.proxyConfiguration(proxyCfg)
.tlsKeyManagersProvider(mockKeyManagersProvider)
.buildWithDefaults(AttributeMap.builder()
.put(TRUST_ALL_CERTIFICATES, true)
.build());
try {
sendRequest(netty, new RecordingResponseHandler());
} catch (Exception ignored) {
}
verify(mockKeyManagersProvider).keyManagers();
}
private void sendRequest(SdkAsyncHttpClient client, SdkAsyncHttpResponseHandler responseHandler) {
AsyncExecuteRequest req = AsyncExecuteRequest.builder()
.request(testSdkRequest())
.requestContentPublisher(new EmptyPublisher())
.responseHandler(responseHandler)
.build();
client.execute(req).join();
}
private static SdkHttpFullRequest testSdkRequest() {
return SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("https")
.host("some-awesome-service.amazonaws.com")
.port(443)
.putHeader("host", "some-awesome-service.amazonaws.com")
.build();
}
}
| 1,036 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/ProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link ProxyConfiguration}.
*/
public class ProxyConfigurationTest {
private static final Random RNG = new Random();
private static final String TEST_HOST = "foo.com";
private static final int TEST_PORT = 7777;
private static final String TEST_NON_PROXY_HOST = "bar.com";
private static final String TEST_USER = "testuser";
private static final String TEST_PASSWORD = "123";
@BeforeEach
public void setup() {
clearProxyProperties();
}
@AfterAll
public static void cleanup() {
clearProxyProperties();
}
@Test
void build_setsAllProperties() {
verifyAllPropertiesSet(allPropertiesSetConfig());
}
@Test
void build_systemPropertyDefault_Http() {
setHttpProxyProperties();
Set<String> nonProxyHost = new HashSet<>();
nonProxyHost.add("bar.com");
ProxyConfiguration config = ProxyConfiguration.builder().build();
assertThat(config.host()).isEqualTo(TEST_HOST);
assertThat(config.port()).isEqualTo(TEST_PORT);
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHost);
assertThat(config.username()).isEqualTo(TEST_USER);
assertThat(config.password()).isEqualTo(TEST_PASSWORD);
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void build_systemPropertyEnabled_Https() {
setHttpsProxyProperties();
Set<String> nonProxyHost = new HashSet<>();
nonProxyHost.add("bar.com");
ProxyConfiguration config = ProxyConfiguration.builder()
.scheme("https")
.useSystemPropertyValues(Boolean.TRUE).build();
assertThat(config.host()).isEqualTo(TEST_HOST);
assertThat(config.port()).isEqualTo(TEST_PORT);
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHost);
assertThat(config.username()).isEqualTo(TEST_USER);
assertThat(config.password()).isEqualTo(TEST_PASSWORD);
assertThat(config.scheme()).isEqualTo("https");
}
@Test
void build_systemPropertyDisabled() {
setHttpProxyProperties();
Set<String> nonProxyHost = new HashSet<>();
nonProxyHost.add("test.com");
ProxyConfiguration config = ProxyConfiguration.builder()
.host("localhost")
.port(8888)
.nonProxyHosts(nonProxyHost)
.username("username")
.password("password")
.useSystemPropertyValues(Boolean.FALSE).build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(8888);
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHost);
assertThat(config.username()).isEqualTo("username");
assertThat(config.password()).isEqualTo("password");
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void build_systemPropertyOverride() {
setHttpProxyProperties();
Set<String> nonProxyHost = new HashSet<>();
nonProxyHost.add("test.com");
ProxyConfiguration config = ProxyConfiguration.builder()
.host("localhost")
.port(8888)
.nonProxyHosts(nonProxyHost)
.username("username")
.password("password")
.build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(8888);
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHost);
assertThat(config.username()).isEqualTo("username");
assertThat(config.password()).isEqualTo("password");
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void toBuilder_roundTrip_producesExactCopy() {
ProxyConfiguration original = allPropertiesSetConfig();
ProxyConfiguration copy = original.toBuilder().build();
assertThat(copy).isEqualTo(original);
}
@Test
void setNonProxyHostsToNull_createsEmptySet() {
ProxyConfiguration cfg = ProxyConfiguration.builder()
.nonProxyHosts(null)
.build();
assertThat(cfg.nonProxyHosts()).isEmpty();
}
@Test
void toBuilderModified_doesNotModifySource() {
ProxyConfiguration original = allPropertiesSetConfig();
ProxyConfiguration modified = setAllPropertiesToRandomValues(original.toBuilder()).build();
assertThat(original).isNotEqualTo(modified);
}
private ProxyConfiguration allPropertiesSetConfig() {
return setAllPropertiesToRandomValues(ProxyConfiguration.builder()).build();
}
private ProxyConfiguration.Builder setAllPropertiesToRandomValues(ProxyConfiguration.Builder builder) {
Stream.of(builder.getClass().getDeclaredMethods())
.filter(m -> m.getParameterCount() == 1 && m.getReturnType().equals(ProxyConfiguration.Builder.class))
.forEach(m -> {
try {
m.setAccessible(true);
setRandomValue(builder, m);
} catch (Exception e) {
throw new RuntimeException("Could not create random proxy config", e);
}
});
return builder;
}
private void setRandomValue(Object o, Method setter) throws InvocationTargetException, IllegalAccessException {
Class<?> paramClass = setter.getParameterTypes()[0];
if (String.class.equals(paramClass)) {
setter.invoke(o, randomString());
} else if (int.class.equals(paramClass)) {
setter.invoke(o, RNG.nextInt());
} else if (Set.class.isAssignableFrom(paramClass)) {
setter.invoke(o, randomSet());
} else if (Boolean.class.equals(paramClass)) {
setter.invoke(o, RNG.nextBoolean());
} else {
throw new RuntimeException("Don't know how create random value for type " + paramClass);
}
}
private void verifyAllPropertiesSet(ProxyConfiguration cfg) {
boolean hasNullProperty = Stream.of(cfg.getClass().getDeclaredMethods())
.filter(m -> !m.getReturnType().equals(Void.class) && m.getParameterCount() == 0)
.anyMatch(m -> {
m.setAccessible(true);
try {
return m.invoke(cfg) == null;
} catch (Exception e) {
return true;
}
});
if (hasNullProperty) {
throw new RuntimeException("Given configuration has unset property");
}
}
private String randomString() {
String alpha = "abcdefghijklmnopqrstuwxyz";
StringBuilder sb = new StringBuilder(16);
for (int i = 0; i < 16; ++i) {
sb.append(alpha.charAt(RNG.nextInt(16)));
}
return sb.toString();
}
private Set<String> randomSet() {
Set<String> ss = new HashSet<>(16);
for (int i = 0; i < 16; ++i) {
ss.add(randomString());
}
return ss;
}
private void setHttpProxyProperties() {
System.setProperty("http.proxyHost", TEST_HOST);
System.setProperty("http.proxyPort", Integer.toString(TEST_PORT));
System.setProperty("http.nonProxyHosts", TEST_NON_PROXY_HOST);
System.setProperty("http.proxyUser", TEST_USER);
System.setProperty("http.proxyPassword", TEST_PASSWORD);
}
private void setHttpsProxyProperties() {
System.setProperty("https.proxyHost", TEST_HOST);
System.setProperty("https.proxyPort", Integer.toString(TEST_PORT));
System.setProperty("http.nonProxyHosts", TEST_NON_PROXY_HOST);
System.setProperty("https.proxyUser", TEST_USER);
System.setProperty("https.proxyPassword", TEST_PASSWORD);
}
private static void clearProxyProperties() {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
System.clearProperty("http.nonProxyHosts");
System.clearProperty("http.proxyUser");
System.clearProperty("http.proxyPassword");
System.clearProperty("https.proxyHost");
System.clearProperty("https.proxyPort");
System.clearProperty("https.proxyUser");
System.clearProperty("https.proxyPassword");
}
}
| 1,037 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/RecordingResponseHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.async.SdkHttpResponseHandler;
import software.amazon.awssdk.http.async.SimpleSubscriber;
import software.amazon.awssdk.metrics.MetricCollector;
public final class RecordingResponseHandler implements SdkAsyncHttpResponseHandler {
List<SdkHttpResponse> responses = new ArrayList<>();
private StringBuilder bodyParts = new StringBuilder();
CompletableFuture<Void> completeFuture = new CompletableFuture<>();
CompletableFuture<Void> executionFuture = null;
MetricCollector collector = MetricCollector.create("test");
@Override
public void onHeaders(SdkHttpResponse response) {
responses.add(response);
}
@Override
public void onStream(Publisher<ByteBuffer> publisher) {
publisher.subscribe(new SimpleSubscriber(byteBuffer -> {
byte[] b = new byte[byteBuffer.remaining()];
byteBuffer.duplicate().get(b);
bodyParts.append(new String(b, StandardCharsets.UTF_8));
}) {
@Override
public void onError(Throwable t) {
completeFuture.completeExceptionally(t);
}
@Override
public void onComplete() {
completeFuture.complete(null);
}
});
}
@Override
public void onError(Throwable error) {
completeFuture.completeExceptionally(error);
}
public String fullResponseAsString() {
return bodyParts.toString();
}
}
| 1,038 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClientDefaultWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.reverse;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.assertj.core.api.Condition;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
public class NettyNioAsyncHttpClientDefaultWireMockTest {
private final RecordingNetworkTrafficListener wiremockTrafficListener = new RecordingNetworkTrafficListener();
@Rule
public WireMockRule mockServer = new WireMockRule(wireMockConfig()
.dynamicPort()
.dynamicHttpsPort()
.networkTrafficListener(wiremockTrafficListener));
private static SdkAsyncHttpClient client = NettyNioAsyncHttpClient.create();
@Before
public void methodSetup() {
wiremockTrafficListener.reset();
}
@AfterClass
public static void tearDown() throws Exception {
client.close();
}
@Test
public void defaultThreadFactoryUsesHelpfulName() throws Exception {
// Make a request to ensure a thread is primed
makeSimpleRequest(client);
String expectedPattern = "aws-java-sdk-NettyEventLoop-\\d+-\\d+";
assertThat(Thread.getAllStackTraces().keySet())
.areAtLeast(1, new Condition<>(t -> t.getName().matches(expectedPattern),
"Matches default thread pattern: `%s`", expectedPattern));
}
/**
* Make a simple async request and wait for it to fiish.
*
* @param client Client to make request with.
*/
private void makeSimpleRequest(SdkAsyncHttpClient client) throws Exception {
String body = randomAlphabetic(10);
URI uri = URI.create("http://localhost:" + mockServer.port());
stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body)));
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build());
recorder.completeFuture.get(5, TimeUnit.SECONDS);
}
@Test
public void canMakeBasicRequestOverHttp() throws Exception {
String smallBody = randomAlphabetic(10);
URI uri = URI.create("http://localhost:" + mockServer.port());
assertCanReceiveBasicRequest(uri, smallBody);
}
@Test
public void canHandleLargerPayloadsOverHttp() throws Exception {
String largishBody = randomAlphabetic(25000);
URI uri = URI.create("http://localhost:" + mockServer.port());
assertCanReceiveBasicRequest(uri, largishBody);
}
@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));
}
@Test
public void requestContentOnlyEqualToContentLengthHeaderFromProvider() throws Exception {
final String content = randomAlphabetic(32);
final String streamContent = content + reverse(content);
stubFor(any(urlEqualTo("/echo?reversed=true"))
.withRequestBody(equalTo(content))
.willReturn(aResponse().withBody(reverse(content))));
URI uri = URI.create("http://localhost:" + mockServer.port());
SdkHttpFullRequest request = createRequest(uri, "/echo", streamContent, SdkHttpMethod.POST, singletonMap("reversed", "true"));
request = request.toBuilder().putHeader("Content-Length", Integer.toString(content.length())).build();
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider(streamContent)).responseHandler(recorder).build());
recorder.completeFuture.get(5, TimeUnit.SECONDS);
// HTTP servers will stop processing the request as soon as it reads
// bytes equal to 'Content-Length' so we need to inspect the raw
// traffic to ensure that there wasn't anything after that.
assertThat(wiremockTrafficListener.requests().toString()).endsWith(content);
}
private void assertCanReceiveBasicRequest(URI uri, String body) throws Exception {
stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withHeader("Some-Header", "With Value").withBody(body)));
SdkHttpRequest request = createRequest(uri);
RecordingResponseHandler recorder = new RecordingResponseHandler();
client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build());
recorder.completeFuture.get(5, TimeUnit.SECONDS);
assertThat(recorder.responses).hasOnlyOneElementSatisfying(
headerResponse -> {
assertThat(headerResponse.headers()).containsKey("Some-Header");
assertThat(headerResponse.statusCode()).isEqualTo(200);
});
assertThat(recorder.fullResponseAsString()).isEqualTo(body);
verify(1, getRequestedFor(urlMatching("/")));
}
private SdkHttpContentPublisher createProvider(String body) {
Stream<ByteBuffer> chunks = splitStringBySize(body).stream()
.map(chunk -> ByteBuffer.wrap(chunk.getBytes(UTF_8)));
return new SdkHttpContentPublisher() {
@Override
public Optional<Long> contentLength() {
return Optional.of(Long.valueOf(body.length()));
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
s.onSubscribe(new Subscription() {
@Override
public void request(long n) {
chunks.forEach(s::onNext);
s.onComplete();
}
@Override
public void cancel() {
}
});
}
};
}
private SdkHttpFullRequest createRequest(URI uri) {
return createRequest(uri, "/", null, SdkHttpMethod.GET, emptyMap());
}
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();
}
private static Collection<String> splitStringBySize(String str) {
if (isBlank(str)) {
return Collections.emptyList();
}
ArrayList<String> split = new ArrayList<>();
for (int i = 0; i <= str.length() / 1000; i++) {
split.add(str.substring(i * 1000, Math.min((i + 1) * 1000, str.length())));
}
return split;
}
}
| 1,039 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/ProxyTunnelInitHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.DefaultChannelPromise;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.pool.ChannelPool;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.ssl.SslCloseCompletionEvent;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Promise;
import java.io.IOException;
import java.net.URI;
import java.util.Base64;
import java.util.function.Supplier;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
/**
* Unit tests for {@link ProxyTunnelInitHandler}.
*/
@RunWith(MockitoJUnitRunner.class)
public class ProxyTunnelInitHandlerTest {
private static final NioEventLoopGroup GROUP = new NioEventLoopGroup(1);
private static final URI REMOTE_HOST = URI.create("https://s3.amazonaws.com:1234");
private static final String PROXY_USER = "myuser";
private static final String PROXY_PASSWORD = "mypassword";
@Mock
private ChannelHandlerContext mockCtx;
@Mock
private Channel mockChannel;
@Mock
private ChannelPipeline mockPipeline;
@Mock
private ChannelPool mockChannelPool;
@Before
public void methodSetup() {
when(mockCtx.channel()).thenReturn(mockChannel);
when(mockCtx.pipeline()).thenReturn(mockPipeline);
when(mockChannel.writeAndFlush(any())).thenReturn(new DefaultChannelPromise(mockChannel, GROUP.next()));
}
@AfterClass
public static void teardown() {
GROUP.shutdownGracefully().awaitUninterruptibly();
}
@Test
public void addedToPipeline_addsCodec() {
HttpClientCodec codec = new HttpClientCodec();
Supplier<HttpClientCodec> codecSupplier = () -> codec;
when(mockCtx.name()).thenReturn("foo");
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, null, null, REMOTE_HOST, null, codecSupplier);
handler.handlerAdded(mockCtx);
verify(mockPipeline).addBefore(eq("foo"), eq(null), eq(codec));
}
@Test
public void successfulProxyResponse_completesFuture() {
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
successResponse(handler);
assertThat(promise.awaitUninterruptibly().getNow()).isEqualTo(mockChannel);
}
@Test
public void successfulProxyResponse_removesSelfAndCodec() {
when(mockPipeline.get(HttpClientCodec.class)).thenReturn(new HttpClientCodec());
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
successResponse(handler);
handler.handlerRemoved(mockCtx);
verify(mockPipeline).remove(eq(handler));
verify(mockPipeline).remove(eq(HttpClientCodec.class));
}
@Test
public void successfulProxyResponse_doesNotRemoveSslHandler() {
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
successResponse(handler);
verify(mockPipeline, never()).get(eq(SslHandler.class));
verify(mockPipeline, never()).remove(eq(SslHandler.class));
}
@Test
public void unexpectedMessage_failsPromise() {
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
handler.channelRead(mockCtx, new Object());
assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse();
}
@Test
public void unsuccessfulResponse_failsPromise() {
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
DefaultHttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN);
handler.channelRead(mockCtx, resp);
assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse();
}
@Test
public void requestWriteFails_failsPromise() {
DefaultChannelPromise writePromise = new DefaultChannelPromise(mockChannel, GROUP.next());
writePromise.setFailure(new IOException("boom"));
when(mockChannel.writeAndFlush(any())).thenReturn(writePromise);
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
handler.handlerAdded(mockCtx);
assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse();
}
@Test
public void channelInactive_shouldFailPromise() throws Exception {
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
SslCloseCompletionEvent event = new SslCloseCompletionEvent(new RuntimeException(""));
handler.channelInactive(mockCtx);
assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse();
verify(mockCtx).close();
}
@Test
public void unexpectedExceptionThrown_shouldFailPromise() throws Exception {
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
handler.exceptionCaught(mockCtx, new RuntimeException("exception"));
assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse();
verify(mockCtx).close();
}
@Test
public void handlerRemoved_removesCodec() {
HttpClientCodec codec = new HttpClientCodec();
when(mockPipeline.get(eq(HttpClientCodec.class))).thenReturn(codec);
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
handler.handlerRemoved(mockCtx);
verify(mockPipeline).remove(eq(HttpClientCodec.class));
}
@Test
public void handledAdded_writesRequest_withoutAuth() {
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
handler.handlerAdded(mockCtx);
ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class);
verify(mockChannel).writeAndFlush(requestCaptor.capture());
String uri = REMOTE_HOST.getHost() + ":" + REMOTE_HOST.getPort();
HttpRequest expectedRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, uri,
Unpooled.EMPTY_BUFFER, false);
expectedRequest.headers().add(HttpHeaderNames.HOST, uri);
assertThat(requestCaptor.getValue()).isEqualTo(expectedRequest);
}
@Test
public void handledAdded_writesRequest_withAuth() {
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, PROXY_USER, PROXY_PASSWORD, REMOTE_HOST, promise);
handler.handlerAdded(mockCtx);
ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class);
verify(mockChannel).writeAndFlush(requestCaptor.capture());
String uri = REMOTE_HOST.getHost() + ":" + REMOTE_HOST.getPort();
HttpRequest expectedRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, uri,
Unpooled.EMPTY_BUFFER, false);
expectedRequest.headers().add(HttpHeaderNames.HOST, uri);
String authB64 = Base64.getEncoder().encodeToString(String.format("%s:%s", PROXY_USER, PROXY_PASSWORD).getBytes(CharsetUtil.UTF_8));
expectedRequest.headers().add(HttpHeaderNames.PROXY_AUTHORIZATION, String.format("Basic %s", authB64));
assertThat(requestCaptor.getValue()).isEqualTo(expectedRequest);
}
private void successResponse(ProxyTunnelInitHandler handler) {
DefaultHttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
handler.channelRead(mockCtx, resp);
}
}
| 1,040 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/CancellableAcquireChannelPoolTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Promise;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link CancellableAcquireChannelPool}.
*/
@RunWith(MockitoJUnitRunner.class)
public class CancellableAcquireChannelPoolTest {
private static final EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
private EventExecutor eventExecutor;
@Mock
private SdkChannelPool mockDelegatePool;
private Channel channel;
private CancellableAcquireChannelPool cancellableAcquireChannelPool;
@Before
public void setup() {
channel = new NioSocketChannel();
eventLoopGroup.register(channel);
eventExecutor = eventLoopGroup.next();
cancellableAcquireChannelPool = new CancellableAcquireChannelPool(eventExecutor, mockDelegatePool);
}
@After
public void methodTeardown() {
channel.close().awaitUninterruptibly();
}
@AfterClass
public static void teardown() {
eventLoopGroup.shutdownGracefully().awaitUninterruptibly();
}
@Test
public void promiseCancelledBeforeAcquireComplete_closesAndReleasesChannel() throws InterruptedException {
Promise<Channel> acquireFuture = eventExecutor.newPromise();
acquireFuture.setFailure(new RuntimeException("Changed my mind!"));
when(mockDelegatePool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> {
Promise p = invocationOnMock.getArgument(0, Promise.class);
p.setSuccess(channel);
return p;
});
cancellableAcquireChannelPool.acquire(acquireFuture);
Thread.sleep(500);
verify(mockDelegatePool).release(eq(channel));
assertThat(channel.closeFuture().isDone()).isTrue();
}
}
| 1,041 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/SharedSdkEventLoopGroupTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Java6Assertions.assertThat;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
public class SharedSdkEventLoopGroupTest {
@Test
public void referenceCountIsInitiallyZero() {
assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(0);
}
@Test
public void referenceCountIsIncrementedOnGet() {
SdkEventLoopGroup group = SharedSdkEventLoopGroup.get();
assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(1);
group.eventLoopGroup().shutdownGracefully();
}
@Test
public void referenceCountIsOnceDecrementedOnClose() {
SdkEventLoopGroup group = SharedSdkEventLoopGroup.get();
group.eventLoopGroup().shutdownGracefully();
assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(0);
group.eventLoopGroup().shutdownGracefully();
assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(0);
}
@Test
public void sharedEventLoopGroupIsDeallocatedWhenCountReachesZero() {
DelegatingEventLoopGroup group1 = (DelegatingEventLoopGroup) SharedSdkEventLoopGroup.get().eventLoopGroup();
DelegatingEventLoopGroup group2 = (DelegatingEventLoopGroup) SharedSdkEventLoopGroup.get().eventLoopGroup();
assertThat(group1.getDelegate()).isEqualTo(group2.getDelegate());
group1.shutdownGracefully();
group2.shutdownGracefully();
assertThat(group1.getDelegate().isShuttingDown()).isTrue();
}
}
| 1,042 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/FutureCancelHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.EXECUTION_ID_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.REQUEST_CONTEXT_KEY;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultChannelId;
import io.netty.channel.EventLoopGroup;
import io.netty.util.DefaultAttributeMap;
import java.io.IOException;
import java.util.concurrent.CancellationException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
/**
* Unit tests for {@link FutureCancelHandler}.
*/
@RunWith(MockitoJUnitRunner.class)
public class FutureCancelHandlerTest {
private FutureCancelHandler handler = FutureCancelHandler.getInstance();
@Mock
private ChannelHandlerContext ctx;
@Mock
private Channel channel;
@Mock
private SdkChannelPool channelPool;
private RequestContext requestContext;
@Mock
private SdkAsyncHttpResponseHandler responseHandler;
@Mock
private EventLoopGroup eventLoopGroup;
@Before
public void methodSetup() {
requestContext = new RequestContext(channelPool,
eventLoopGroup,
AsyncExecuteRequest.builder().responseHandler(responseHandler).build(),
null);
DefaultAttributeMap attrMap = new DefaultAttributeMap();
attrMap.attr(EXECUTION_ID_KEY).set(1L);
attrMap.attr(REQUEST_CONTEXT_KEY).set(requestContext);
when(ctx.channel()).thenReturn(channel);
when(channel.attr(EXECUTION_ID_KEY)).thenReturn(attrMap.attr(EXECUTION_ID_KEY));
when(channel.attr(REQUEST_CONTEXT_KEY)).thenReturn(attrMap.attr(REQUEST_CONTEXT_KEY));
when(channel.id()).thenReturn(DefaultChannelId.newInstance());
}
@Test
public void surfacesCancelExceptionAsIOException() {
FutureCancelledException cancelledException = new FutureCancelledException(1L, new CancellationException());
ArgumentCaptor<Throwable> exceptionCaptor = ArgumentCaptor.forClass(Throwable.class);
handler.exceptionCaught(ctx, cancelledException);
verify(ctx).fireExceptionCaught(exceptionCaptor.capture());
assertThat(exceptionCaptor.getValue()).isInstanceOf(IOException.class);
}
@Test
public void forwardsExceptionIfNotCancelledException() {
ArgumentCaptor<Throwable> exceptionCaptor = ArgumentCaptor.forClass(Throwable.class);
Throwable err = new RuntimeException("some other exception");
handler.exceptionCaught(ctx, err);
verify(ctx).fireExceptionCaught(exceptionCaptor.capture());
assertThat(exceptionCaptor.getValue()).isEqualTo(err);
}
@Test
public void cancelledException_executionIdNull_shouldIgnoreExceptionAndCloseChannel() {
when(channel.attr(EXECUTION_ID_KEY)).thenReturn(null);
FutureCancelledException cancelledException = new FutureCancelledException(1L, new CancellationException());
handler.exceptionCaught(ctx, cancelledException);
verify(ctx, never()).fireExceptionCaught(any(Throwable.class));
verify(ctx).close();
}
}
| 1,043 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/HandlerRemovingChannelPoolListenerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.IN_USE;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.REQUEST_CONTEXT_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_COMPLETE_KEY;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.nio.netty.internal.nrs.HttpStreamsClientHandler;
@RunWith(MockitoJUnitRunner.class)
public class HandlerRemovingChannelPoolListenerTest {
@Mock
private SdkChannelPool channelPool;
@Mock
private SdkAsyncHttpResponseHandler responseHandler;
private Channel mockChannel;
private ChannelPipeline pipeline;
private NioEventLoopGroup nioEventLoopGroup;
private HandlerRemovingChannelPoolListener handler;
@Before
public void setup() throws Exception {
mockChannel = new MockChannel();
pipeline = mockChannel.pipeline();
pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
nioEventLoopGroup = new NioEventLoopGroup();
nioEventLoopGroup.register(mockChannel);
RequestContext requestContext = new RequestContext(channelPool,
nioEventLoopGroup,
AsyncExecuteRequest.builder().responseHandler(responseHandler).build(),
null);
mockChannel.attr(IN_USE).set(true);
mockChannel.attr(REQUEST_CONTEXT_KEY).set(requestContext);
mockChannel.attr(RESPONSE_COMPLETE_KEY).set(true);
pipeline.addLast(new HttpStreamsClientHandler());
pipeline.addLast(ResponseHandler.getInstance());
pipeline.addLast(new ReadTimeoutHandler(10));
pipeline.addLast(new WriteTimeoutHandler(10));
handler = HandlerRemovingChannelPoolListener.create();
}
@After
public void tearDown() {
nioEventLoopGroup.shutdownGracefully();
}
@Test
public void release_openChannel_handlerShouldBeRemovedFromChannelPool() {
assertHandlersNotRemoved();
handler.channelReleased(mockChannel);
assertHandlersRemoved();
}
@Test
public void release_closedChannel_handlerShouldBeRemovedFromPipeline() {
mockChannel.close().awaitUninterruptibly();
// CLOSE -> INACTIVE -> UNREGISTERED: channel handlers should be removed at this point
assertHandlersRemoved();
handler.channelReleased(mockChannel);
assertHandlersRemoved();
}
@Test
public void release_deregisteredOpenChannel_handlerShouldBeRemovedFromChannelPool() {
mockChannel.deregister().awaitUninterruptibly();
assertHandlersNotRemoved();
handler.channelReleased(mockChannel);
assertHandlersRemoved();
}
private void assertHandlersRemoved() {
assertThat(pipeline.get(HttpStreamsClientHandler.class)).isNull();
assertThat(pipeline.get(ResponseHandler.class)).isNull();
assertThat(pipeline.get(ReadTimeoutHandler.class)).isNull();
assertThat(pipeline.get(WriteTimeoutHandler.class)).isNull();
}
private void assertHandlersNotRemoved() {
assertThat(pipeline.get(HttpStreamsClientHandler.class)).isNotNull();
assertThat(pipeline.get(ResponseHandler.class)).isNotNull();
assertThat(pipeline.get(ReadTimeoutHandler.class)).isNotNull();
assertThat(pipeline.get(WriteTimeoutHandler.class)).isNotNull();
}
}
| 1,044 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/HealthCheckedChannelPoolTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.KEEP_ALIVE;
import io.netty.channel.Channel;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.util.Attribute;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.ScheduledFuture;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.OngoingStubbing;
import software.amazon.awssdk.utils.AttributeMap;
public class HealthCheckedChannelPoolTest {
private EventLoopGroup eventLoopGroup = Mockito.mock(EventLoopGroup.class);
private EventLoop eventLoop = Mockito.mock(EventLoop.class);
private SdkChannelPool downstreamChannelPool = Mockito.mock(SdkChannelPool.class);
private List<Channel> channels = new ArrayList<>();
private ScheduledFuture<?> scheduledFuture = Mockito.mock(ScheduledFuture.class);
private Attribute<Boolean> attribute = mock(Attribute.class);
private static final NettyConfiguration NETTY_CONFIGURATION =
new NettyConfiguration(AttributeMap.builder()
.put(CONNECTION_ACQUIRE_TIMEOUT, Duration.ofMillis(10))
.build());
private HealthCheckedChannelPool channelPool = new HealthCheckedChannelPool(eventLoopGroup,
NETTY_CONFIGURATION,
downstreamChannelPool);
@BeforeEach
public void reset() {
Mockito.reset(eventLoopGroup, eventLoop, downstreamChannelPool, scheduledFuture, attribute);
channels.clear();
Mockito.when(eventLoopGroup.next()).thenReturn(eventLoop);
Mockito.when(eventLoop.newPromise())
.thenAnswer((Answer<Promise<Object>>) i -> new DefaultPromise<>(GlobalEventExecutor.INSTANCE));
}
@Test
public void acquireCanMakeJustOneCall() throws Exception {
stubForIgnoredTimeout();
stubAcquireHealthySequence(true);
Future<Channel> acquire = channelPool.acquire();
acquire.get(5, TimeUnit.SECONDS);
assertThat(acquire.isDone()).isTrue();
assertThat(acquire.isSuccess()).isTrue();
assertThat(acquire.getNow()).isEqualTo(channels.get(0));
Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any());
}
@Test
public void acquireCanMakeManyCalls() throws Exception {
stubForIgnoredTimeout();
stubAcquireHealthySequence(false, false, false, false, true);
Future<Channel> acquire = channelPool.acquire();
acquire.get(5, TimeUnit.SECONDS);
assertThat(acquire.isDone()).isTrue();
assertThat(acquire.isSuccess()).isTrue();
assertThat(acquire.getNow()).isEqualTo(channels.get(4));
Mockito.verify(downstreamChannelPool, Mockito.times(5)).acquire(any());
}
@Test
public void acquireActiveAndKeepAliveTrue_shouldAcquireOnce() throws Exception {
stubForIgnoredTimeout();
stubAcquireActiveAndKeepAlive();
Future<Channel> acquire = channelPool.acquire();
acquire.get(5, TimeUnit.SECONDS);
assertThat(acquire.isDone()).isTrue();
assertThat(acquire.isSuccess()).isTrue();
assertThat(acquire.getNow()).isEqualTo(channels.get(0));
Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any());
}
@Test
public void acquire_firstChannelKeepAliveFalse_shouldAcquireAnother() throws Exception {
stubForIgnoredTimeout();
stubAcquireTwiceFirstTimeNotKeepAlive();
Future<Channel> acquire = channelPool.acquire();
acquire.get(5, TimeUnit.SECONDS);
assertThat(acquire.isDone()).isTrue();
assertThat(acquire.isSuccess()).isTrue();
assertThat(acquire.getNow()).isEqualTo(channels.get(1));
Mockito.verify(downstreamChannelPool, Mockito.times(2)).acquire(any());
}
@Test
public void badDownstreamAcquiresCausesException() throws Exception {
stubForIgnoredTimeout();
stubBadDownstreamAcquire();
Future<Channel> acquire = channelPool.acquire();
try {
acquire.get(5, TimeUnit.SECONDS);
} catch (ExecutionException e) {
// Expected
}
assertThat(acquire.isDone()).isTrue();
assertThat(acquire.isSuccess()).isFalse();
assertThat(acquire.cause()).isInstanceOf(IOException.class);
Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any());
}
@Test
public void slowAcquireTimesOut() throws Exception {
stubIncompleteDownstreamAcquire();
Mockito.when(eventLoopGroup.schedule(Mockito.any(Runnable.class), Mockito.eq(10), Mockito.eq(TimeUnit.MILLISECONDS)))
.thenAnswer(i -> scheduledFuture);
Future<Channel> acquire = channelPool.acquire();
ArgumentCaptor<Runnable> timeoutTask = ArgumentCaptor.forClass(Runnable.class);
Mockito.verify(eventLoopGroup).schedule(timeoutTask.capture(), anyLong(), any());
timeoutTask.getValue().run();
try {
acquire.get(5, TimeUnit.SECONDS);
} catch (ExecutionException e) {
// Expected
}
assertThat(acquire.isDone()).isTrue();
assertThat(acquire.isSuccess()).isFalse();
assertThat(acquire.cause()).isInstanceOf(TimeoutException.class);
Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any());
}
@Test
public void releaseHealthyDoesNotClose() {
Channel channel = Mockito.mock(Channel.class);
Mockito.when(channel.isActive()).thenReturn(true);
stubKeepAliveAttribute(channel, null);
channelPool.release(channel);
Mockito.verify(channel, never()).close();
Mockito.verify(downstreamChannelPool, times(1)).release(channel);
}
@Test
public void releaseHealthyCloses() {
Channel channel = Mockito.mock(Channel.class);
Mockito.when(channel.isActive()).thenReturn(false);
stubKeepAliveAttribute(channel, null);
channelPool.release(channel);
Mockito.verify(channel, times(1)).close();
Mockito.verify(downstreamChannelPool, times(1)).release(channel);
}
public void stubAcquireHealthySequence(Boolean... acquireHealthySequence) {
OngoingStubbing<Future<Channel>> stubbing = Mockito.when(downstreamChannelPool.acquire(any()));
for (boolean shouldAcquireBeHealthy : acquireHealthySequence) {
stubbing = stubbing.thenAnswer(invocation -> {
Promise<Channel> promise = invocation.getArgument(0, Promise.class);
Channel channel = Mockito.mock(Channel.class);
Mockito.when(channel.isActive()).thenReturn(shouldAcquireBeHealthy);
stubKeepAliveAttribute(channel, null);
channels.add(channel);
promise.setSuccess(channel);
return promise;
});
}
}
private void stubAcquireActiveAndKeepAlive() {
OngoingStubbing<Future<Channel>> stubbing = Mockito.when(downstreamChannelPool.acquire(any()));
stubbing = stubbing.thenAnswer(invocation -> {
Promise<Channel> promise = invocation.getArgument(0, Promise.class);
Channel channel = Mockito.mock(Channel.class);
Mockito.when(channel.isActive()).thenReturn(true);
stubKeepAliveAttribute(channel, true);
channels.add(channel);
promise.setSuccess(channel);
return promise;
});
}
private void stubKeepAliveAttribute(Channel channel, Boolean isKeepAlive) {
Mockito.when(channel.attr(KEEP_ALIVE)).thenReturn(attribute);
when(attribute.get()).thenReturn(isKeepAlive);
}
public void stubBadDownstreamAcquire() {
Mockito.when(downstreamChannelPool.acquire(any())).thenAnswer(invocation -> {
Promise<Channel> promise = invocation.getArgument(0, Promise.class);
promise.setFailure(new IOException());
return promise;
});
}
public void stubIncompleteDownstreamAcquire() {
Mockito.when(downstreamChannelPool.acquire(any())).thenAnswer(invocation -> invocation.getArgument(0, Promise.class));
}
public void stubForIgnoredTimeout() {
Mockito.when(eventLoopGroup.schedule(any(Runnable.class), anyLong(), any()))
.thenAnswer(i -> scheduledFuture);
}
private void stubAcquireTwiceFirstTimeNotKeepAlive() {
OngoingStubbing<Future<Channel>> stubbing = Mockito.when(downstreamChannelPool.acquire(any()));
stubbing = stubbing.thenAnswer(invocation -> {
Promise<Channel> promise = invocation.getArgument(0, Promise.class);
Channel channel = Mockito.mock(Channel.class);
stubKeepAliveAttribute(channel, false);
Mockito.when(channel.isActive()).thenReturn(true);
channels.add(channel);
promise.setSuccess(channel);
return promise;
});
stubbing.thenAnswer(invocation -> {
Promise<Channel> promise = invocation.getArgument(0, Promise.class);
Channel channel = Mockito.mock(Channel.class);
Mockito.when(channel.isActive()).thenReturn(true);
channels.add(channel);
promise.setSuccess(channel);
stubKeepAliveAttribute(channel, true);
return promise;
});
}
} | 1,045 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/OldConnectionReaperHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import io.netty.channel.ChannelHandlerContext;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.internal.verification.Times;
public class OldConnectionReaperHandlerTest {
@Test
@SuppressWarnings("unchecked")
public void inUseChannelsAreFlaggedToBeClosed() throws Exception {
// Given
MockChannel channel = new MockChannel();
channel.attr(ChannelAttributeKey.IN_USE).set(true);
ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
Mockito.when(ctx.channel()).thenReturn(channel);
// When
new OldConnectionReaperHandler(1).handlerAdded(ctx);
channel.runAllPendingTasks();
// Then
Mockito.verify(ctx, new Times(0)).close();
Mockito.verify(ctx, new Times(0)).close(any());
assertThat(channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).get()).isTrue();
}
@Test
public void notInUseChannelsAreClosed() throws Exception {
// Given
MockChannel channel = new MockChannel();
channel.attr(ChannelAttributeKey.IN_USE).set(false);
ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
Mockito.when(ctx.channel()).thenReturn(channel);
// When
new OldConnectionReaperHandler(1).handlerAdded(ctx);
channel.runAllPendingTasks();
// Then
Mockito.verify(ctx, new Times(1)).close();
Mockito.verify(ctx, new Times(0)).close(any());
}
}
| 1,046 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/NettyRequestExecutorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.WRITE_TIMEOUT;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.IN_USE;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.DefaultChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.Promise;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.utils.AttributeMap;
public class NettyRequestExecutorTest {
private SdkChannelPool mockChannelPool;
private EventLoopGroup eventLoopGroup;
private NettyRequestExecutor nettyRequestExecutor;
private RequestContext requestContext;
@BeforeEach
public void setup() {
mockChannelPool = mock(SdkChannelPool.class);
eventLoopGroup = new NioEventLoopGroup();
AttributeMap attributeMap = AttributeMap.builder()
.put(WRITE_TIMEOUT, Duration.ofSeconds(3))
.build();
requestContext = new RequestContext(mockChannelPool,
eventLoopGroup,
AsyncExecuteRequest.builder().request(SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.host("amazonaws.com")
.protocol("https")
.build())
.build(),
new NettyConfiguration(attributeMap));
nettyRequestExecutor = new NettyRequestExecutor(requestContext);
}
@AfterEach
public void teardown() throws InterruptedException {
eventLoopGroup.shutdownGracefully().await();
}
@Test
public void cancelExecuteFuture_channelNotAcquired_failsAcquirePromise() {
ArgumentCaptor<Promise> acquireCaptor = ArgumentCaptor.forClass(Promise.class);
when(mockChannelPool.acquire(acquireCaptor.capture())).thenAnswer((Answer<Promise>) invocationOnMock -> {
return invocationOnMock.getArgument(0, Promise.class);
});
CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute();
executeFuture.cancel(true);
assertThat(acquireCaptor.getValue().isDone()).isTrue();
assertThat(acquireCaptor.getValue().isSuccess()).isFalse();
}
@Test
public void cancelExecuteFuture_channelAcquired_submitsRunnable() throws InterruptedException {
EventLoop mockEventLoop = mock(EventLoop.class);
Channel mockChannel = mock(Channel.class);
ChannelPipeline mockPipeline = mock(ChannelPipeline.class);
when(mockChannel.pipeline()).thenReturn(mockPipeline);
when(mockChannel.eventLoop()).thenReturn(mockEventLoop);
when(mockChannel.isActive()).thenReturn(true);
Attribute<Boolean> mockInUseAttr = mock(Attribute.class);
when(mockInUseAttr.get()).thenReturn(Boolean.TRUE);
CompletableFuture<Protocol> protocolFuture = CompletableFuture.completedFuture(Protocol.HTTP1_1);
Attribute<CompletableFuture<Protocol>> mockProtocolFutureAttr = mock(Attribute.class);
when(mockProtocolFutureAttr.get()).thenReturn(protocolFuture);
when(mockChannel.attr(any(AttributeKey.class))).thenAnswer(i -> {
AttributeKey argumentAt = i.getArgument(0, AttributeKey.class);
if (argumentAt == IN_USE) {
return mockInUseAttr;
}
if (argumentAt == PROTOCOL_FUTURE) {
return mockProtocolFutureAttr;
}
return mock(Attribute.class);
});
when(mockChannel.writeAndFlush(any(Object.class))).thenReturn(new DefaultChannelPromise(mockChannel));
ChannelConfig mockChannelConfig = mock(ChannelConfig.class);
when(mockChannel.config()).thenReturn(mockChannelConfig);
CountDownLatch submitLatch = new CountDownLatch(1);
when(mockEventLoop.submit(any(Runnable.class))).thenAnswer(i -> {
i.getArgument(0, Runnable.class).run();
// Need to wait until the first submit() happens which sets up the channel before cancelling the future.
submitLatch.countDown();
return null;
});
when(mockChannelPool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> {
Promise p = invocationOnMock.getArgument(0, Promise.class);
p.setSuccess(mockChannel);
return p;
});
CountDownLatch exceptionFiredLatch = new CountDownLatch(1);
when(mockPipeline.fireExceptionCaught(any(FutureCancelledException.class))).thenAnswer(i -> {
exceptionFiredLatch.countDown();
return mockPipeline;
});
CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute();
submitLatch.await(1, TimeUnit.SECONDS);
executeFuture.cancel(true);
exceptionFiredLatch.await(1, TimeUnit.SECONDS);
verify(mockEventLoop, times(2)).submit(any(Runnable.class));
}
}
| 1,047 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/SslCloseCompletionEventHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.IN_USE;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.ssl.SslCloseCompletionEvent;
import java.nio.channels.ClosedChannelException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class SslCloseCompletionEventHandlerTest {
private ChannelHandlerContext ctx;
private MockChannel channel;
@BeforeEach
public void setup() throws Exception {
ctx = mock(ChannelHandlerContext.class);
channel = new MockChannel();
when(ctx.channel()).thenReturn(channel);
}
@AfterEach
public void teardown() {
channel.close();
}
@Test
public void userEventTriggeredUnusedChannel_ClosesChannel() {
SslCloseCompletionEventHandler handler = SslCloseCompletionEventHandler.getInstance();
handler.userEventTriggered(ctx, new SslCloseCompletionEvent(new ClosedChannelException()));
verify(ctx).close();
}
@Test
public void userEventTriggered_StaticVariable_ClosesChannel() {
SslCloseCompletionEventHandler handler = SslCloseCompletionEventHandler.getInstance();
handler.userEventTriggered(ctx, SslCloseCompletionEvent.SUCCESS);
verify(ctx).close();
}
@Test
public void userEventTriggered_channelInUse_shouldForwardEvent() {
SslCloseCompletionEventHandler handler = SslCloseCompletionEventHandler.getInstance();
channel.attr(IN_USE).set(true);
SslCloseCompletionEvent event = new SslCloseCompletionEvent(new ClosedChannelException());
handler.userEventTriggered(ctx, event);
verify(ctx).fireUserEventTriggered(event);
}
}
| 1,048 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/StaticKeyManagerFactorySpiTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import java.util.Arrays;
import java.util.stream.IntStream;
import javax.net.ssl.KeyManager;
import org.junit.Test;
/**
* Tests for {@link StaticKeyManagerFactorySpi}.
*/
public class StaticKeyManagerFactorySpiTest {
@Test(expected = NullPointerException.class)
public void nullListInConstructor_throws() {
new StaticKeyManagerFactorySpi(null);
}
@Test
public void constructorCreatesArrayCopy() {
KeyManager[] keyManagers = IntStream.range(0,8)
.mapToObj(i -> mock(KeyManager.class))
.toArray(KeyManager[]::new);
KeyManager[] arg = Arrays.copyOf(keyManagers, keyManagers.length);
StaticKeyManagerFactorySpi spi = new StaticKeyManagerFactorySpi(arg);
for (int i = 0; i < keyManagers.length; ++i) {
arg[i] = null;
}
assertThat(spi.engineGetKeyManagers()).containsExactly(keyManagers);
}
@Test
public void engineGetKeyManagers_returnsProvidedList() {
KeyManager[] keyManagers = IntStream.range(0,8)
.mapToObj(i -> mock(KeyManager.class))
.toArray(KeyManager[]::new);
StaticKeyManagerFactorySpi spi = new StaticKeyManagerFactorySpi(keyManagers);
assertThat(spi.engineGetKeyManagers()).containsExactly(keyManagers);
}
@Test(expected = UnsupportedOperationException.class)
public void engineInit_storeAndPasswords_throws() {
StaticKeyManagerFactorySpi staticKeyManagerFactorySpi = new StaticKeyManagerFactorySpi(new KeyManager[0]);
staticKeyManagerFactorySpi.engineInit(null, null);
}
@Test(expected = UnsupportedOperationException.class)
public void engineInit_spec_throws() {
StaticKeyManagerFactorySpi staticKeyManagerFactorySpi = new StaticKeyManagerFactorySpi(new KeyManager[0]);
staticKeyManagerFactorySpi.engineInit(null);
}
}
| 1,049 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/UnusedChannelExceptionHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultChannelId;
import io.netty.util.Attribute;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import org.mockito.Mockito;
import org.mockito.internal.verification.Times;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class UnusedChannelExceptionHandlerTest {
private Throwable exception = new Throwable();
private IOException ioException = new IOException();
private ChannelHandlerContext ctx;
private Channel channel;
private Attribute<Boolean> inUseAttribute;
private Attribute<CompletableFuture<Void>> futureAttribute;
@BeforeMethod
@SuppressWarnings("unchecked")
public void setUp() {
ctx = Mockito.mock(ChannelHandlerContext.class);
channel = Mockito.mock(Channel.class);
Mockito.when(channel.id()).thenReturn(DefaultChannelId.newInstance());
inUseAttribute = Mockito.mock(Attribute.class);
futureAttribute = Mockito.mock(Attribute.class);
Mockito.when(ctx.channel()).thenReturn(channel);
Mockito.when(channel.attr(ChannelAttributeKey.IN_USE)).thenReturn(inUseAttribute);
Mockito.when(channel.attr(ChannelAttributeKey.EXECUTE_FUTURE_KEY)).thenReturn(futureAttribute);
}
@Test
public void inUseDoesNothing() {
Mockito.when(inUseAttribute.get()).thenReturn(true);
UnusedChannelExceptionHandler.getInstance().exceptionCaught(ctx, exception);
Mockito.verify(ctx).fireExceptionCaught(exception);
Mockito.verify(ctx, new Times(0)).close();
}
@Test
public void notInUseNonIoExceptionCloses() {
notInUseCloses(exception);
}
@Test
public void notInUseIoExceptionCloses() {
notInUseCloses(ioException);
}
@Test
public void notInUseHasIoExceptionCauseCloses() {
notInUseCloses(new RuntimeException(ioException));
}
private void notInUseCloses(Throwable exception) {
Mockito.when(inUseAttribute.get()).thenReturn(false);
Mockito.when(futureAttribute.get()).thenReturn(CompletableFuture.completedFuture(null));
UnusedChannelExceptionHandler.getInstance().exceptionCaught(ctx, exception);
Mockito.verify(ctx).close();
}
@Test
public void notInUseFutureCompletes() {
CompletableFuture<Void> incompleteFuture = new CompletableFuture<>();
Mockito.when(inUseAttribute.get()).thenReturn(false);
Mockito.when(futureAttribute.get()).thenReturn(incompleteFuture);
UnusedChannelExceptionHandler.getInstance().exceptionCaught(ctx, exception);
Mockito.verify(ctx).close();
assertThat(incompleteFuture.isDone()).isTrue();
}
}
| 1,050 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/OneTimeReadTimeoutHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import java.time.Duration;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class OneTimeReadTimeoutHandlerTest {
private static final long TIMEOUT_IN_MILLIS = 1000;
private static OneTimeReadTimeoutHandler handler;
@Mock
private ChannelHandlerContext context;
@Mock
private ChannelPipeline channelPipeline;
@Mock
private Object object;
@BeforeClass
public static void setup() {
handler = new OneTimeReadTimeoutHandler(Duration.ofMillis(TIMEOUT_IN_MILLIS));
}
@Test
public void channelRead_removesSelf() throws Exception {
when(context.pipeline()).thenReturn(channelPipeline);
handler.channelRead(context, object);
verify(channelPipeline, times(1)).remove(eq(handler));
verify(context, times(1)).fireChannelRead(object);
}
}
| 1,051 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/MockChannel.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.embedded.EmbeddedChannel;
public class MockChannel extends EmbeddedChannel {
public MockChannel() throws Exception {
super.doRegister();
}
public void runAllPendingTasks() throws InterruptedException {
super.runPendingTasks();
while (runScheduledPendingTasks() != -1) {
Thread.sleep(1);
}
}
}
| 1,052 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/PublisherAdapterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.EXECUTE_FUTURE_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.REQUEST_CONTEXT_KEY;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.EmptyByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.codec.http.DefaultHttpContent;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.reactivex.Flowable;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.nio.netty.internal.nrs.DefaultStreamedHttpResponse;
import software.amazon.awssdk.http.nio.netty.internal.nrs.StreamedHttpResponse;
@RunWith(MockitoJUnitRunner.class)
public class PublisherAdapterTest {
@Mock
private ChannelHandlerContext ctx;
private MockChannel channel;
@Mock
private SdkChannelPool channelPool;
@Mock
private EventLoopGroup eventLoopGroup;
@Mock
private SdkAsyncHttpResponseHandler responseHandler;
private HttpContent fullHttpResponse;
private RequestContext requestContext;
private CompletableFuture<Void> executeFuture;
private ResponseHandler nettyResponseHandler;
@Before
public void setUp() throws Exception {
executeFuture = new CompletableFuture<>();
fullHttpResponse = mock(DefaultHttpContent.class);
when(fullHttpResponse.content()).thenReturn(new EmptyByteBuf(ByteBufAllocator.DEFAULT));
requestContext = new RequestContext(channelPool,
eventLoopGroup,
AsyncExecuteRequest.builder()
.request(SdkHttpRequest.builder()
.uri(URI.create("https://localhost"))
.method(SdkHttpMethod.GET)
.build())
.responseHandler(responseHandler)
.build(),
null);
channel = new MockChannel();
channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1));
channel.attr(REQUEST_CONTEXT_KEY).set(requestContext);
channel.attr(EXECUTE_FUTURE_KEY).set(executeFuture);
when(ctx.channel()).thenReturn(channel);
nettyResponseHandler = ResponseHandler.getInstance();
DefaultHttpResponse defaultFullHttpResponse = mock(DefaultHttpResponse.class);
when(defaultFullHttpResponse.headers()).thenReturn(EmptyHttpHeaders.INSTANCE);
when(defaultFullHttpResponse.status()).thenReturn(HttpResponseStatus.CREATED);
when(defaultFullHttpResponse.protocolVersion()).thenReturn(HttpVersion.HTTP_1_1);
nettyResponseHandler.channelRead0(ctx, defaultFullHttpResponse);
}
@Test
public void successfulStreaming_shouldNotInvokeChannelRead() {
Flowable<HttpContent> testPublisher = Flowable.just(fullHttpResponse);
StreamedHttpResponse streamedHttpResponse = new DefaultStreamedHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.ACCEPTED,
testPublisher);
ResponseHandler.PublisherAdapter publisherAdapter = new ResponseHandler.PublisherAdapter(streamedHttpResponse,
ctx,
requestContext,
executeFuture
);
TestSubscriber subscriber = new TestSubscriber();
publisherAdapter.subscribe(subscriber);
verify(ctx, times(0)).read();
verify(ctx, times(0)).close();
assertThat(subscriber.isCompleted).isEqualTo(true);
verify(channelPool).release(channel);
executeFuture.join();
assertThat(executeFuture).isCompleted();
}
@Test
public void errorOccurred_shouldInvokeResponseHandler() {
RuntimeException exception = new RuntimeException("boom");
Flowable<HttpContent> testPublisher = Flowable.error(exception);
StreamedHttpResponse streamedHttpResponse = new DefaultStreamedHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.ACCEPTED,
testPublisher);
ResponseHandler.PublisherAdapter publisherAdapter = new ResponseHandler.PublisherAdapter(streamedHttpResponse,
ctx,
requestContext,
executeFuture
);
TestSubscriber subscriber = new TestSubscriber();
publisherAdapter.subscribe(subscriber);
verify(ctx, times(0)).read();
verify(ctx).close();
assertThat(subscriber.errorOccurred).isEqualTo(true);
verify(channelPool).release(channel);
assertThat(executeFuture).isCompletedExceptionally();
verify(responseHandler).onError(exception);
}
@Test
public void subscriptionCancelled_upstreamPublisherCallsOnNext_httpContentReleased() {
HttpContent firstContent = mock(HttpContent.class);
when(firstContent.content()).thenReturn(Unpooled.EMPTY_BUFFER);
HttpContent[] contentToIgnore = new HttpContent[8];
for (int i = 0; i < contentToIgnore.length; ++i) {
contentToIgnore[i] = mock(HttpContent.class);
}
Publisher<HttpContent> publisher = subscriber -> subscriber.onSubscribe(new Subscription() {
@Override
public void request(long l) {
// We ignore any cancel signal and just publish all the content
subscriber.onNext(firstContent);
for (int i = 0; i < l && i < contentToIgnore.length; ++i) {
subscriber.onNext(contentToIgnore[i]);
}
}
@Override
public void cancel() {
// no-op
}
});
DefaultStreamedHttpResponse streamedResponse = new DefaultStreamedHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK, publisher);
Subscriber<ByteBuffer> subscriber = new Subscriber<ByteBuffer>() {
private Subscription subscription;
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(ByteBuffer byteBuffer) {
subscription.cancel();
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
};
ResponseHandler.PublisherAdapter publisherAdapter = new ResponseHandler.PublisherAdapter(streamedResponse, ctx,
requestContext, executeFuture);
publisherAdapter.subscribe(subscriber);
// First one should be accessed as normal
verify(firstContent).content();
verify(firstContent).release();
for (int i = 0; i < contentToIgnore.length; ++i) {
verify(contentToIgnore[i]).release();
verifyNoMoreInteractions(contentToIgnore[i]);
}
}
@Test
public void contentLengthValidationFails_closesAndReleasesConnection() {
channel.attr(ChannelAttributeKey.RESPONSE_CONTENT_LENGTH).set(1L);
channel.attr(ChannelAttributeKey.RESPONSE_DATA_READ).set(0L);
Publisher<HttpContent> publisher = subscriber -> subscriber.onSubscribe(new Subscription() {
@Override
public void request(long l) {
subscriber.onComplete();
}
@Override
public void cancel() {
}
});
DefaultStreamedHttpResponse streamedResponse = new DefaultStreamedHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK, publisher);
Subscriber<ByteBuffer> subscriber = new Subscriber<ByteBuffer>() {
private Subscription subscription;
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(ByteBuffer byteBuffer) {
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
};
ResponseHandler.PublisherAdapter publisherAdapter = new ResponseHandler.PublisherAdapter(streamedResponse, ctx,
requestContext, executeFuture);
publisherAdapter.subscribe(subscriber);
verify(ctx).close();
verify(channelPool).release(channel);
}
static final class TestSubscriber implements Subscriber<ByteBuffer> {
private Subscription subscription;
private boolean isCompleted = false;
private boolean errorOccurred = false;
@Override
public void onSubscribe(Subscription s) {
this.subscription = s;
subscription.request(1);
}
@Override
public void onNext(ByteBuffer byteBuffer) {
subscription.request(1);
}
@Override
public void onError(Throwable t) {
errorOccurred = true;
}
@Override
public void onComplete() {
isCompleted = true;
}
}
}
| 1,053 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/BootstrapProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TCP_KEEPALIVE;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
import software.amazon.awssdk.utils.AttributeMap;
@RunWith(MockitoJUnitRunner.class)
public class BootstrapProviderTest {
private final BootstrapProvider bootstrapProvider =
new BootstrapProvider(SdkEventLoopGroup.builder().build(),
new NettyConfiguration(GLOBAL_HTTP_DEFAULTS),
new SdkChannelOptions());
// IMPORTANT: This unit test asserts that the bootstrap provider creates bootstraps using 'unresolved
// InetSocketAddress'. If this test is replaced or removed, perhaps due to a different implementation of
// SocketAddress, a different test must be created that ensures that the hostname will be resolved on every
// connection attempt and not cached between connection attempts.
@Test
public void createBootstrap_usesUnresolvedInetSocketAddress() {
Bootstrap bootstrap = bootstrapProvider.createBootstrap("some-awesome-service-1234.amazonaws.com", 443, false);
SocketAddress socketAddress = bootstrap.config().remoteAddress();
assertThat(socketAddress).isInstanceOf(InetSocketAddress.class);
InetSocketAddress inetSocketAddress = (InetSocketAddress)socketAddress;
assertThat(inetSocketAddress.isUnresolved()).isTrue();
}
@Test
public void createBootstrapNonBlockingDns_usesUnresolvedInetSocketAddress() {
Bootstrap bootstrap = bootstrapProvider.createBootstrap("some-awesome-service-1234.amazonaws.com", 443, true);
SocketAddress socketAddress = bootstrap.config().remoteAddress();
assertThat(socketAddress).isInstanceOf(InetSocketAddress.class);
InetSocketAddress inetSocketAddress = (InetSocketAddress)socketAddress;
assertThat(inetSocketAddress.isUnresolved()).isTrue();
}
@Test
public void createBootstrap_defaultConfiguration_tcpKeepAliveShouldBeFalse() {
Bootstrap bootstrap = bootstrapProvider.createBootstrap("some-awesome-service-1234.amazonaws.com", 443, false);
Boolean keepAlive = (Boolean) bootstrap.config().options().get(ChannelOption.SO_KEEPALIVE);
assertThat(keepAlive).isFalse();
}
@Test
public void createBootstrap_tcpKeepAliveTrue_shouldApply() {
NettyConfiguration nettyConfiguration =
new NettyConfiguration(AttributeMap.builder().put(TCP_KEEPALIVE, true)
.build().merge(GLOBAL_HTTP_DEFAULTS));
BootstrapProvider provider =
new BootstrapProvider(SdkEventLoopGroup.builder().build(),
nettyConfiguration,
new SdkChannelOptions());
Bootstrap bootstrap = provider.createBootstrap("some-awesome-service-1234.amazonaws.com", 443, false);
Boolean keepAlive = (Boolean) bootstrap.config().options().get(ChannelOption.SO_KEEPALIVE);
assertThat(keepAlive).isTrue();
}
} | 1,054 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/DnsResolverLoaderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.channel.epoll.EpollDatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.oio.OioDatagramChannel;
import io.netty.resolver.dns.DnsAddressResolverGroup;
import org.junit.jupiter.api.Test;
public class DnsResolverLoaderTest {
@Test
public void canResolveChannelFactory() {
assertThat(DnsResolverLoader.init(NioDatagramChannel::new)).isInstanceOf(DnsAddressResolverGroup.class);
assertThat(DnsResolverLoader.init(EpollDatagramChannel::new)).isInstanceOf(DnsAddressResolverGroup.class);
assertThat(DnsResolverLoader.init(OioDatagramChannel::new)).isInstanceOf(DnsAddressResolverGroup.class);
}
}
| 1,055 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/AwaitCloseChannelPoolMapTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import io.netty.channel.Channel;
import io.netty.channel.pool.ChannelPool;
import io.netty.handler.ssl.SslProvider;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Future;
import java.net.URI;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.TlsKeyManagersProvider;
import software.amazon.awssdk.http.nio.netty.ProxyConfiguration;
import software.amazon.awssdk.http.nio.netty.RecordingNetworkTrafficListener;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
import software.amazon.awssdk.utils.AttributeMap;
public class AwaitCloseChannelPoolMapTest {
private final RecordingNetworkTrafficListener recorder = new RecordingNetworkTrafficListener();
private AwaitCloseChannelPoolMap channelPoolMap;
@Rule
public WireMockRule mockProxy = new WireMockRule(wireMockConfig()
.dynamicPort()
.networkTrafficListener(recorder));
@After
public void methodTeardown() {
if (channelPoolMap != null) {
channelPoolMap.close();
}
channelPoolMap = null;
recorder.reset();
}
@Test
public void close_underlyingPoolsShouldBeClosed() {
channelPoolMap = AwaitCloseChannelPoolMap.builder()
.sdkChannelOptions(new SdkChannelOptions())
.sdkEventLoopGroup(SdkEventLoopGroup.builder().build())
.configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS))
.protocol(Protocol.HTTP1_1)
.maxStreams(100)
.sslProvider(SslProvider.OPENSSL)
.build();
int numberOfChannelPools = 5;
List<SimpleChannelPoolAwareChannelPool> channelPools = new ArrayList<>();
for (int i = 0; i < numberOfChannelPools; i++) {
channelPools.add(
channelPoolMap.get(URI.create("http://" + RandomStringUtils.randomAlphabetic(2) + i + "localhost:" + numberOfChannelPools)));
}
assertThat(channelPoolMap.pools().size()).isEqualTo(numberOfChannelPools);
channelPoolMap.close();
channelPools.forEach(channelPool -> {
assertThat(channelPool.underlyingSimpleChannelPool().closeFuture()).isDone();
assertThat(channelPool.underlyingSimpleChannelPool().closeFuture().join()).isTrue();
});
}
@Test
public void get_callsInjectedBootstrapProviderCorrectly() {
BootstrapProvider bootstrapProvider = Mockito.spy(
new BootstrapProvider(SdkEventLoopGroup.builder().build(),
new NettyConfiguration(GLOBAL_HTTP_DEFAULTS),
new SdkChannelOptions()));
URI targetUri = URI.create("https://some-awesome-service-1234.amazonaws.com:8080");
AwaitCloseChannelPoolMap.Builder builder =
AwaitCloseChannelPoolMap.builder()
.sdkChannelOptions(new SdkChannelOptions())
.sdkEventLoopGroup(SdkEventLoopGroup.builder().build())
.configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS))
.protocol(Protocol.HTTP1_1)
.maxStreams(100)
.sslProvider(SslProvider.OPENSSL);
channelPoolMap = new AwaitCloseChannelPoolMap(builder, null, bootstrapProvider);
channelPoolMap.get(targetUri);
verify(bootstrapProvider).createBootstrap("some-awesome-service-1234.amazonaws.com", 8080, null);
}
@Test
public void get_usingProxy_callsInjectedBootstrapProviderCorrectly() {
BootstrapProvider bootstrapProvider = Mockito.spy(
new BootstrapProvider(SdkEventLoopGroup.builder().build(),
new NettyConfiguration(GLOBAL_HTTP_DEFAULTS),
new SdkChannelOptions()));
URI targetUri = URI.create("https://some-awesome-service-1234.amazonaws.com:8080");
Map<URI, Boolean> shouldProxyCache = new HashMap<>();
shouldProxyCache.put(targetUri, true);
ProxyConfiguration proxyConfiguration =
ProxyConfiguration.builder()
.host("localhost")
.port(mockProxy.port())
.build();
AwaitCloseChannelPoolMap.Builder builder =
AwaitCloseChannelPoolMap.builder()
.proxyConfiguration(proxyConfiguration)
.sdkChannelOptions(new SdkChannelOptions())
.sdkEventLoopGroup(SdkEventLoopGroup.builder().build())
.configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS))
.protocol(Protocol.HTTP1_1)
.maxStreams(100)
.sslProvider(SslProvider.OPENSSL);
channelPoolMap = new AwaitCloseChannelPoolMap(builder, shouldProxyCache, bootstrapProvider);
channelPoolMap.get(targetUri);
verify(bootstrapProvider).createBootstrap("localhost", mockProxy.port(), null);
}
@Test
public void usingProxy_usesCachedValueWhenPresent() {
URI targetUri = URI.create("https://some-awesome-service-1234.amazonaws.com");
Map<URI, Boolean> shouldProxyCache = new HashMap<>();
shouldProxyCache.put(targetUri, true);
ProxyConfiguration proxyConfiguration = ProxyConfiguration.builder()
.host("localhost")
.port(mockProxy.port())
// Deliberately set the target host as a non-proxy host to
// see if it will check the cache first
.nonProxyHosts(Stream.of(targetUri.getHost()).collect(Collectors.toSet()))
.build();
AwaitCloseChannelPoolMap.Builder builder = AwaitCloseChannelPoolMap.builder()
.proxyConfiguration(proxyConfiguration)
.sdkChannelOptions(new SdkChannelOptions())
.sdkEventLoopGroup(SdkEventLoopGroup.builder().build())
.configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS))
.protocol(Protocol.HTTP1_1)
.maxStreams(100)
.sslProvider(SslProvider.OPENSSL);
channelPoolMap = new AwaitCloseChannelPoolMap(builder, shouldProxyCache, null);
// The target host does not exist so acquiring a channel should fail unless we're configured to connect to
// the mock proxy host for this URI.
SimpleChannelPoolAwareChannelPool channelPool = channelPoolMap.newPool(targetUri);
Future<Channel> channelFuture = channelPool.underlyingSimpleChannelPool().acquire().awaitUninterruptibly();
assertThat(channelFuture.isSuccess()).isTrue();
channelPool.release(channelFuture.getNow()).awaitUninterruptibly();
}
@Test
public void usingProxy_noSchemeGiven_defaultsToHttp() {
ProxyConfiguration proxyConfiguration = ProxyConfiguration.builder()
.host("localhost")
.port(mockProxy.port())
.build();
channelPoolMap = AwaitCloseChannelPoolMap.builder()
.proxyConfiguration(proxyConfiguration)
.sdkChannelOptions(new SdkChannelOptions())
.sdkEventLoopGroup(SdkEventLoopGroup.builder().build())
.configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS))
.protocol(Protocol.HTTP1_1)
.maxStreams(100)
.sslProvider(SslProvider.OPENSSL)
.build();
SimpleChannelPoolAwareChannelPool simpleChannelPoolAwareChannelPool = channelPoolMap.newPool(
URI.create("https://some-awesome-service:443"));
simpleChannelPoolAwareChannelPool.acquire().awaitUninterruptibly();
String requests = recorder.requests().toString();
assertThat(requests).contains("CONNECT some-awesome-service:443");
}
@Test
public void usingProxy_withAuth() {
ProxyConfiguration proxyConfiguration = ProxyConfiguration.builder()
.host("localhost")
.port(mockProxy.port())
.username("myuser")
.password("mypassword")
.build();
channelPoolMap = AwaitCloseChannelPoolMap.builder()
.proxyConfiguration(proxyConfiguration)
.sdkChannelOptions(new SdkChannelOptions())
.sdkEventLoopGroup(SdkEventLoopGroup.builder().build())
.configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS))
.protocol(Protocol.HTTP1_1)
.maxStreams(100)
.sslProvider(SslProvider.OPENSSL)
.build();
SimpleChannelPoolAwareChannelPool simpleChannelPoolAwareChannelPool = channelPoolMap.newPool(
URI.create("https://some-awesome-service:443"));
simpleChannelPoolAwareChannelPool.acquire().awaitUninterruptibly();
String requests = recorder.requests().toString();
assertThat(requests).contains("CONNECT some-awesome-service:443");
String authB64 = Base64.getEncoder().encodeToString("myuser:mypassword".getBytes(CharsetUtil.UTF_8));
String authHeaderValue = String.format("Basic %s", authB64);
assertThat(requests).contains(String.format("proxy-authorization: %s", authHeaderValue));
}
@Test
public void usesProvidedKeyManagersProvider() {
TlsKeyManagersProvider provider = mock(TlsKeyManagersProvider.class);
AttributeMap config = AttributeMap.builder()
.put(TLS_KEY_MANAGERS_PROVIDER, provider)
.build();
channelPoolMap = AwaitCloseChannelPoolMap.builder()
.sdkChannelOptions(new SdkChannelOptions())
.sdkEventLoopGroup(SdkEventLoopGroup.builder().build())
.protocol(Protocol.HTTP1_1)
.configuration(new NettyConfiguration(config.merge(GLOBAL_HTTP_DEFAULTS)))
.build();
ChannelPool channelPool = channelPoolMap.newPool(URI.create("https://localhost:" + mockProxy.port()));
channelPool.acquire().awaitUninterruptibly();
verify(provider).keyManagers();
}
@Test
public void acquireChannel_autoReadDisabled() {
channelPoolMap = AwaitCloseChannelPoolMap.builder()
.sdkChannelOptions(new SdkChannelOptions())
.sdkEventLoopGroup(SdkEventLoopGroup.builder().build())
.configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS))
.protocol(Protocol.HTTP1_1)
.maxStreams(100)
.sslProvider(SslProvider.OPENSSL)
.build();
ChannelPool channelPool = channelPoolMap.newPool(URI.create("https://localhost:" + mockProxy.port()));
Channel channel = channelPool.acquire().awaitUninterruptibly().getNow();
assertThat(channel.config().isAutoRead()).isFalse();
}
@Test
public void releaseChannel_autoReadEnabled() {
channelPoolMap = AwaitCloseChannelPoolMap.builder()
.sdkChannelOptions(new SdkChannelOptions())
.sdkEventLoopGroup(SdkEventLoopGroup.builder().build())
.configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS))
.protocol(Protocol.HTTP1_1)
.maxStreams(100)
.sslProvider(SslProvider.OPENSSL)
.build();
ChannelPool channelPool = channelPoolMap.newPool(URI.create("https://localhost:" + mockProxy.port()));
Channel channel = channelPool.acquire().awaitUninterruptibly().getNow();
channelPool.release(channel).awaitUninterruptibly();
assertThat(channel.config().isAutoRead()).isTrue();
}
}
| 1,056 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/HonorCloseOnReleaseChannelPoolTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.pool.ChannelPool;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.internal.verification.Times;
public class HonorCloseOnReleaseChannelPoolTest {
@Test
public void releaseDoesntCloseIfNotFlagged() throws Exception {
ChannelPool channelPool = Mockito.mock(ChannelPool.class);
MockChannel channel = new MockChannel();
channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).set(false);
new HonorCloseOnReleaseChannelPool(channelPool).release(channel);
channel.runAllPendingTasks();
assertThat(channel.isOpen()).isTrue();
Mockito.verify(channelPool, new Times(0)).release(any());
Mockito.verify(channelPool, new Times(1)).release(any(), any());
}
@Test
public void releaseClosesIfFlagged() throws Exception {
ChannelPool channelPool = Mockito.mock(ChannelPool.class);
MockChannel channel = new MockChannel();
channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).set(true);
new HonorCloseOnReleaseChannelPool(channelPool).release(channel);
channel.runAllPendingTasks();
assertThat(channel.isOpen()).isFalse();
Mockito.verify(channelPool, new Times(0)).release(any());
Mockito.verify(channelPool, new Times(1)).release(any(), any());
}
@Test
public void release_delegateReleaseFails_futureFailed() throws Exception {
NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
try {
ChannelPool mockDelegatePool = Mockito.mock(ChannelPool.class);
MockChannel channel = new MockChannel();
nioEventLoopGroup.register(channel);
HonorCloseOnReleaseChannelPool channelPool = new HonorCloseOnReleaseChannelPool(mockDelegatePool);
RuntimeException errorToThrow = new RuntimeException("failed!");
when(mockDelegatePool.release(any(Channel.class), any(Promise.class))).thenThrow(errorToThrow);
Promise<Void> promise = channel.eventLoop().newPromise();
Future<Void> releasePromise = channelPool.release(channel, promise);
try {
releasePromise.get(1, TimeUnit.SECONDS);
} catch (Exception e) {
if (e instanceof InterruptedException) {
throw e;
}
// ignore any other exception
}
assertThat(releasePromise.isSuccess()).isFalse();
assertThat(releasePromise.cause()).isSameAs(errorToThrow);
} finally {
nioEventLoopGroup.shutdownGracefully();
}
}
}
| 1,057 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/ResponseCompletionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE;
import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.reactivex.Flowable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
import software.amazon.awssdk.utils.AttributeMap;
public class ResponseCompletionTest {
private SdkAsyncHttpClient netty;
private Server server;
@AfterEach
public void teardown() throws InterruptedException {
if (server != null) {
server.shutdown();
}
server = null;
if (netty != null) {
netty.close();
}
netty = null;
}
@Test
public void connectionCloseAfterResponse_shouldNotReuseConnection() throws Exception {
server = new Server();
server.init();
netty = NettyNioAsyncHttpClient.builder()
.eventLoopGroup(SdkEventLoopGroup.builder().numberOfThreads(2).build())
.protocol(Protocol.HTTP1_1)
.buildWithDefaults(AttributeMap.builder().put(TRUST_ALL_CERTIFICATES, true).build());
sendGetRequest().join();
sendGetRequest().join();
assertThat(server.channels.size()).isEqualTo(2);
}
private CompletableFuture<Void> sendGetRequest() {
AsyncExecuteRequest req = AsyncExecuteRequest.builder()
.responseHandler(new SdkAsyncHttpResponseHandler() {
private SdkHttpResponse headers;
@Override
public void onHeaders(SdkHttpResponse headers) {
this.headers = headers;
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
Flowable.fromPublisher(stream).forEach(b -> {
});
}
@Override
public void onError(Throwable error) {
}
})
.request(SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("https")
.host("localhost")
.port(server.port())
.build())
.requestContentPublisher(new EmptyPublisher())
.build();
return netty.execute(req);
}
private static class Server extends ChannelInitializer<SocketChannel> {
private static final byte[] CONTENT = RandomStringUtils.randomAscii(7000).getBytes();
private ServerBootstrap bootstrap;
private ServerSocketChannel serverSock;
private List<SocketChannel> channels = new ArrayList<>();
private final NioEventLoopGroup group = new NioEventLoopGroup();
private SslContext sslCtx;
public void init() throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
bootstrap = new ServerBootstrap()
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.group(group)
.childHandler(this);
serverSock = (ServerSocketChannel) bootstrap.bind(0).sync().channel();
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
channels.add(ch);
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new AlwaysCloseConnectionChannelHandler());
}
public void shutdown() throws InterruptedException {
group.shutdownGracefully().await();
}
public int port() {
return serverSock.localAddress().getPort();
}
private static class AlwaysCloseConnectionChannelHandler extends ChannelDuplexHandler {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK,
Unpooled.wrappedBuffer(CONTENT));
response.headers()
.set(CONTENT_TYPE, TEXT_PLAIN)
.set(CONNECTION, CLOSE)
.setInt(CONTENT_LENGTH, response.content().readableBytes());
ctx.writeAndFlush(response).addListener(i -> ctx.channel().close());
}
}
}
}
}
| 1,058 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/SslContextProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import io.netty.handler.codec.http2.Http2SecurityUtil;
import io.netty.handler.ssl.SslProvider;
import javax.net.ssl.TrustManager;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.TlsKeyManagersProvider;
import software.amazon.awssdk.http.TlsTrustManagersProvider;
import software.amazon.awssdk.utils.AttributeMap;
public class SslContextProviderTest {
@Test
public void sslContext_h2WithJdk_h2CiphersShouldBeUsed() {
SslContextProvider sslContextProvider = new SslContextProvider(new NettyConfiguration(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS),
Protocol.HTTP2,
SslProvider.JDK);
assertThat(sslContextProvider.sslContext().cipherSuites()).isSubsetOf(Http2SecurityUtil.CIPHERS);
}
@Test
public void sslContext_h2WithOpenSsl_h2CiphersShouldBeUsed() {
SslContextProvider sslContextProvider = new SslContextProvider(new NettyConfiguration(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS),
Protocol.HTTP2,
SslProvider.OPENSSL);
assertThat(sslContextProvider.sslContext().cipherSuites()).isSubsetOf(Http2SecurityUtil.CIPHERS);
}
@Test
public void sslContext_h1_defaultCipherShouldBeUsed() {
SslContextProvider sslContextProvider = new SslContextProvider(new NettyConfiguration(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS),
Protocol.HTTP1_1,
SslProvider.JDK);
assertThat(sslContextProvider.sslContext().cipherSuites()).isNotIn(Http2SecurityUtil.CIPHERS);
}
@Test
public void customizedKeyManagerPresent_shouldUseCustomized() {
TlsKeyManagersProvider mockProvider = Mockito.mock(TlsKeyManagersProvider.class);
SslContextProvider sslContextProvider = new SslContextProvider(new NettyConfiguration(AttributeMap.builder()
.put(TRUST_ALL_CERTIFICATES, false)
.put(TLS_KEY_MANAGERS_PROVIDER, mockProvider)
.build()),
Protocol.HTTP1_1,
SslProvider.JDK);
sslContextProvider.sslContext();
Mockito.verify(mockProvider).keyManagers();
}
@Test
public void customizedTrustManagerPresent_shouldUseCustomized() {
TlsTrustManagersProvider mockProvider = Mockito.mock(TlsTrustManagersProvider.class);
TrustManager mockTrustManager = Mockito.mock(TrustManager.class);
Mockito.when(mockProvider.trustManagers()).thenReturn(new TrustManager[] {mockTrustManager});
SslContextProvider sslContextProvider = new SslContextProvider(new NettyConfiguration(AttributeMap.builder()
.put(TRUST_ALL_CERTIFICATES, false)
.put(TLS_TRUST_MANAGERS_PROVIDER, mockProvider)
.build()),
Protocol.HTTP1_1,
SslProvider.JDK);
sslContextProvider.sslContext();
Mockito.verify(mockProvider).trustManagers();
}
@Test
public void TlsTrustManagerAndTrustAllCertificates_shouldThrowException() {
TlsTrustManagersProvider mockProvider = Mockito.mock(TlsTrustManagersProvider.class);
assertThatThrownBy(() -> new SslContextProvider(new NettyConfiguration(AttributeMap.builder()
.put(TRUST_ALL_CERTIFICATES, true)
.put(TLS_TRUST_MANAGERS_PROVIDER,
mockProvider)
.build()),
Protocol.HTTP1_1,
SslProvider.JDK)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("A TlsTrustManagerProvider can't"
+ " be provided if "
+ "TrustAllCertificates is also "
+ "set");
}
}
| 1,059 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/InUseTrackingChannelPoolListenerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.IN_USE;
import io.netty.channel.Channel;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class InUseTrackingChannelPoolListenerTest {
Channel mockChannel;
InUseTrackingChannelPoolListener handler;
@BeforeEach
void setUp() throws Exception {
mockChannel = new MockChannel();
handler = InUseTrackingChannelPoolListener.create();
}
@Test
void channelAcquired() {
mockChannel.attr(IN_USE).set(false);
handler.channelAcquired(mockChannel);
assertThat(mockChannel.attr(IN_USE).get()).isTrue();
}
@Test
void channelReleased() {
mockChannel.attr(IN_USE).set(true);
handler.channelReleased(mockChannel);
assertThat(mockChannel.attr(IN_USE).get()).isFalse();
}
} | 1,060 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/FullResponseContentPublisherTckTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment;
import org.testng.annotations.BeforeMethod;
/**
* TCK verification test for {@link software.amazon.awssdk.http.nio.netty.internal.ResponseHandler.FullResponseContentPublisher}.
*/
public class FullResponseContentPublisherTckTest extends PublisherVerification<ByteBuffer> {
private static final byte[] CONTENT = new byte[16];
private CompletableFuture<Void> executeFuture;
private ChannelHandlerContext mockCtx = mock(ChannelHandlerContext.class);
@SuppressWarnings("unchecked")
@BeforeMethod
public void methodSetup() {
Channel chan = mock(Channel.class);
when(mockCtx.channel()).thenReturn(chan);
when(chan.attr(any(AttributeKey.class))).thenReturn(mock(Attribute.class));
executeFuture = new CompletableFuture<>();
}
public FullResponseContentPublisherTckTest() {
super(new TestEnvironment());
}
// This is a one-shot publisher
@Override
public long maxElementsFromPublisher() {
return 1;
}
@Override
public Publisher<ByteBuffer> createPublisher(long l) {
return new ResponseHandler.FullResponseContentPublisher(mockCtx, ByteBuffer.wrap(CONTENT), executeFuture);
}
@Override
public Publisher<ByteBuffer> createFailedPublisher() {
return null;
}
}
| 1,061 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/ConnectionReaperTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.Options;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import java.time.Duration;
import java.time.Instant;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.internal.verification.AtLeast;
import org.mockito.internal.verification.Times;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.ConnectionCountingTrafficListener;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.RecordingResponseHandler;
@RunWith(MockitoJUnitRunner.class)
public class ConnectionReaperTest {
private static final ConnectionCountingTrafficListener TRAFFIC_LISTENER = new ConnectionCountingTrafficListener();
@Rule
public final WireMockRule mockServer = new WireMockRule(wireMockConfig().dynamicPort()
.dynamicHttpsPort()
.networkTrafficListener(TRAFFIC_LISTENER));
@Test
public void idleConnectionReaperDoesNotReapActiveConnections() throws InterruptedException {
Duration maxIdleTime = Duration.ofSeconds(2);
try(SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder()
.connectionMaxIdleTime(maxIdleTime)
.buildWithDefaults(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)) {
Instant end = Instant.now().plus(maxIdleTime.plusSeconds(1));
// Send requests for longer than the max-idle time, ensuring no connections are closed.
int connectionCount = TRAFFIC_LISTENER.openedConnections();
while (Instant.now().isBefore(end)) {
makeRequest(client);
Thread.sleep(100);
}
assertThat(TRAFFIC_LISTENER.openedConnections()).isEqualTo(connectionCount + 1);
// Do nothing for longer than the max-idle time, ensuring connections are closed.
Thread.sleep(maxIdleTime.plusSeconds(1).toMillis());
makeRequest(client);
assertThat(TRAFFIC_LISTENER.openedConnections()).isEqualTo(connectionCount + 2);
}
}
@Test
public void oldConnectionReaperReapsActiveConnections() throws InterruptedException {
Duration connectionTtl = Duration.ofMillis(200);
try (SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder()
.connectionTimeToLive(connectionTtl)
.buildWithDefaults(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)) {
Instant end = Instant.now().plus(Duration.ofSeconds(5));
int connectionCount = TRAFFIC_LISTENER.openedConnections();
// Send requests frequently, validating that new connections are being opened.
while (Instant.now().isBefore(end)) {
makeRequest(client);
Thread.sleep(100);
}
assertThat(TRAFFIC_LISTENER.openedConnections()).isGreaterThanOrEqualTo(connectionCount + 15);
}
}
@Test
public void noReapingWorks() throws InterruptedException {
try (SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder()
.connectionMaxIdleTime(Duration.ofMillis(10))
.useIdleConnectionReaper(false)
.buildWithDefaults(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)) {
int connectionCount = TRAFFIC_LISTENER.openedConnections();
makeRequest(client);
Thread.sleep(2_000);
makeRequest(client);
assertThat(TRAFFIC_LISTENER.openedConnections()).isEqualTo(connectionCount + 1);
}
}
private void makeRequest(SdkAsyncHttpClient client) {
stubFor(WireMock.any(anyUrl()).willReturn(aResponse().withBody(randomAlphabetic(10))));
RecordingResponseHandler handler = new RecordingResponseHandler();
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())
.putHeader("Content-Length", "0")
.build())
.requestContentPublisher(new EmptyPublisher())
.responseHandler(handler)
.build())
.join();
assertThat(handler.fullResponseAsString()).hasSize(10);
}
}
| 1,062 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/ChannelDiagnosticsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.channel.embedded.EmbeddedChannel;
import java.time.Duration;
import org.junit.jupiter.api.Test;
public class ChannelDiagnosticsTest {
@Test
public void stopIdleTimer_noPreviousCallToStartIdleTimer_noDurationCalculated() {
ChannelDiagnostics cd = new ChannelDiagnostics(new EmbeddedChannel());
cd.stopIdleTimer();
assertThat(cd.lastIdleDuration()).isNull();
}
@Test
public void stopIdleTimer_previousCallToStartIdleTimer_durationCalculated() {
ChannelDiagnostics cd = new ChannelDiagnostics(new EmbeddedChannel());
cd.startIdleTimer();
cd.stopIdleTimer();
assertThat(cd.lastIdleDuration().toNanos()).isPositive();
}
@Test
public void incrementResponseCount_reflectsCorrectValue() {
ChannelDiagnostics cd = new ChannelDiagnostics(new EmbeddedChannel());
int count = 42;
for (int i = 0; i < count; ++i) {
cd.incrementResponseCount();
}
assertThat(cd.responseCount()).isEqualTo(count);
}
}
| 1,063 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/SdkChannelOptionsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import io.netty.channel.ChannelOption;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
public class SdkChannelOptionsTest {
@Test
public void defaultSdkSocketOptionPresent() {
SdkChannelOptions channelOptions = new SdkChannelOptions();
Map<ChannelOption, Object> expectedOptions = new HashMap<>();
expectedOptions.put(ChannelOption.TCP_NODELAY, Boolean.TRUE);
assertEquals(expectedOptions, channelOptions.channelOptions());
}
@Test
public void additionalSdkSocketOptionsPresent() {
SdkChannelOptions channelOptions = new SdkChannelOptions();
channelOptions.putOption(ChannelOption.SO_LINGER, 0);
Map<ChannelOption, Object> expectedOptions = new HashMap<>();
expectedOptions.put(ChannelOption.TCP_NODELAY, Boolean.TRUE);
expectedOptions.put(ChannelOption.SO_LINGER, 0);
assertEquals(expectedOptions, channelOptions.channelOptions());
}
}
| 1,064 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/LastHttpContentSwallowerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.LastHttpContent;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link LastHttpContentSwallower}.
*/
public class LastHttpContentSwallowerTest {
private final LastHttpContentSwallower lastHttpContentSwallower = LastHttpContentSwallower.getInstance();
private ChannelHandlerContext mockCtx;
private ChannelPipeline mockPipeline;
@BeforeEach
public void setUp() {
mockCtx = mock(ChannelHandlerContext.class);
mockPipeline = mock(ChannelPipeline.class);
when(mockCtx.pipeline()).thenReturn(mockPipeline);
}
@Test
public void testOtherHttpObjectRead_removesSelfFromPipeline() {
HttpObject contentObject = mock(HttpContent.class);
lastHttpContentSwallower.channelRead0(mockCtx, contentObject);
verify(mockPipeline).remove(eq(lastHttpContentSwallower));
}
@Test
public void testLastHttpContentRead_removesSelfFromPipeline() {
LastHttpContent lastContent = mock(LastHttpContent.class);
lastHttpContentSwallower.channelRead0(mockCtx, lastContent);
verify(mockPipeline).remove(eq(lastHttpContentSwallower));
}
@Test
public void testLastHttpContentRead_swallowsObject() {
LastHttpContent lastContent = mock(LastHttpContent.class);
lastHttpContentSwallower.channelRead0(mockCtx, lastContent);
verify(mockCtx, times(0)).fireChannelRead(eq(lastContent));
}
@Test
public void testOtherHttpObjectRead_doesNotSwallowObject() {
HttpContent content = mock(HttpContent.class);
lastHttpContentSwallower.channelRead0(mockCtx, content);
verify(mockCtx).fireChannelRead(eq(content));
}
@Test
public void testCallsReadAfterSwallowingContent() {
LastHttpContent lastContent = mock(LastHttpContent.class);
lastHttpContentSwallower.channelRead0(mockCtx, lastContent);
verify(mockCtx).read();
}
}
| 1,065 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/StaticKeyManagerFactoryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import java.util.stream.IntStream;
import javax.net.ssl.KeyManager;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link StaticKeyManagerFactory}.
*/
public class StaticKeyManagerFactoryTest {
@Test
public void createReturnFactoryWithCorrectKeyManagers() {
KeyManager[] keyManagers = IntStream.range(0,8)
.mapToObj(i -> mock(KeyManager.class))
.toArray(KeyManager[]::new);
StaticKeyManagerFactory staticKeyManagerFactory = StaticKeyManagerFactory.create(keyManagers);
assertThat(staticKeyManagerFactory.getKeyManagers())
.containsExactly(keyManagers);
}
}
| 1,066 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/ChannelPipelineInitializerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.pool.ChannelPool;
import io.netty.handler.codec.http2.Http2SecurityUtil;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
import io.netty.handler.ssl.SupportedCipherSuiteFilter;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.SSLException;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.Protocol;
public class ChannelPipelineInitializerTest {
private ChannelPipelineInitializer pipelineInitializer;
private URI targetUri;
@Test
public void channelConfigOptionCheck() throws SSLException {
targetUri = URI.create("https://some-awesome-service-1234.amazonaws.com:8080");
SslContext sslContext = SslContextBuilder.forClient()
.sslProvider(SslProvider.JDK)
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
.build();
AtomicReference<ChannelPool> channelPoolRef = new AtomicReference<>();
NettyConfiguration nettyConfiguration = new NettyConfiguration(GLOBAL_HTTP_DEFAULTS);
pipelineInitializer = new ChannelPipelineInitializer(Protocol.HTTP1_1,
sslContext,
SslProvider.JDK,
100,
1024,
Duration.ZERO,
channelPoolRef,
nettyConfiguration,
targetUri);
Channel channel = new EmbeddedChannel();
pipelineInitializer.channelCreated(channel);
assertThat(channel.config().getOption(ChannelOption.ALLOCATOR), is(UnpooledByteBufAllocator.DEFAULT));
}
} | 1,067 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/Http1TunnelConnectionPoolTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.nio.netty.internal.Http1TunnelConnectionPool.TUNNEL_ESTABLISHED_KEY;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.pool.ChannelPool;
import io.netty.channel.pool.ChannelPoolHandler;
import io.netty.handler.ssl.ApplicationProtocolNegotiator;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.Attribute;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSessionContext;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
/**
* Unit tests for {@link Http1TunnelConnectionPool}.
*/
@RunWith(MockitoJUnitRunner.class)
public class Http1TunnelConnectionPoolTest {
private static final NioEventLoopGroup GROUP = new NioEventLoopGroup(1);
private static final URI HTTP_PROXY_ADDRESS = URI.create("http://localhost:1234");
private static final URI HTTPS_PROXY_ADDRESS = URI.create("https://localhost:5678");
private static final URI REMOTE_ADDRESS = URI.create("https://s3.amazonaws.com:5678");
private static final String PROXY_USER = "myuser";
private static final String PROXY_PASSWORD = "mypassword";
@Mock
private ChannelPool delegatePool;
@Mock
private ChannelPoolHandler mockHandler;
@Mock
public Channel mockChannel;
@Mock
public ChannelPipeline mockPipeline;
@Mock
public Attribute mockAttr;
@Mock
public ChannelHandlerContext mockCtx;
@Mock
public ChannelId mockId;
public NettyConfiguration configuration;
@Before
public void methodSetup() {
Future<Channel> channelFuture = GROUP.next().newSucceededFuture(mockChannel);
when(delegatePool.acquire(any(Promise.class))).thenReturn(channelFuture);
when(mockChannel.attr(eq(TUNNEL_ESTABLISHED_KEY))).thenReturn(mockAttr);
when(mockChannel.id()).thenReturn(mockId);
when(mockChannel.pipeline()).thenReturn(mockPipeline);
configuration = new NettyConfiguration(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS);
}
@AfterClass
public static void teardown() {
GROUP.shutdownGracefully().awaitUninterruptibly();
}
@Test
public void tunnelAlreadyEstablished_doesNotAddInitHandler() {
Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null,
HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration);
when(mockAttr.get()).thenReturn(true);
tunnelPool.acquire().awaitUninterruptibly();
verify(mockPipeline, never()).addLast(any());
}
@Test(timeout = 1000)
public void tunnelNotEstablished_addsInitHandler() throws InterruptedException {
Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null,
HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration);
when(mockAttr.get()).thenReturn(false);
CountDownLatch latch = new CountDownLatch(1);
when(mockPipeline.addLast(any(ChannelHandler.class))).thenAnswer(i -> {
latch.countDown();
return mockPipeline;
});
tunnelPool.acquire();
latch.await();
verify(mockPipeline, times(1)).addLast(any(ProxyTunnelInitHandler.class));
}
@Test
public void tunnelInitFails_acquireFutureFails() {
Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> {
initFuture.setFailure(new IOException("boom"));
return mock(ChannelHandler.class);
};
Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null,
HTTP_PROXY_ADDRESS,null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration);
Future<Channel> acquireFuture = tunnelPool.acquire();
assertThat(acquireFuture.awaitUninterruptibly().cause()).hasMessage("boom");
}
@Test
public void tunnelInitSucceeds_acquireFutureSucceeds() {
Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> {
initFuture.setSuccess(mockChannel);
return mock(ChannelHandler.class);
};
Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null,
HTTP_PROXY_ADDRESS, null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration);
Future<Channel> acquireFuture = tunnelPool.acquire();
assertThat(acquireFuture.awaitUninterruptibly().getNow()).isEqualTo(mockChannel);
}
@Test
public void acquireFromDelegatePoolFails_failsFuture() {
Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null,
HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration);
when(delegatePool.acquire(any(Promise.class))).thenReturn(GROUP.next().newFailedFuture(new IOException("boom")));
Future<Channel> acquireFuture = tunnelPool.acquire();
assertThat(acquireFuture.awaitUninterruptibly().cause()).hasMessage("boom");
}
@Test
public void sslContextProvided_andProxyUsingHttps_addsSslHandler() {
SslHandler mockSslHandler = mock(SslHandler.class);
SSLEngine mockSslEngine = mock(SSLEngine.class);
when(mockSslHandler.engine()).thenReturn(mockSslEngine);
when(mockSslEngine.getSSLParameters()).thenReturn(mock(SSLParameters.class));
TestSslContext mockSslCtx = new TestSslContext(mockSslHandler);
Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> {
initFuture.setSuccess(mockChannel);
return mock(ChannelHandler.class);
};
Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx,
HTTPS_PROXY_ADDRESS, null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration);
tunnelPool.acquire().awaitUninterruptibly();
ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
verify(mockPipeline, times(2)).addLast(handlersCaptor.capture());
assertThat(handlersCaptor.getAllValues().get(0)).isEqualTo(mockSslHandler);
}
@Test
public void sslContextProvided_andProxyNotUsingHttps_doesNotAddSslHandler() {
SslHandler mockSslHandler = mock(SslHandler.class);
TestSslContext mockSslCtx = new TestSslContext(mockSslHandler);
Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> {
initFuture.setSuccess(mockChannel);
return mock(ChannelHandler.class);
};
Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx,
HTTP_PROXY_ADDRESS, null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration);
tunnelPool.acquire().awaitUninterruptibly();
ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
verify(mockPipeline).addLast(handlersCaptor.capture());
assertThat(handlersCaptor.getAllValues().get(0)).isNotInstanceOf(SslHandler.class);
}
@Test
public void release_releasedToDelegatePool() {
Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null,
HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration);
tunnelPool.release(mockChannel);
verify(delegatePool).release(eq(mockChannel), any(Promise.class));
}
@Test
public void release_withGivenPromise_releasedToDelegatePool() {
Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null,
HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration);
Promise mockPromise = mock(Promise.class);
tunnelPool.release(mockChannel, mockPromise);
verify(delegatePool).release(eq(mockChannel), eq(mockPromise));
}
@Test
public void close_closesDelegatePool() {
Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null,
HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration);
tunnelPool.close();
verify(delegatePool).close();
}
@Test
public void proxyAuthProvided_addInitHandler_withAuth(){
TestInitHandlerData data = new TestInitHandlerData();
Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> {
initFuture.setSuccess(mockChannel);
data.proxyUser(proxyUser);
data.proxyPassword(proxyPassword);
return mock(ChannelHandler.class);
};
Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null,
HTTP_PROXY_ADDRESS, PROXY_USER, PROXY_PASSWORD, REMOTE_ADDRESS, mockHandler, supplier, configuration);
tunnelPool.acquire().awaitUninterruptibly();
assertThat(data.proxyUser()).isEqualTo(PROXY_USER);
assertThat(data.proxyPassword()).isEqualTo(PROXY_PASSWORD);
}
private static class TestInitHandlerData {
private String proxyUser;
private String proxyPassword;
public void proxyUser(String proxyUser) {
this.proxyUser = proxyUser;
}
public String proxyUser() {
return this.proxyUser;
}
public void proxyPassword(String proxyPassword) {
this.proxyPassword = proxyPassword;
}
public String proxyPassword(){
return this.proxyPassword;
}
}
private static class TestSslContext extends SslContext {
private final SslHandler handler;
protected TestSslContext(SslHandler handler) {
this.handler = handler;
}
@Override
public boolean isClient() {
return false;
}
@Override
public List<String> cipherSuites() {
return null;
}
@Override
public long sessionCacheSize() {
return 0;
}
@Override
public long sessionTimeout() {
return 0;
}
@Override
public ApplicationProtocolNegotiator applicationProtocolNegotiator() {
return null;
}
@Override
public SSLEngine newEngine(ByteBufAllocator alloc) {
return null;
}
@Override
public SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) {
return null;
}
@Override
public SSLSessionContext sessionContext() {
return null;
}
@Override
public SslHandler newHandler(ByteBufAllocator alloc, String host, int port, boolean startTls) {
return handler;
}
}
}
| 1,068 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/RequestAdapterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.HttpConversionUtil;
import java.net.URI;
import java.util.List;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
public class RequestAdapterTest {
private final RequestAdapter h1Adapter = new RequestAdapter(Protocol.HTTP1_1);
private final RequestAdapter h2Adapter = new RequestAdapter(Protocol.HTTP2);
@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");
}
@Test
public void adapt_h2Request_addsSchemeExtension() {
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 = h2Adapter.adapt(request);
assertThat(adapted.headers().getAll(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text())).containsExactly("http");
}
@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");
}
@Test
public void adapt_hostHeaderSet() {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("http://localhost:12345/"))
.method(SdkHttpMethod.HEAD)
.build();
HttpRequest result = h1Adapter.adapt(sdkRequest);
List<String> hostHeaders = result.headers()
.getAll(HttpHeaderNames.HOST.toString());
assertThat(hostHeaders).containsExactly("localhost:12345");
}
@Test
public void adapt_standardHttpsPort_omittedInHeader() {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("https://localhost:443/"))
.method(SdkHttpMethod.HEAD)
.build();
HttpRequest result = h1Adapter.adapt(sdkRequest);
List<String> hostHeaders = result.headers()
.getAll(HttpHeaderNames.HOST.toString());
assertThat(hostHeaders).containsExactly("localhost");
}
@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");
}
@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("/");
}
@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));
}
@Test
public void adapt_nonStandardHttpPort() {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("http://localhost:8080/"))
.method(SdkHttpMethod.HEAD)
.build();
HttpRequest result = h1Adapter.adapt(sdkRequest);
List<String> hostHeaders = result.headers()
.getAll(HttpHeaderNames.HOST.toString());
assertThat(hostHeaders).containsExactly("localhost:8080");
}
@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");
}
}
| 1,069 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/IdleConnectionCountingChannelPoolTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import io.netty.channel.Channel;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.pool.ChannelPool;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.metrics.MetricCollector;
public class IdleConnectionCountingChannelPoolTest {
private EventLoopGroup eventLoopGroup;
private ChannelPool delegatePool;
private IdleConnectionCountingChannelPool idleCountingPool;
@Before
public void setup() {
delegatePool = mock(ChannelPool.class);
eventLoopGroup = new NioEventLoopGroup(4);
idleCountingPool = new IdleConnectionCountingChannelPool(eventLoopGroup.next(), delegatePool);
}
@After
public void teardown() {
eventLoopGroup.shutdownGracefully();
}
@Test(timeout = 5_000)
public void acquiresAndReleasesOfNewChannelsIncreaseCount() throws InterruptedException {
stubDelegatePoolAcquires(createSuccessfulAcquire(), createSuccessfulAcquire());
stubDelegatePoolReleasesForSuccess();
assertThat(getIdleConnectionCount()).isEqualTo(0);
Channel firstChannel = idleCountingPool.acquire().await().getNow();
assertThat(getIdleConnectionCount()).isEqualTo(0);
Channel secondChannel = idleCountingPool.acquire().await().getNow();
assertThat(getIdleConnectionCount()).isEqualTo(0);
idleCountingPool.release(firstChannel).await();
assertThat(getIdleConnectionCount()).isEqualTo(1);
idleCountingPool.release(secondChannel).await();
assertThat(getIdleConnectionCount()).isEqualTo(2);
}
@Test(timeout = 5_000)
public void channelsClosedInTheDelegatePoolAreNotCounted() throws InterruptedException {
stubDelegatePoolAcquires(createSuccessfulAcquire());
stubDelegatePoolReleasesForSuccess();
assertThat(getIdleConnectionCount()).isEqualTo(0);
Channel channel = idleCountingPool.acquire().await().getNow();
assertThat(getIdleConnectionCount()).isEqualTo(0);
idleCountingPool.release(channel).await();
assertThat(getIdleConnectionCount()).isEqualTo(1);
channel.close().await();
assertThat(getIdleConnectionCount()).isEqualTo(0);
}
@Test(timeout = 5_000)
public void channelsClosedWhenCheckedOutAreNotCounted() throws InterruptedException {
stubDelegatePoolAcquires(createSuccessfulAcquire());
stubDelegatePoolReleasesForSuccess();
assertThat(getIdleConnectionCount()).isEqualTo(0);
Channel channel = idleCountingPool.acquire().await().getNow();
assertThat(getIdleConnectionCount()).isEqualTo(0);
channel.close().await();
assertThat(getIdleConnectionCount()).isEqualTo(0);
idleCountingPool.release(channel).await();
assertThat(getIdleConnectionCount()).isEqualTo(0);
}
@Test
public void checkingOutAnIdleChannelIsCountedCorrectly() throws InterruptedException {
Future<Channel> successfulAcquire = createSuccessfulAcquire();
stubDelegatePoolAcquires(successfulAcquire, successfulAcquire);
stubDelegatePoolReleasesForSuccess();
assertThat(getIdleConnectionCount()).isEqualTo(0);
Channel channel1 = idleCountingPool.acquire().await().getNow();
assertThat(getIdleConnectionCount()).isEqualTo(0);
idleCountingPool.release(channel1).await();
assertThat(getIdleConnectionCount()).isEqualTo(1);
Channel channel2 = idleCountingPool.acquire().await().getNow();
assertThat(getIdleConnectionCount()).isEqualTo(0);
assertThat(channel1).isEqualTo(channel2);
}
@Test
public void stochastic_rapidAcquireReleaseIsCalculatedCorrectly() throws InterruptedException {
Future<Channel> successfulAcquire = createSuccessfulAcquire();
Channel expectedChannel = successfulAcquire.getNow();
stubDelegatePoolAcquires(successfulAcquire);
stubDelegatePoolReleasesForSuccess();
for (int i = 0; i < 1000; ++i) {
Channel channel = idleCountingPool.acquire().await().getNow();
assertThat(channel).isEqualTo(expectedChannel);
assertThat(getIdleConnectionCount()).isEqualTo(0);
idleCountingPool.release(channel).await();
assertThat(getIdleConnectionCount()).isEqualTo(1);
}
}
@Test
public void stochastic_rapidAcquireReleaseCloseIsCalculatedCorrectly() throws InterruptedException {
stubDelegatePoolAcquiresForSuccess();
stubDelegatePoolReleasesForSuccess();
for (int i = 0; i < 1000; ++i) {
Channel channel = idleCountingPool.acquire().await().getNow();
assertThat(getIdleConnectionCount()).isEqualTo(0);
idleCountingPool.release(channel).await();
assertThat(getIdleConnectionCount()).isEqualTo(1);
channel.close().await();
assertThat(getIdleConnectionCount()).isEqualTo(0);
}
}
@Test
public void stochastic_rapidAcquireCloseReleaseIsCalculatedCorrectly() throws InterruptedException {
stubDelegatePoolAcquiresForSuccess();
stubDelegatePoolReleasesForSuccess();
for (int i = 0; i < 1000; ++i) {
Channel channel = idleCountingPool.acquire().await().getNow();
assertThat(getIdleConnectionCount()).isEqualTo(0);
channel.close().await();
assertThat(getIdleConnectionCount()).isEqualTo(0);
idleCountingPool.release(channel).await();
assertThat(getIdleConnectionCount()).isEqualTo(0);
}
}
@Test
public void collectChannelPoolMetrics_failes_futureFailed() throws Exception {
MockChannel channel = new MockChannel();
eventLoopGroup.register(channel);
RuntimeException errorToThrow = new RuntimeException("failed!");
MetricCollector mockMetricCollector = mock(MetricCollector.class);
doThrow(errorToThrow).when(mockMetricCollector).reportMetric(any(), any());
CompletableFuture<Void> collectFuture = idleCountingPool.collectChannelPoolMetrics(mockMetricCollector);
assertThatThrownBy(() -> collectFuture.get(1, TimeUnit.SECONDS)).hasCause(errorToThrow);
}
private int getIdleConnectionCount() {
MetricCollector metricCollector = MetricCollector.create("test");
idleCountingPool.collectChannelPoolMetrics(metricCollector).join();
return metricCollector.collect().metricValues(HttpMetric.AVAILABLE_CONCURRENCY).get(0);
}
@SafeVarargs
private final void stubDelegatePoolAcquires(Future<Channel> result, Future<Channel>... extraResults) {
Mockito.when(delegatePool.acquire(any())).thenReturn(result, extraResults);
}
private void stubDelegatePoolAcquiresForSuccess() {
Mockito.when(delegatePool.acquire(any())).thenAnswer(a -> createSuccessfulAcquire());
}
private void stubDelegatePoolReleasesForSuccess() {
Mockito.when(delegatePool.release(any(Channel.class), any(Promise.class))).thenAnswer((Answer<Future<Void>>) invocation -> {
Promise<Void> promise = invocation.getArgument(1, Promise.class);
promise.setSuccess(null);
return promise;
});
}
private Future<Channel> createSuccessfulAcquire() {
try {
EventLoop eventLoop = this.eventLoopGroup.next();
Promise<Channel> channelPromise = eventLoop.newPromise();
MockChannel channel = new MockChannel();
eventLoop.register(channel);
channelPromise.setSuccess(channel);
return channelPromise;
} catch (Exception e) {
throw new Error(e);
}
}
} | 1,070 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/NettyUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.handler.timeout.WriteTimeoutException;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.time.Duration;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.SSLEngine;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.slf4j.Logger;
import software.amazon.awssdk.http.nio.netty.internal.MockChannel;
public class NettyUtilsTest {
private static EventLoopGroup eventLoopGroup;
@BeforeAll
public static void setup() {
eventLoopGroup = new NioEventLoopGroup(1);
}
@AfterAll
public static void teardown() throws InterruptedException {
eventLoopGroup.shutdownGracefully().await();
}
@Test
public void testGetOrCreateAttributeKey_calledTwiceWithSameName_returnsSameInstance() {
String attr = "NettyUtilsTest.Foo";
AttributeKey<String> fooAttr = NettyUtils.getOrCreateAttributeKey(attr);
assertThat(NettyUtils.getOrCreateAttributeKey(attr)).isSameAs(fooAttr);
}
@Test
public void newSslHandler_sslEngineShouldBeConfigured() throws Exception {
SslContext sslContext = SslContextBuilder.forClient().build();
Channel channel = null;
try {
channel = new MockChannel();
SslHandler sslHandler = NettyUtils.newSslHandler(sslContext, channel.alloc(), "localhost", 80,
Duration.ofMillis(1000));
assertThat(sslHandler.getHandshakeTimeoutMillis()).isEqualTo(1000);
SSLEngine engine = sslHandler.engine();
assertThat(engine.getSSLParameters().getEndpointIdentificationAlgorithm()).isEqualTo("HTTPS");
} finally {
if (channel != null) {
channel.close();
}
}
}
@Test
public void doInEventLoop_inEventLoop_doesNotSubmit() {
EventExecutor mockExecutor = mock(EventExecutor.class);
when(mockExecutor.inEventLoop()).thenReturn(true);
NettyUtils.doInEventLoop(mockExecutor, () -> {});
verify(mockExecutor, never()).submit(any(Runnable.class));
}
@Test
public void doInEventLoop_notInEventLoop_submits() {
EventExecutor mockExecutor = mock(EventExecutor.class);
when(mockExecutor.inEventLoop()).thenReturn(false);
NettyUtils.doInEventLoop(mockExecutor, () -> {});
verify(mockExecutor).submit(any(Runnable.class));
}
@Test
public void runOrPropagate_success_runs() throws Exception {
Promise<String> destination = eventLoopGroup.next().newPromise();
AtomicBoolean reference = new AtomicBoolean();
GenericFutureListener<Future<Void>> listener =
NettyUtils.runOrPropagate(destination, () -> reference.set(true));
Promise<Void> source = eventLoopGroup.next().newPromise();
source.setSuccess(null);
listener.operationComplete(source);
assertThat(reference.get()).isTrue();
}
@Test
public void runOrPropagate_exception_propagates() throws Exception {
Promise<String> destination = eventLoopGroup.next().newPromise();
GenericFutureListener<Future<Void>> listener =
NettyUtils.runOrPropagate(destination, () -> {
});
Promise<Void> source = eventLoopGroup.next().newPromise();
source.setFailure(new RuntimeException("Intentional exception for testing purposes"));
listener.operationComplete(source);
assertThat(destination.cause())
.isInstanceOf(RuntimeException.class)
.hasMessage("Intentional exception for testing purposes");
}
@Test
public void runOrPropagate_cancel_propagates() throws Exception {
Promise<String> destination = eventLoopGroup.next().newPromise();
GenericFutureListener<Future<Void>> listener =
NettyUtils.runOrPropagate(destination, () -> {
});
Promise<Void> source = eventLoopGroup.next().newPromise();
source.cancel(false);
listener.operationComplete(source);
assertThat(destination.isCancelled()).isTrue();
}
@Test
public void consumeOrPropagate_success_consumes() throws Exception {
Promise<String> destination = eventLoopGroup.next().newPromise();
AtomicReference<String> reference = new AtomicReference<>();
GenericFutureListener<Future<String>> listener =
NettyUtils.consumeOrPropagate(destination, reference::set);
Promise<String> source = eventLoopGroup.next().newPromise();
source.setSuccess("test");
listener.operationComplete(source);
assertThat(reference.get()).isEqualTo("test");
}
@Test
public void consumeOrPropagate_exception_propagates() throws Exception {
Promise<String> destination = eventLoopGroup.next().newPromise();
GenericFutureListener<Future<String>> listener =
NettyUtils.consumeOrPropagate(destination, s -> {
});
Promise<String> source = eventLoopGroup.next().newPromise();
source.setFailure(new RuntimeException("Intentional exception for testing purposes"));
listener.operationComplete(source);
assertThat(destination.cause())
.isInstanceOf(RuntimeException.class)
.hasMessage("Intentional exception for testing purposes");
}
@Test
public void consumeOrPropagate_cancel_propagates() throws Exception {
Promise<String> destination = eventLoopGroup.next().newPromise();
GenericFutureListener<Future<String>> listener =
NettyUtils.consumeOrPropagate(destination, s -> {
});
Promise<String> source = eventLoopGroup.next().newPromise();
source.cancel(false);
listener.operationComplete(source);
assertThat(destination.isCancelled()).isTrue();
}
@Test
public void runAndLogError_runnableDoesNotThrow_loggerNotInvoked() {
Logger delegateLogger = mock(Logger.class);
NettyClientLogger logger = new NettyClientLogger(delegateLogger);
NettyUtils.runAndLogError(logger, "Something went wrong", () -> {});
verifyNoMoreInteractions(delegateLogger);
}
@Test
public void runAndLogError_runnableThrows_loggerInvoked() {
Logger delegateLogger = mock(Logger.class);
when(delegateLogger.isErrorEnabled()).thenReturn(true);
NettyClientLogger logger = new NettyClientLogger(delegateLogger);
String msg = "Something went wrong";
RuntimeException error = new RuntimeException("Boom!");
NettyUtils.runAndLogError(logger, msg, () -> {
throw error;
});
verify(delegateLogger).error(msg, error);
}
@Test
public void closedChannelMessage_with_nullChannelAttribute() throws Exception {
Channel channel = Mockito.mock(Channel.class);
when(channel.parent()).thenReturn(null);
assertThat(NettyUtils.closedChannelMessage(channel))
.isEqualTo(NettyUtils.CLOSED_CHANNEL_ERROR_MESSAGE);
}
@Test
public void closedChannelMessage_with_nullChannel() throws Exception {
Channel channel = null;
assertThat(NettyUtils.closedChannelMessage(channel))
.isEqualTo(NettyUtils.CLOSED_CHANNEL_ERROR_MESSAGE);
}
@Test
public void closedChannelMessage_with_nullParentChannel() throws Exception {
Channel channel = mock(Channel.class);
Attribute attribute = mock(Attribute.class);
when(channel.parent()).thenReturn(null);
when(channel.attr(any())).thenReturn(attribute);
assertThat(NettyUtils.closedChannelMessage(channel))
.isEqualTo(NettyUtils.CLOSED_CHANNEL_ERROR_MESSAGE);
}
@Test
public void closedChannelMessage_with_nullParentChannelAttribute() throws Exception {
Channel channel = mock(Channel.class);
Attribute attribute = mock(Attribute.class);
Channel parentChannel = mock(Channel.class);
when(channel.parent()).thenReturn(parentChannel);
when(channel.attr(any())).thenReturn(attribute);
when(parentChannel.attr(any())).thenReturn(null);
assertThat(NettyUtils.closedChannelMessage(channel))
.isEqualTo(NettyUtils.CLOSED_CHANNEL_ERROR_MESSAGE);
}
@Test
public void decorateException_with_TimeoutException() {
Channel channel = mock(Channel.class);
Throwable timeoutException = new TimeoutException("...Acquire operation took longer...");
Throwable output = NettyUtils.decorateException(channel, timeoutException);
assertThat(output).isInstanceOf(Throwable.class);
assertThat(output.getCause()).isInstanceOf(TimeoutException.class);
assertThat(output.getMessage()).isNotNull();
}
@Test
public void decorateException_with_TimeoutException_noMsg() {
Channel channel = mock(Channel.class);
Throwable timeoutException = new TimeoutException();
Throwable output = NettyUtils.decorateException(channel, timeoutException);
assertThat(output).isInstanceOf(TimeoutException.class);
assertThat(output.getCause()).isNull();
}
@Test
public void decorateException_with_IllegalStateException() {
Channel channel = mock(Channel.class);
Throwable illegalStateException = new IllegalStateException("...Too many outstanding acquire operations...");
Throwable output = NettyUtils.decorateException(channel, illegalStateException);
assertThat(output).isInstanceOf(Throwable.class);
assertThat(output.getCause()).isInstanceOf(IllegalStateException.class);
assertThat(output.getMessage()).isNotNull();
}
@Test
public void decorateException_with_IllegalStateException_noMsg() {
Channel channel = mock(Channel.class);
Throwable illegalStateException = new IllegalStateException();
Throwable output = NettyUtils.decorateException(channel, illegalStateException);
assertThat(output).isInstanceOf(IllegalStateException.class);
assertThat(output.getCause()).isNull();
}
@Test
public void decorateException_with_ReadTimeoutException() {
Channel channel = mock(Channel.class);
Throwable readTimeoutException = new ReadTimeoutException();
Throwable output = NettyUtils.decorateException(channel, readTimeoutException);
assertThat(output).isInstanceOf(IOException.class);
assertThat(output.getCause()).isInstanceOf(ReadTimeoutException.class);
assertThat(output.getMessage()).isNotNull();
}
@Test
public void decorateException_with_WriteTimeoutException() {
Channel channel = mock(Channel.class);
Throwable writeTimeoutException = new WriteTimeoutException();
Throwable output = NettyUtils.decorateException(channel, writeTimeoutException);
assertThat(output).isInstanceOf(IOException.class);
assertThat(output.getCause()).isInstanceOf(WriteTimeoutException.class);
assertThat(output.getMessage()).isNotNull();
}
@Test
public void decorateException_with_ClosedChannelException() {
Channel channel = mock(Channel.class);
Throwable closedChannelException = new ClosedChannelException();
Throwable output = NettyUtils.decorateException(channel, closedChannelException);
assertThat(output).isInstanceOf(IOException.class);
assertThat(output.getCause()).isInstanceOf(ClosedChannelException.class);
assertThat(output.getMessage()).isNotNull();
}
@Test
public void decorateException_with_IOException_reset() {
Channel channel = mock(Channel.class);
Throwable closedChannelException = new IOException("...Connection reset by peer...");
Throwable output = NettyUtils.decorateException(channel, closedChannelException);
assertThat(output).isInstanceOf(IOException.class);
assertThat(output.getCause()).isInstanceOf(IOException.class);
assertThat(output.getMessage()).isNotNull();
}
@Test
public void decorateException_with_IOException_noMsg() {
Channel channel = mock(Channel.class);
Throwable closedChannelException = new IOException();
Throwable output = NettyUtils.decorateException(channel, closedChannelException);
assertThat(output).isInstanceOf(IOException.class);
assertThat(output.getCause()).isNull();
}
}
| 1,071 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/ChannelUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_MULTIPLEXED_CHANNEL_POOL;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.MAX_CONCURRENT_STREAMS;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.nio.netty.internal.MockChannel;
public class ChannelUtilsTest {
@Test
public void testGetAttributes() throws Exception {
MockChannel channel = null;
try {
channel = new MockChannel();
channel.attr(MAX_CONCURRENT_STREAMS).set(1L);
assertThat(ChannelUtils.getAttribute(channel, MAX_CONCURRENT_STREAMS).get()).isEqualTo(1L);
assertThat(ChannelUtils.getAttribute(channel, HTTP2_MULTIPLEXED_CHANNEL_POOL)).isNotPresent();
} finally {
Optional.ofNullable(channel).ifPresent(Channel::close);
}
}
@Test
public void removeIfExists() throws Exception {
MockChannel channel = null;
try {
channel = new MockChannel();
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new ReadTimeoutHandler(1));
pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
ChannelUtils.removeIfExists(pipeline, ReadTimeoutHandler.class, LoggingHandler.class);
assertThat(pipeline.get(ReadTimeoutHandler.class)).isNull();
assertThat(pipeline.get(LoggingHandler.class)).isNull();
} finally {
Optional.ofNullable(channel).ifPresent(Channel::close);
}
}
}
| 1,072 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/ExceptionHandlingUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.utils;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.function.Consumer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ExceptionHandlingUtilsTest {
@Mock
private Consumer<Throwable> errorNotifier;
@Mock
private Runnable cleanupExecutor;
@Test
public void tryCatch() {
ExceptionHandlingUtils.tryCatch(() -> {
},
errorNotifier);
verify(errorNotifier, times(0)).accept(any(Throwable.class));
}
@Test
public void tryCatchExceptionThrows() {
ExceptionHandlingUtils.tryCatch(() -> {
throw new RuntimeException("helloworld");
},
errorNotifier);
verify(errorNotifier).accept(any(Throwable.class));
}
@Test
public void tryCatchFinallyException() {
ExceptionHandlingUtils.tryCatchFinally(() -> "blah",
errorNotifier,
cleanupExecutor
);
verify(errorNotifier, times(0)).accept(any(Throwable.class));
verify(cleanupExecutor).run();
}
@Test
public void tryCatchFinallyExceptionThrows() {
ExceptionHandlingUtils.tryCatchFinally(() -> {
throw new RuntimeException("helloworld");
},
errorNotifier,
cleanupExecutor
);
verify(errorNotifier).accept(any(Throwable.class));
verify(cleanupExecutor).run();
}
}
| 1,073 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/ChannelResolverTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.nio.netty.internal.utils.ChannelResolver.resolveDatagramChannelFactory;
import static software.amazon.awssdk.http.nio.netty.internal.utils.ChannelResolver.resolveSocketChannelFactory;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollDatagramChannel;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.channel.socket.oio.OioDatagramChannel;
import io.netty.channel.socket.oio.OioSocketChannel;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.nio.netty.internal.DelegatingEventLoopGroup;
public class ChannelResolverTest {
@Test
public void canDetectFactoryForStandardNioEventLoopGroup() {
assertThat(resolveSocketChannelFactory(new NioEventLoopGroup()).newChannel()).isInstanceOf(NioSocketChannel.class);
assertThat(resolveDatagramChannelFactory(new NioEventLoopGroup()).newChannel()).isInstanceOf(NioDatagramChannel.class);
}
@Test
public void canDetectEpollEventLoopGroupFactory() {
Assumptions.assumeTrue(Epoll.isAvailable());
assertThat(resolveSocketChannelFactory(new EpollEventLoopGroup()).newChannel()).isInstanceOf(EpollSocketChannel.class);
assertThat(resolveDatagramChannelFactory(new EpollEventLoopGroup()).newChannel()).isInstanceOf(EpollDatagramChannel.class);
}
@Test
public void worksWithDelegateEventLoopGroupsFactory() {
assertThat(resolveSocketChannelFactory(new DelegatingEventLoopGroup(new NioEventLoopGroup()) {}).newChannel()).isInstanceOf(NioSocketChannel.class);
assertThat(resolveDatagramChannelFactory(new DelegatingEventLoopGroup(new NioEventLoopGroup()) {}).newChannel()).isInstanceOf(NioDatagramChannel.class);
}
@Test
public void worksWithOioEventLoopGroupFactory() {
assertThat(resolveSocketChannelFactory(new OioEventLoopGroup()).newChannel()).isInstanceOf(OioSocketChannel.class);
assertThat(resolveDatagramChannelFactory(new OioEventLoopGroup()).newChannel()).isInstanceOf(OioDatagramChannel.class);
}
}
| 1,074 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/NettyClientLoggerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.utils;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.DefaultChannelId;
import io.netty.channel.embedded.EmbeddedChannel;
import java.util.function.Supplier;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.Logger;
@RunWith(MockitoJUnitRunner.class)
public class NettyClientLoggerTest {
private static final String TEST_MSG = "test";
private static final ChannelId CHANNEL_ID = DefaultChannelId.newInstance();
private static final String CHANNEL_TO_STRING = "NettyClientLoggerTest_TestChannel";
private static final String EXPECTED_MESSAGE_SHORT = String.format("[Channel: %s] %s",
CHANNEL_ID.asShortText(),
TEST_MSG);
private static final String EXPECTED_MESSAGE_FULL = String.format("[Channel: %s] %s",
CHANNEL_TO_STRING,
TEST_MSG);
@Mock
public Logger delegateLogger;
@Mock
public Supplier<String> msgSupplier;
private NettyClientLogger logger;
private EmbeddedChannel ch;
@BeforeClass
public static void setup() throws InterruptedException {
}
@Before
public void methodSetup() {
when(msgSupplier.get()).thenReturn(TEST_MSG);
logger = new NettyClientLogger(delegateLogger);
ch = spy(new EmbeddedChannel(CHANNEL_ID));
when(ch.toString()).thenReturn(CHANNEL_TO_STRING);
}
@After
public void methodTeardown() throws InterruptedException {
ch.close().await();
}
@Test
public void debugNotEnabled_doesNotInvokeLogger() {
when(delegateLogger.isDebugEnabled()).thenReturn(false);
Channel channel = mock(Channel.class);
logger.debug(channel, msgSupplier, null);
verify(delegateLogger, never()).debug(anyString(), any(Throwable.class));
verifyNoMoreInteractions(msgSupplier);
verifyNoMoreInteractions(channel);
}
@Test
public void debugEnabled_invokesLogger() {
when(delegateLogger.isDebugEnabled()).thenReturn(true);
RuntimeException exception = new RuntimeException("boom!");
logger.debug(ch, msgSupplier, exception);
verify(delegateLogger).debug(EXPECTED_MESSAGE_FULL, exception);
}
@Test
public void debugNotEnabled_channelNotProvided_doesNotInvokeLogger() {
when(delegateLogger.isDebugEnabled()).thenReturn(false);
logger.debug(null, msgSupplier, null);
verify(delegateLogger, never()).debug(anyString(), any(Throwable.class));
verifyNoMoreInteractions(msgSupplier);
}
@Test
public void debugEnabled_channelNotProvided_invokesLogger() {
when(delegateLogger.isDebugEnabled()).thenReturn(true);
RuntimeException exception = new RuntimeException("boom!");
logger.debug(null, msgSupplier, exception);
verify(delegateLogger).debug(TEST_MSG, exception);
}
@Test
public void warnNotEnabled_doesNotInvokeLogger() {
when(delegateLogger.isWarnEnabled()).thenReturn(false);
Channel channel = mock(Channel.class);
logger.warn(channel, msgSupplier, null);
verify(delegateLogger, never()).warn(anyString(), any(Throwable.class));
verifyNoMoreInteractions(msgSupplier);
verifyNoMoreInteractions(channel);
}
@Test
public void warnEnabled_invokesLogger() {
when(delegateLogger.isWarnEnabled()).thenReturn(true);
RuntimeException exception = new RuntimeException("boom!");
logger.warn(ch, msgSupplier, exception);
verify(delegateLogger).warn(EXPECTED_MESSAGE_SHORT, exception);
}
@Test
public void warnEnabled_debugEnabled_invokesLogger() {
when(delegateLogger.isWarnEnabled()).thenReturn(true);
when(delegateLogger.isDebugEnabled()).thenReturn(true);
RuntimeException exception = new RuntimeException("boom!");
logger.warn(ch, msgSupplier, exception);
verify(delegateLogger).warn(EXPECTED_MESSAGE_FULL, exception);
}
@Test
public void errorNotEnabled_noChannelProvided_doesNotInvokeLogger() {
when(delegateLogger.isErrorEnabled()).thenReturn(false);
logger.error(null, msgSupplier, null);
verify(delegateLogger, never()).error(anyString(), any(Throwable.class));
verifyNoMoreInteractions(msgSupplier);
}
@Test
public void errorEnabled_noChannelProvided_invokesLogger() {
when(delegateLogger.isErrorEnabled()).thenReturn(true);
RuntimeException exception = new RuntimeException("boom!");
logger.error(null, msgSupplier, exception);
verify(delegateLogger).error(TEST_MSG, exception);
}
@Test
public void errorNotEnabled_doesNotInvokeLogger() {
when(delegateLogger.isErrorEnabled()).thenReturn(false);
Channel channel = mock(Channel.class);
logger.error(channel, msgSupplier, null);
verify(delegateLogger, never()).error(anyString(), any(Throwable.class));
verifyNoMoreInteractions(msgSupplier);
verifyNoMoreInteractions(channel);
}
@Test
public void errorEnabled_invokesLogger() {
when(delegateLogger.isErrorEnabled()).thenReturn(true);
RuntimeException exception = new RuntimeException("boom!");
logger.error(ch, msgSupplier, exception);
verify(delegateLogger).error(EXPECTED_MESSAGE_SHORT, exception);
}
@Test
public void errorEnabled_debugEnabled_invokesLogger() {
when(delegateLogger.isErrorEnabled()).thenReturn(true);
when(delegateLogger.isDebugEnabled()).thenReturn(true);
RuntimeException exception = new RuntimeException("boom!");
logger.error(ch, msgSupplier, exception);
verify(delegateLogger).error(EXPECTED_MESSAGE_FULL, exception);
}
@Test
public void warnNotEnabled_noChannelProvided_doesNotInvokeLogger() {
when(delegateLogger.isWarnEnabled()).thenReturn(false);
logger.warn(null, msgSupplier, null);
verify(delegateLogger, never()).warn(anyString(), any(Throwable.class));
verifyNoMoreInteractions(msgSupplier);
}
@Test
public void warnEnabled_noChannelProvided_invokesLogger() {
when(delegateLogger.isWarnEnabled()).thenReturn(true);
RuntimeException exception = new RuntimeException("boom!");
logger.warn(null, msgSupplier, exception);
verify(delegateLogger).warn(TEST_MSG, exception);
}
@Test
public void traceNotEnabled_doesNotInvokeLogger() {
when(delegateLogger.isTraceEnabled()).thenReturn(false);
Channel channel = mock(Channel.class);
logger.trace(channel, msgSupplier);
verify(delegateLogger, never()).trace(anyString());
verifyNoMoreInteractions(msgSupplier);
verifyNoMoreInteractions(channel);
}
@Test
public void traceEnabled_invokesLogger() {
when(delegateLogger.isTraceEnabled()).thenReturn(true);
when(delegateLogger.isDebugEnabled()).thenReturn(true);
logger.trace(ch, msgSupplier);
verify(delegateLogger).trace(EXPECTED_MESSAGE_FULL);
}
@Test
public void traceNotEnabled_noChannelProvided_doesNotInvokeLogger() {
when(delegateLogger.isTraceEnabled()).thenReturn(false);
logger.trace(null, msgSupplier);
verify(delegateLogger, never()).trace(anyString());
verifyNoMoreInteractions(msgSupplier);
}
@Test
public void traceEnabled_noChannelProvided_invokesLogger() {
when(delegateLogger.isTraceEnabled()).thenReturn(true);
logger.trace(null, msgSupplier);
verify(delegateLogger).trace(TEST_MSG);
}
}
| 1,075 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/BetterFixedChannelPoolTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.nio.netty.internal.MockChannel;
import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPool;
import software.amazon.awssdk.http.nio.netty.internal.utils.BetterFixedChannelPool.AcquireTimeoutAction;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.utils.CompletableFutureUtils;
public class BetterFixedChannelPoolTest {
private static EventLoopGroup eventLoopGroup;
private BetterFixedChannelPool channelPool;
private SdkChannelPool delegatePool;
@BeforeClass
public static void setupClass() {
eventLoopGroup = new NioEventLoopGroup(1);
}
@AfterClass
public static void teardownClass() throws InterruptedException {
eventLoopGroup.shutdownGracefully().await();
}
@Before
public void setup() {
delegatePool = mock(SdkChannelPool.class);
channelPool = BetterFixedChannelPool.builder()
.channelPool(delegatePool)
.maxConnections(2)
.maxPendingAcquires(2)
.acquireTimeoutAction(AcquireTimeoutAction.FAIL)
.acquireTimeoutMillis(10_000)
.executor(eventLoopGroup.next())
.build();
}
@After
public void teardown() {
channelPool.close();
}
@Test
public void delegateChannelPoolMetricFailureIsReported() {
Throwable t = new Throwable();
Mockito.when(delegatePool.collectChannelPoolMetrics(any())).thenReturn(CompletableFutureUtils.failedFuture(t));
CompletableFuture<Void> result = channelPool.collectChannelPoolMetrics(MetricCollector.create("test"));
waitForCompletion(result);
assertThat(result).hasFailedWithThrowableThat().isEqualTo(t);
}
@Test(timeout = 5_000)
public void metricCollectionHasCorrectValuesAfterAcquiresAndReleases() throws Exception {
List<Promise<Channel>> acquirePromises = Collections.synchronizedList(new ArrayList<>());
Mockito.when(delegatePool.acquire(isA(Promise.class))).thenAnswer(i -> {
Promise<Channel> promise = eventLoopGroup.next().newPromise();
acquirePromises.add(promise);
return promise;
});
List<Promise<Channel>> releasePromises = Collections.synchronizedList(new ArrayList<>());
Mockito.when(delegatePool.release(isA(Channel.class), isA(Promise.class))).thenAnswer(i -> {
Promise promise = i.getArgument(1, Promise.class);
releasePromises.add(promise);
return promise;
});
Mockito.when(delegatePool.collectChannelPoolMetrics(any())).thenReturn(CompletableFuture.completedFuture(null));
assertConnectionsCheckedOutAndPending(0, 0);
channelPool.acquire();
completePromise(acquirePromises, 0);
assertConnectionsCheckedOutAndPending(1, 0);
channelPool.acquire();
completePromise(acquirePromises, 1);
assertConnectionsCheckedOutAndPending(2, 0);
channelPool.acquire();
assertConnectionsCheckedOutAndPending(2, 1);
channelPool.acquire();
assertConnectionsCheckedOutAndPending(2, 2);
Future<Channel> f = channelPool.acquire();
assertConnectionsCheckedOutAndPending(2, 2);
assertThat(f.isSuccess()).isFalse();
assertThat(f.cause()).isInstanceOf(IllegalStateException.class);
channelPool.release(acquirePromises.get(1).getNow());
assertConnectionsCheckedOutAndPending(2, 2);
completePromise(releasePromises, 0);
completePromise(acquirePromises, 2);
assertConnectionsCheckedOutAndPending(2, 1);
channelPool.release(acquirePromises.get(2).getNow());
completePromise(releasePromises, 1);
completePromise(acquirePromises, 3);
assertConnectionsCheckedOutAndPending(2, 0);
channelPool.release(acquirePromises.get(0).getNow());
completePromise(releasePromises, 2);
assertConnectionsCheckedOutAndPending(1, 0);
channelPool.release(acquirePromises.get(3).getNow());
completePromise(releasePromises, 3);
assertConnectionsCheckedOutAndPending(0, 0);
}
private void completePromise(List<Promise<Channel>> promises, int promiseIndex) throws Exception {
waitForPromise(promises, promiseIndex);
MockChannel channel = new MockChannel();
eventLoopGroup.next().register(channel);
promises.get(promiseIndex).setSuccess(channel);
}
private void waitForPromise(List<Promise<Channel>> promises, int promiseIndex) throws Exception {
while (promises.size() < promiseIndex + 1) {
Thread.sleep(1);
}
}
private void assertConnectionsCheckedOutAndPending(int checkedOut, int pending) {
MetricCollector metricCollector = MetricCollector.create("foo");
waitForCompletion(channelPool.collectChannelPoolMetrics(metricCollector));
MetricCollection metrics = metricCollector.collect();
assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(2);
assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY)).containsExactly(checkedOut);
assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES)).containsExactly(pending);
}
private void waitForCompletion(CompletableFuture<Void> future) {
try {
future.get(5, TimeUnit.SECONDS);
} catch (ExecutionException e) {
return;
} catch (InterruptedException | TimeoutException e) {
throw new Error(e);
}
}
} | 1,076 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2StreamExceptionHandlerTest.java |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PING_TRACKER;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.timeout.ReadTimeoutException;
import java.io.IOException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.nio.netty.internal.MockChannel;
@RunWith(MockitoJUnitRunner.class)
public class Http2StreamExceptionHandlerTest {
private static final NioEventLoopGroup GROUP = new NioEventLoopGroup(1);
private Http2StreamExceptionHandler handler;
@Mock
private ChannelHandlerContext context;
@Mock
private Channel mockParentChannel;
private MockChannel embeddedParentChannel;
@Mock
private Channel streamChannel;
private TestVerifyExceptionHandler verifyExceptionHandler;
@Before
public void setup() throws Exception {
embeddedParentChannel = new MockChannel();
verifyExceptionHandler = new TestVerifyExceptionHandler();
embeddedParentChannel.pipeline().addLast(verifyExceptionHandler);
when(context.channel()).thenReturn(streamChannel);
handler = Http2StreamExceptionHandler.create();
when(context.executor()).thenReturn(GROUP.next());
}
@After
public void tearDown() {
embeddedParentChannel.close().awaitUninterruptibly();
Mockito.reset(streamChannel, context, mockParentChannel);
}
@AfterClass
public static void teardown() {
GROUP.shutdownGracefully().awaitUninterruptibly();
}
@Test
public void timeoutException_shouldFireExceptionAndPropagateException() {
when(streamChannel.parent()).thenReturn(embeddedParentChannel);
handler.exceptionCaught(context, ReadTimeoutException.INSTANCE);
assertThat(verifyExceptionHandler.exceptionCaught).isExactlyInstanceOf(Http2ConnectionTerminatingException.class);
verify(context).fireExceptionCaught(ReadTimeoutException.INSTANCE);
}
@Test
public void ioException_shouldFireExceptionAndPropagateException() {
IOException ioException = new IOException("yolo");
when(streamChannel.parent()).thenReturn(embeddedParentChannel);
handler.exceptionCaught(context, ioException);
assertThat(verifyExceptionHandler.exceptionCaught).isExactlyInstanceOf(Http2ConnectionTerminatingException.class);
verify(context).fireExceptionCaught(ioException);
}
@Test
public void otherException_shouldJustPropagateException() {
when(streamChannel.parent()).thenReturn(embeddedParentChannel);
RuntimeException otherException = new RuntimeException("test");
handler.exceptionCaught(context, otherException);
assertThat(embeddedParentChannel.attr(PING_TRACKER).get()).isNull();
verify(context).fireExceptionCaught(otherException);
assertThat(verifyExceptionHandler.exceptionCaught).isNull();
}
private static final class TestVerifyExceptionHandler extends ChannelInboundHandlerAdapter {
private Throwable exceptionCaught;
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
exceptionCaught = cause;
}
}
} | 1,077 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2MultiplexedChannelPoolTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_CONNECTION;
import static software.amazon.awssdk.http.nio.netty.internal.http2.utils.Http2TestUtils.newHttp2Channel;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.pool.ChannelPool;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http2.Http2Connection;
import io.netty.handler.codec.http2.Http2LocalFlowController;
import io.netty.handler.codec.http2.Http2Stream;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.FailedFuture;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricCollector;
/**
* Tests for {@link Http2MultiplexedChannelPool}.
*/
public class Http2MultiplexedChannelPoolTest {
private static EventLoopGroup loopGroup;
@BeforeClass
public static void setup() {
loopGroup = new NioEventLoopGroup(4);
}
@AfterClass
public static void teardown() {
loopGroup.shutdownGracefully().awaitUninterruptibly();
}
@Test
public void failedConnectionAcquireNotifiesPromise() throws InterruptedException {
IOException exception = new IOException();
ChannelPool connectionPool = mock(ChannelPool.class);
when(connectionPool.acquire()).thenReturn(new FailedFuture<>(loopGroup.next(), exception));
ChannelPool pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null);
Future<Channel> acquirePromise = pool.acquire().await();
assertThat(acquirePromise.isSuccess()).isFalse();
assertThat(acquirePromise.cause()).isEqualTo(exception);
}
@Test
public void releaseParentChannelIfReleasingLastChildChannelOnGoAwayChannel() {
SocketChannel channel = new NioSocketChannel();
try {
loopGroup.register(channel).awaitUninterruptibly();
ChannelPool connectionPool = mock(ChannelPool.class);
ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class);
when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> {
Promise<?> promise = releasePromise.getValue();
promise.setSuccess(null);
return promise;
});
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null);
Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup,
Collections.singleton(record), null);
h2Pool.close();
InOrder inOrder = Mockito.inOrder(connectionPool);
inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class));
inOrder.verify(connectionPool).close();
} finally {
channel.close().awaitUninterruptibly();
}
}
@Test
public void acquireAfterCloseFails() throws InterruptedException {
ChannelPool connectionPool = mock(ChannelPool.class);
Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null);
h2Pool.close();
Future<Channel> acquireResult = h2Pool.acquire().await();
assertThat(acquireResult.isSuccess()).isFalse();
assertThat(acquireResult.cause()).isInstanceOf(IOException.class);
}
@Test
public void closeWaitsForConnectionToBeReleasedBeforeClosingConnectionPool() {
SocketChannel channel = new NioSocketChannel();
try {
loopGroup.register(channel).awaitUninterruptibly();
ChannelPool connectionPool = mock(ChannelPool.class);
ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class);
when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> {
Promise<?> promise = releasePromise.getValue();
promise.setSuccess(null);
return promise;
});
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null);
Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup,
Collections.singleton(record), null);
h2Pool.close();
InOrder inOrder = Mockito.inOrder(connectionPool);
inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class));
inOrder.verify(connectionPool).close();
} finally {
channel.close().awaitUninterruptibly();
}
}
@Test
public void acquire_shouldAcquireAgainIfExistingNotReusable() throws Exception {
Channel channel = new EmbeddedChannel();
try {
ChannelPool connectionPool = Mockito.mock(ChannelPool.class);
loopGroup.register(channel).awaitUninterruptibly();
Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
channelPromise.setSuccess(channel);
Mockito.when(connectionPool.acquire()).thenReturn(channelPromise);
Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup,
Collections.emptySet(), null);
h2Pool.acquire().awaitUninterruptibly();
h2Pool.acquire().awaitUninterruptibly();
Mockito.verify(connectionPool, Mockito.times(2)).acquire();
} finally {
channel.close();
}
}
@Test(timeout = 5_000)
public void interruptDuringClosePreservesFlag() throws InterruptedException {
SocketChannel channel = new NioSocketChannel();
try {
loopGroup.register(channel).awaitUninterruptibly();
Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
channelPromise.setSuccess(channel);
ChannelPool connectionPool = mock(ChannelPool.class);
Promise<Void> releasePromise = Mockito.spy(new DefaultPromise<>(loopGroup.next()));
when(connectionPool.release(eq(channel))).thenReturn(releasePromise);
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null);
Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup,
Collections.singleton(record), null);
CompletableFuture<Boolean> interrupteFlagPreserved = new CompletableFuture<>();
Thread t = new Thread(() -> {
try {
h2Pool.close();
} catch (Exception e) {
if (e.getCause() instanceof InterruptedException && Thread.currentThread().isInterrupted()) {
interrupteFlagPreserved.complete(true);
}
}
});
t.start();
t.interrupt();
t.join();
assertThat(interrupteFlagPreserved.join()).isTrue();
} finally {
channel.close().awaitUninterruptibly();
}
}
@Test
public void acquire_shouldExpandConnectionWindowSizeProportionally() {
int maxConcurrentStream = 3;
EmbeddedChannel channel = newHttp2Channel();
channel.attr(ChannelAttributeKey.MAX_CONCURRENT_STREAMS).set((long) maxConcurrentStream);
try {
ChannelPool connectionPool = Mockito.mock(ChannelPool.class);
loopGroup.register(channel).awaitUninterruptibly();
Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
channelPromise.setSuccess(channel);
Mockito.when(connectionPool.acquire()).thenReturn(channelPromise);
Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup,
Collections.emptySet(), null);
Future<Channel> acquire = h2Pool.acquire();
acquire.awaitUninterruptibly();
channel.runPendingTasks();
Http2Connection http2Connection = channel.attr(HTTP2_CONNECTION).get();
Http2LocalFlowController flowController =
http2Connection.local().flowController();
System.out.println(flowController.initialWindowSize());
Http2Stream connectionStream = http2Connection.stream(0);
// 1_048_576 (initial configured window size), 65535 (configured initial window size)
// (1048576 - 65535) *2 + 65535 = 2031617
assertThat(flowController.windowSize(connectionStream)).isEqualTo(2031617);
// 2031617 + 1048576 (configured initial window size) = 3080193
assertThat(flowController.initialWindowSize(connectionStream)).isEqualTo(3080193);
// acquire again
h2Pool.acquire().awaitUninterruptibly();
channel.runPendingTasks();
// 3080193 + 1048576 (configured initial window size) = 4128769
assertThat(flowController.initialWindowSize(connectionStream)).isEqualTo(4128769);
Mockito.verify(connectionPool, Mockito.times(1)).acquire();
} finally {
channel.close();
}
}
@Test
public void metricsShouldSumAllChildChannels() throws InterruptedException {
int maxConcurrentStream = 2;
EmbeddedChannel channel1 = newHttp2Channel();
EmbeddedChannel channel2 = newHttp2Channel();
channel1.attr(ChannelAttributeKey.MAX_CONCURRENT_STREAMS).set((long) maxConcurrentStream);
channel2.attr(ChannelAttributeKey.MAX_CONCURRENT_STREAMS).set((long) maxConcurrentStream);
try {
ChannelPool connectionPool = Mockito.mock(ChannelPool.class);
loopGroup.register(channel1).awaitUninterruptibly();
loopGroup.register(channel2).awaitUninterruptibly();
Promise<Channel> channel1Promise = new DefaultPromise<>(loopGroup.next());
Promise<Channel> channel2Promise = new DefaultPromise<>(loopGroup.next());
channel1Promise.setSuccess(channel1);
channel2Promise.setSuccess(channel2);
Mockito.when(connectionPool.acquire()).thenReturn(channel1Promise, channel2Promise);
Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool,
Http2MultiplexedChannelPoolTest.loopGroup,
Collections.emptySet(), null);
MetricCollection metrics;
metrics = getMetrics(h2Pool);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0);
doAcquire(channel1, channel2, h2Pool);
metrics = getMetrics(h2Pool);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1);
doAcquire(channel1, channel2, h2Pool);
metrics = getMetrics(h2Pool);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0);
doAcquire(channel1, channel2, h2Pool);
metrics = getMetrics(h2Pool);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1);
Channel lastAcquire = doAcquire(channel1, channel2, h2Pool);
metrics = getMetrics(h2Pool);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0);
lastAcquire.close();
h2Pool.release(lastAcquire).awaitUninterruptibly();
metrics = getMetrics(h2Pool);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1);
channel1.close();
h2Pool.release(channel1);
metrics = getMetrics(h2Pool);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1);
channel2.close();
metrics = getMetrics(h2Pool);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0);
} finally {
channel1.close();
channel2.close();
}
}
private Channel doAcquire(EmbeddedChannel channel1, EmbeddedChannel channel2, Http2MultiplexedChannelPool h2Pool) {
Future<Channel> acquire = h2Pool.acquire();
acquire.awaitUninterruptibly();
runPendingTasks(channel1, channel2);
return acquire.getNow();
}
private void runPendingTasks(EmbeddedChannel channel1, EmbeddedChannel channel2) {
channel1.runPendingTasks();
channel2.runPendingTasks();
}
private MetricCollection getMetrics(Http2MultiplexedChannelPool h2Pool) {
MetricCollector metricCollector = MetricCollector.create("test");
h2Pool.collectChannelPoolMetrics(metricCollector);
return metricCollector.collect();
}
}
| 1,078 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2GoAwayEventListenerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.DefaultChannelId;
import io.netty.util.Attribute;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey;
public class Http2GoAwayEventListenerTest {
private ChannelHandlerContext ctx;
private Channel channel;
private ChannelPipeline channelPipeline;
private Attribute<Http2MultiplexedChannelPool> attribute;
@BeforeEach
public void setup() {
this.ctx = mock(ChannelHandlerContext.class);
this.channel = mock(Channel.class);
this.channelPipeline = mock(ChannelPipeline.class);
this.attribute = mock(Attribute.class);
when(ctx.channel()).thenReturn(channel);
when(channel.pipeline()).thenReturn(channelPipeline);
when(channel.attr(ChannelAttributeKey.HTTP2_MULTIPLEXED_CHANNEL_POOL)).thenReturn(attribute);
when(channel.id()).thenReturn(DefaultChannelId.newInstance());
}
@Test
public void goAwayWithNoChannelPoolRecordRaisesNoExceptions() throws Exception {
when(attribute.get()).thenReturn(null);
ByteBuf emptyBuffer = Unpooled.EMPTY_BUFFER;
new Http2GoAwayEventListener(channel).onGoAwayReceived(0, 0, emptyBuffer);
verify(channelPipeline).fireExceptionCaught(isA(GoAwayException.class));
assertEquals(1, emptyBuffer.refCnt());
}
@Test
public void goAwayWithChannelPoolRecordPassesAlongTheFrame() throws Exception {
Http2MultiplexedChannelPool record = mock(Http2MultiplexedChannelPool.class);
when(attribute.get()).thenReturn(record);
ByteBuf emptyBuffer = Unpooled.EMPTY_BUFFER;
new Http2GoAwayEventListener(channel).onGoAwayReceived(0, 0, emptyBuffer);
verify(record).handleGoAway(eq(channel), eq(0), isA(GoAwayException.class));
verifyNoMoreInteractions(record);
assertEquals(1, emptyBuffer.refCnt());
}
}
| 1,079 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/HttpOrHttp2ChannelPoolTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.MAX_PENDING_CONNECTION_ACQUIRES;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.REAP_IDLE_CONNECTIONS;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.pool.ChannelPool;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.MockChannel;
import software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Tests for {@link HttpOrHttp2ChannelPool}.
*/
@RunWith(MockitoJUnitRunner.class)
public class HttpOrHttp2ChannelPoolTest {
private static EventLoopGroup eventLoopGroup;
@Mock
private ChannelPool mockDelegatePool;
private HttpOrHttp2ChannelPool httpOrHttp2ChannelPool;
@BeforeClass
public static void setup() {
eventLoopGroup = new NioEventLoopGroup(1);
}
@AfterClass
public static void teardown() throws InterruptedException {
eventLoopGroup.shutdownGracefully().await();
}
@Before
public void methodSetup() {
httpOrHttp2ChannelPool = new HttpOrHttp2ChannelPool(mockDelegatePool,
eventLoopGroup,
4,
new NettyConfiguration(AttributeMap.builder()
.put(CONNECTION_ACQUIRE_TIMEOUT, Duration.ofSeconds(1))
.put(MAX_PENDING_CONNECTION_ACQUIRES, 5)
.put(REAP_IDLE_CONNECTIONS, false)
.build()));
}
@Test
public void protocolConfigNotStarted_closeSucceeds() {
httpOrHttp2ChannelPool.close();
}
@Test(timeout = 5_000)
public void invalidProtocolConfig_shouldFailPromise() throws Exception {
HttpOrHttp2ChannelPool invalidChannelPool = new HttpOrHttp2ChannelPool(mockDelegatePool,
eventLoopGroup,
4,
new NettyConfiguration(AttributeMap.builder()
.put(CONNECTION_ACQUIRE_TIMEOUT, Duration.ofSeconds(1))
.put(MAX_PENDING_CONNECTION_ACQUIRES, 0)
.build()));
Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise();
when(mockDelegatePool.acquire()).thenReturn(acquirePromise);
Thread.sleep(500);
Channel channel = new MockChannel();
eventLoopGroup.register(channel);
channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1));
acquirePromise.setSuccess(channel);
Future<Channel> p = invalidChannelPool.acquire();
assertThat(p.await().cause().getMessage()).contains("maxPendingAcquires: 0 (expected: >= 1)");
verify(mockDelegatePool).release(channel);
assertThat(channel.isOpen()).isFalse();
}
@Test
public void protocolConfigNotStarted_closeClosesDelegatePool() throws InterruptedException {
httpOrHttp2ChannelPool.close();
Thread.sleep(500);
verify(mockDelegatePool).close();
}
@Test(timeout = 5_000)
public void poolClosed_acquireFails() throws InterruptedException {
httpOrHttp2ChannelPool.close();
Thread.sleep(500);
Future<Channel> p = httpOrHttp2ChannelPool.acquire(eventLoopGroup.next().newPromise());
assertThat(p.await().cause().getMessage()).contains("pool is closed");
}
@Test(timeout = 5_000)
public void protocolConfigInProgress_poolClosed_closesChannelAndDelegatePoolOnAcquireSuccess() throws InterruptedException {
Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise();
when(mockDelegatePool.acquire()).thenReturn(acquirePromise);
// initiate the configuration
httpOrHttp2ChannelPool.acquire();
// close the pool before the config can complete (we haven't completed acquirePromise yet)
httpOrHttp2ChannelPool.close();
Thread.sleep(500);
Channel channel = new NioSocketChannel();
eventLoopGroup.register(channel);
try {
channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1));
acquirePromise.setSuccess(channel);
assertThat(channel.closeFuture().await().isDone()).isTrue();
Thread.sleep(500);
verify(mockDelegatePool).release(eq(channel));
verify(mockDelegatePool).close();
} finally {
channel.close();
}
}
@Test
public void protocolConfigInProgress_poolClosed_delegatePoolClosedOnAcquireFailure() throws InterruptedException {
Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise();
when(mockDelegatePool.acquire()).thenReturn(acquirePromise);
// initiate the configuration
httpOrHttp2ChannelPool.acquire();
// close the pool before the config can complete (we haven't completed acquirePromise yet)
httpOrHttp2ChannelPool.close();
Thread.sleep(500);
acquirePromise.setFailure(new RuntimeException("Some failure"));
Thread.sleep(500);
verify(mockDelegatePool).close();
}
@Test(timeout = 5_000)
public void protocolConfigComplete_poolClosed_closesDelegatePool() throws InterruptedException {
Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise();
when(mockDelegatePool.acquire()).thenReturn(acquirePromise);
// initiate the configuration
httpOrHttp2ChannelPool.acquire();
Thread.sleep(500);
Channel channel = new NioSocketChannel();
eventLoopGroup.register(channel);
try {
channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1));
// this should complete the protocol config
acquirePromise.setSuccess(channel);
Thread.sleep(500);
// close the pool
httpOrHttp2ChannelPool.close();
Thread.sleep(500);
verify(mockDelegatePool).close();
} finally {
channel.close();
}
}
@Test(timeout = 5_000)
public void incompleteProtocolFutureDelaysMetricsDelegationAndForwardsFailures() throws InterruptedException {
Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise();
when(mockDelegatePool.acquire()).thenReturn(acquirePromise);
// startConnection
httpOrHttp2ChannelPool.acquire();
// query for metrics before the config can complete (we haven't completed acquirePromise yet)
CompletableFuture<Void> metrics = httpOrHttp2ChannelPool.collectChannelPoolMetrics(MetricCollector.create("test"));
Thread.sleep(500);
assertThat(metrics.isDone()).isFalse();
acquirePromise.setFailure(new RuntimeException("Some failure"));
Thread.sleep(500);
assertThat(metrics.isCompletedExceptionally()).isTrue();
}
@Test(timeout = 5_000)
public void incompleteProtocolFutureDelaysMetricsDelegationAndForwardsSuccessForHttp1() throws Exception {
incompleteProtocolFutureDelaysMetricsDelegationAndForwardsSuccessForProtocol(Protocol.HTTP1_1);
}
@Test(timeout = 5_000)
public void incompleteProtocolFutureDelaysMetricsDelegationAndForwardsSuccessForHttp2() throws Exception {
incompleteProtocolFutureDelaysMetricsDelegationAndForwardsSuccessForProtocol(Protocol.HTTP2);
}
public void incompleteProtocolFutureDelaysMetricsDelegationAndForwardsSuccessForProtocol(Protocol protocol) throws Exception {
Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise();
Promise<Void> releasePromise = eventLoopGroup.next().newPromise();
when(mockDelegatePool.acquire()).thenReturn(acquirePromise);
when(mockDelegatePool.release(any(Channel.class))).thenReturn(releasePromise);
// startConnection
httpOrHttp2ChannelPool.acquire();
// query for metrics before the config can complete (we haven't completed acquirePromise yet)
MetricCollector metricCollector = MetricCollector.create("foo");
CompletableFuture<Void> metricsFuture = httpOrHttp2ChannelPool.collectChannelPoolMetrics(metricCollector);
Thread.sleep(500);
assertThat(metricsFuture.isDone()).isFalse();
Channel channel = new MockChannel();
eventLoopGroup.register(channel);
channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(protocol));
acquirePromise.setSuccess(channel);
releasePromise.setSuccess(null);
metricsFuture.join();
MetricCollection metrics = metricCollector.collect();
assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES).get(0)).isEqualTo(0);
assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY).get(0)).isEqualTo(4);
assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY).get(0)).isBetween(0, 1);
assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY).get(0)).isBetween(0, 1);
}
@Test(timeout = 5_000)
public void protocolFutureAwaitsReleaseFuture() throws Exception {
Promise<Channel> delegateAcquirePromise = eventLoopGroup.next().newPromise();
Promise<Void> releasePromise = eventLoopGroup.next().newPromise();
when(mockDelegatePool.acquire()).thenReturn(delegateAcquirePromise);
when(mockDelegatePool.release(any(Channel.class))).thenReturn(releasePromise);
MockChannel channel = new MockChannel();
eventLoopGroup.register(channel);
channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1));
// Acquire a new connection and save the returned future
Future<Channel> acquireFuture = httpOrHttp2ChannelPool.acquire();
// Return a successful connection from the delegate pool
delegateAcquirePromise.setSuccess(channel);
// The returned future should not complete until the release completes
assertThat(acquireFuture.isDone()).isFalse();
// Complete the release
releasePromise.setSuccess(null);
// Assert the returned future completes (within the test timeout)
acquireFuture.await();
}
}
| 1,080 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2SettingsFrameHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_MULTIPLEXED_CHANNEL_POOL;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.MAX_CONCURRENT_STREAMS;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.pool.ChannelPool;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.Http2SettingsFrame;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.MockChannel;
@RunWith(MockitoJUnitRunner.class)
public class Http2SettingsFrameHandlerTest {
private Http2SettingsFrameHandler handler;
private MockChannel channel;
private AtomicReference<ChannelPool> channelPoolRef;
@Mock
private ChannelHandlerContext context;
@Mock
private ChannelPool channelPool;
private CompletableFuture<Protocol> protocolCompletableFuture;
private long clientMaxStreams;
@Before
public void setup() throws Exception {
clientMaxStreams = 1000L;
protocolCompletableFuture = new CompletableFuture<>();
channel = new MockChannel();
channel.attr(MAX_CONCURRENT_STREAMS).set(null);
channel.attr(PROTOCOL_FUTURE).set(protocolCompletableFuture);
channelPoolRef = new AtomicReference<>(channelPool);
handler = new Http2SettingsFrameHandler(channel, clientMaxStreams, channelPoolRef);
}
@Test
public void channelRead_useServerMaxStreams() {
long serverMaxStreams = 50L;
Http2SettingsFrame http2SettingsFrame = http2SettingsFrame(serverMaxStreams);
handler.channelRead0(context, http2SettingsFrame);
assertThat(channel.attr(MAX_CONCURRENT_STREAMS).get()).isEqualTo(serverMaxStreams);
assertThat(protocolCompletableFuture).isDone();
assertThat(protocolCompletableFuture.join()).isEqualTo(Protocol.HTTP2);
}
@Test
public void channelRead_useClientMaxStreams() {
long serverMaxStreams = 10000L;
Http2SettingsFrame http2SettingsFrame = http2SettingsFrame(serverMaxStreams);
handler.channelRead0(context, http2SettingsFrame);
assertThat(channel.attr(MAX_CONCURRENT_STREAMS).get()).isEqualTo(clientMaxStreams);
assertThat(protocolCompletableFuture).isDone();
assertThat(protocolCompletableFuture.join()).isEqualTo(Protocol.HTTP2);
}
@Test
public void exceptionCaught_shouldHandleErrorCloseChannel() throws Exception {
Throwable cause = new Throwable(new RuntimeException("BOOM"));
handler.exceptionCaught(context, cause);
verifyChannelError(cause.getClass());
}
@Test
public void channelUnregistered_ProtocolFutureNotDone_ShouldRaiseError() throws InterruptedException {
handler.channelUnregistered(context);
verifyChannelError(IOException.class);
}
private void verifyChannelError(Class<? extends Throwable> cause) throws InterruptedException {
channel.attr(HTTP2_MULTIPLEXED_CHANNEL_POOL).set(null);
channel.runAllPendingTasks();
assertThat(channel.isOpen()).isFalse();
assertThat(protocolCompletableFuture).isDone();
assertThatThrownBy(() -> protocolCompletableFuture.join()).hasCauseExactlyInstanceOf(cause);
Mockito.verify(channelPool).release(channel);
}
private Http2SettingsFrame http2SettingsFrame(long serverMaxStreams) {
return new Http2SettingsFrame() {
@Override
public Http2Settings settings() {
Http2Settings http2Settings = new Http2Settings();
http2Settings.maxConcurrentStreams(serverMaxStreams);
return http2Settings;
}
@Override
public String name() {
return "test";
}
};
}
}
| 1,081 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/ReadTimeoutTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.util.ReferenceCountUtil;
import io.reactivex.Flowable;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Optional;
import java.util.function.Supplier;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
public class ReadTimeoutTest {
private static final int N_FRAMES = 10;
private TestH2Server testServer;
private SdkAsyncHttpClient netty;
@AfterEach
public void methodTeardown() throws InterruptedException {
if (testServer != null) {
testServer.shutdown();
}
testServer = null;
if (netty != null) {
netty.close();
}
netty = null;
}
@Test
public void readTimeoutActivatedAfterRequestFullyWritten() throws InterruptedException {
testServer = new TestH2Server(StreamHandler::new);
testServer.init();
// Set a very short read timeout, shorter than it will take to transfer
// the body
netty = NettyNioAsyncHttpClient.builder()
.protocol(Protocol.HTTP2)
.readTimeout(Duration.ofMillis(500))
.build();
SdkHttpFullRequest sdkRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.PUT)
.protocol("http")
.host("localhost")
.port(testServer.port())
.build();
// at 10 frames, should take approximately 3-4 seconds for the server
// to receive given that it sleeps for 500ms between data frames and
// sleeps for most of them
byte[] data = new byte[16384 * N_FRAMES];
Publisher<ByteBuffer> dataPublisher = Flowable.just(ByteBuffer.wrap(data));
AsyncExecuteRequest executeRequest = AsyncExecuteRequest.builder()
.request(sdkRequest)
.responseHandler(new SdkAsyncHttpResponseHandler() {
@Override
public void onHeaders(SdkHttpResponse headers) {
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
Flowable.fromPublisher(stream).forEach(s -> {});
}
@Override
public void onError(Throwable error) {
}
})
.requestContentPublisher(new SdkHttpContentPublisher() {
@Override
public Optional<Long> contentLength() {
return Optional.of((long) data.length);
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
dataPublisher.subscribe(s);
}
})
.build();
netty.execute(executeRequest).join();
}
private static final class TestH2Server extends ChannelInitializer<SocketChannel> {
private final Supplier<ChannelHandler> handlerSupplier;
private ServerBootstrap bootstrap;
private ServerSocketChannel channel;
private TestH2Server(Supplier<ChannelHandler> handlerSupplier) {
this.handlerSupplier = handlerSupplier;
}
public void init() throws InterruptedException {
bootstrap = new ServerBootstrap()
.channel(NioServerSocketChannel.class)
.group(new NioEventLoopGroup())
.childHandler(this)
.localAddress(0)
.childOption(ChannelOption.SO_KEEPALIVE, true);
channel = ((ServerSocketChannel) bootstrap.bind().await().channel());
}
public int port() {
return channel.localAddress().getPort();
}
public void shutdown() throws InterruptedException {
channel.close().await();
}
@Override
protected void initChannel(SocketChannel ch) {
Http2FrameCodec codec = Http2FrameCodecBuilder.forServer()
.autoAckPingFrame(true)
.initialSettings(new Http2Settings()
.initialWindowSize(16384)
.maxFrameSize(16384)
.maxConcurrentStreams(5))
.build();
ch.pipeline().addLast(codec);
ch.pipeline().addLast(handlerSupplier.get());
}
}
private static class StreamHandler extends ChannelInboundHandlerAdapter {
private int sleeps = N_FRAMES - 3;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (!(msg instanceof Http2Frame)) {
ctx.fireChannelRead(msg);
return;
}
Http2Frame frame = (Http2Frame) msg;
if (frame instanceof Http2DataFrame) {
Http2DataFrame dataFrame = (Http2DataFrame) frame;
ReferenceCountUtil.release(frame);
if (dataFrame.isEndStream()) {
Http2HeadersFrame respHeaders = new DefaultHttp2HeadersFrame(
new DefaultHttp2Headers().status("204"), true)
.stream(dataFrame.stream());
ctx.writeAndFlush(respHeaders);
}
if (sleeps > 0) {
--sleeps;
// Simulate a server that's slow to read data. Since our
// window size is equal to the max frame size, the client
// shouldn't be able to send more data until we update our
// window
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
ctx.writeAndFlush(new DefaultHttp2WindowUpdateFrame(dataFrame.initialFlowControlledBytes())
.stream(dataFrame.stream()));
}
}
}
}
| 1,082 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/WindowSizeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.Http2SettingsFrame;
import io.netty.util.ReferenceCountUtil;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.nio.netty.Http2Configuration;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
public class WindowSizeTest {
private static final int DEFAULT_INIT_WINDOW_SIZE = 1024 * 1024;
private TestH2Server server;
private SdkAsyncHttpClient netty;
@Rule
public ExpectedException expected = ExpectedException.none();
@After
public void methodTeardown() throws InterruptedException {
if (netty != null) {
netty.close();
}
netty = null;
if (server != null) {
server.shutdown();
}
server = null;
}
@Test
public void builderSetter_negativeValue_throws() {
expected.expect(IllegalArgumentException.class);
NettyNioAsyncHttpClient.builder()
.http2Configuration(Http2Configuration.builder()
.initialWindowSize(-1)
.build())
.build();
}
@Test
public void builderSetter_0Value_throws() {
expected.expect(IllegalArgumentException.class);
NettyNioAsyncHttpClient.builder()
.http2Configuration(Http2Configuration.builder()
.initialWindowSize(0)
.build())
.build();
}
@Test
public void builderSetter_explicitNullSet_usesDefaultValue() throws InterruptedException {
expectCorrectWindowSizeValueTest(null, DEFAULT_INIT_WINDOW_SIZE);
}
@Test
public void execute_customWindowValue_valueSentInSettings() throws InterruptedException {
int windowSize = 128 * 1024 * 1024;
expectCorrectWindowSizeValueTest(windowSize, windowSize);
}
@Test
public void execute_noExplicitValueSet_sendsDefaultValueInSettings() throws InterruptedException {
ConcurrentLinkedQueue<Http2Frame> receivedFrames = new ConcurrentLinkedQueue<>();
server = new TestH2Server(() -> new StreamHandler(receivedFrames));
server.init();
netty = NettyNioAsyncHttpClient.builder()
.protocol(Protocol.HTTP2)
.build();
AsyncExecuteRequest req = AsyncExecuteRequest.builder()
.requestContentPublisher(new EmptyPublisher())
.request(SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("http")
.host("localhost")
.port(server.port())
.build())
.responseHandler(new SdkAsyncHttpResponseHandler() {
@Override
public void onHeaders(SdkHttpResponse headers) {
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
}
@Override
public void onError(Throwable error) {
}
})
.build();
netty.execute(req).join();
List<Http2Settings> receivedSettings = receivedFrames.stream()
.filter(f -> f instanceof Http2SettingsFrame)
.map(f -> (Http2SettingsFrame) f)
.map(Http2SettingsFrame::settings)
.collect(Collectors.toList());
assertThat(receivedSettings.size()).isGreaterThan(0);
for (Http2Settings s : receivedSettings) {
assertThat(s.initialWindowSize()).isEqualTo(DEFAULT_INIT_WINDOW_SIZE);
}
}
private void expectCorrectWindowSizeValueTest(Integer builderSetterValue, int settingsFrameValue) throws InterruptedException {
ConcurrentLinkedQueue<Http2Frame> receivedFrames = new ConcurrentLinkedQueue<>();
server = new TestH2Server(() -> new StreamHandler(receivedFrames));
server.init();
netty = NettyNioAsyncHttpClient.builder()
.protocol(Protocol.HTTP2)
.http2Configuration(Http2Configuration.builder()
.initialWindowSize(builderSetterValue)
.build())
.build();
AsyncExecuteRequest req = AsyncExecuteRequest.builder()
.requestContentPublisher(new EmptyPublisher())
.request(SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("http")
.host("localhost")
.port(server.port())
.build())
.responseHandler(new SdkAsyncHttpResponseHandler() {
@Override
public void onHeaders(SdkHttpResponse headers) {
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
}
@Override
public void onError(Throwable error) {
}
})
.build();
netty.execute(req).join();
List<Http2Settings> receivedSettings = receivedFrames.stream()
.filter(f -> f instanceof Http2SettingsFrame)
.map(f -> (Http2SettingsFrame) f)
.map(Http2SettingsFrame::settings)
.collect(Collectors.toList());
assertThat(receivedSettings.size()).isGreaterThan(0);
for (Http2Settings s : receivedSettings) {
assertThat(s.initialWindowSize()).isEqualTo(settingsFrameValue);
}
}
private static final class TestH2Server extends ChannelInitializer<SocketChannel> {
private final Supplier<ChannelHandler> handlerSupplier;
private ServerBootstrap bootstrap;
private ServerSocketChannel channel;
private TestH2Server(Supplier<ChannelHandler> handlerSupplier) {
this.handlerSupplier = handlerSupplier;
}
public void init() throws InterruptedException {
bootstrap = new ServerBootstrap()
.channel(NioServerSocketChannel.class)
.group(new NioEventLoopGroup())
.childHandler(this)
.localAddress(0)
.childOption(ChannelOption.SO_KEEPALIVE, true);
channel = ((ServerSocketChannel) bootstrap.bind().await().channel());
}
public int port() {
return channel.localAddress().getPort();
}
public void shutdown() throws InterruptedException {
channel.close().await();
}
@Override
protected void initChannel(SocketChannel ch) {
Http2FrameCodec codec = Http2FrameCodecBuilder.forServer()
.initialSettings(new Http2Settings()
.maxConcurrentStreams(5))
.build();
ch.pipeline().addLast(codec);
ch.pipeline().addLast(handlerSupplier.get());
}
}
private static class StreamHandler extends ChannelInboundHandlerAdapter {
private final Queue<Http2Frame> receivedFrames;
private StreamHandler(Queue<Http2Frame> receivedFrames) {
this.receivedFrames = receivedFrames;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (!(msg instanceof Http2Frame)) {
ctx.fireChannelRead(msg);
return;
}
Http2Frame frame = (Http2Frame) msg;
receivedFrames.add(frame);
if (frame instanceof Http2DataFrame) {
Http2DataFrame dataFrame = (Http2DataFrame) frame;
if (dataFrame.isEndStream()) {
Http2HeadersFrame respHeaders = new DefaultHttp2HeadersFrame(
new DefaultHttp2Headers().status("204"), true)
.stream(dataFrame.stream());
ctx.writeAndFlush(respHeaders);
}
}
ReferenceCountUtil.release(frame);
}
}
}
| 1,083 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/HttpToHttp2OutboundAdapterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultChannelPromise;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.HttpConversionUtil;
import java.util.List;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class HttpToHttp2OutboundAdapterTest {
private static final NioEventLoopGroup EVENT_LOOP_GROUP = new NioEventLoopGroup(1);
@Mock
public ChannelHandlerContext ctx;
@Mock
public Channel channel;
@AfterClass
public static void classTeardown() {
EVENT_LOOP_GROUP.shutdownGracefully();
}
@Test
public void aggregatesWritePromises() {
when(ctx.executor()).thenReturn(EVENT_LOOP_GROUP.next());
when(ctx.channel()).thenReturn(channel);
HttpToHttp2OutboundAdapter adapter = new HttpToHttp2OutboundAdapter();
ChannelPromise writePromise = new DefaultChannelPromise(channel, EVENT_LOOP_GROUP.next());
writeRequest(adapter, writePromise);
ArgumentCaptor<ChannelPromise> writePromiseCaptor = ArgumentCaptor.forClass(ChannelPromise.class);
verify(ctx, atLeastOnce()).write(any(Object.class), writePromiseCaptor.capture());
List<ChannelPromise> writePromises = writePromiseCaptor.getAllValues();
assertThat(writePromise.isDone()).isFalse();
writePromises.forEach(ChannelPromise::setSuccess);
assertThat(writePromise.isDone()).isTrue();
}
private void writeRequest(HttpToHttp2OutboundAdapter adapter, ChannelPromise promise) {
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "/", Unpooled.wrappedBuffer(new byte[16]));
request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http");
adapter.write(ctx, request, promise);
}
}
| 1,084 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/MultiplexedChannelRecordTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey;
import software.amazon.awssdk.http.nio.netty.internal.MockChannel;
import software.amazon.awssdk.http.nio.netty.internal.UnusedChannelExceptionHandler;
public class MultiplexedChannelRecordTest {
private EventLoopGroup loopGroup;
private MockChannel channel;
@BeforeEach
public void setup() throws Exception {
loopGroup = new NioEventLoopGroup(4);
channel = new MockChannel();
}
@AfterEach
public void teardown() {
loopGroup.shutdownGracefully().awaitUninterruptibly();
channel.close();
}
@Test
public void nullIdleTimeoutSeemsToDisableReaping() throws InterruptedException {
EmbeddedChannel channel = newHttp2Channel();
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 1, null);
Promise<Channel> streamPromise = channel.eventLoop().newPromise();
record.acquireStream(streamPromise);
channel.runPendingTasks();
assertThat(streamPromise.isSuccess()).isTrue();
assertThat(channel.isOpen()).isTrue();
record.closeAndReleaseChild(streamPromise.getNow());
assertThat(channel.isOpen()).isTrue();
Thread.sleep(1_000);
channel.runPendingTasks();
assertThat(channel.isOpen()).isTrue();
}
@Test
public void recordsWithoutReservedStreamsAreClosedAfterTimeout() throws InterruptedException {
int idleTimeoutMillis = 1000;
EmbeddedChannel channel = newHttp2Channel();
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 1, Duration.ofMillis(idleTimeoutMillis));
Promise<Channel> streamPromise = channel.eventLoop().newPromise();
record.acquireStream(streamPromise);
channel.runPendingTasks();
assertThat(streamPromise.isSuccess()).isTrue();
assertThat(channel.isOpen()).isTrue();
record.closeAndReleaseChild(streamPromise.getNow());
assertThat(channel.isOpen()).isTrue();
Thread.sleep(idleTimeoutMillis * 2);
channel.runPendingTasks();
assertThat(channel.isOpen()).isFalse();
}
@Test
public void recordsWithReservedStreamsAreNotClosedAfterTimeout() throws InterruptedException {
int idleTimeoutMillis = 1000;
EmbeddedChannel channel = newHttp2Channel();
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 2, Duration.ofMillis(idleTimeoutMillis));
Promise<Channel> streamPromise = channel.eventLoop().newPromise();
Promise<Channel> streamPromise2 = channel.eventLoop().newPromise();
record.acquireStream(streamPromise);
record.acquireStream(streamPromise2);
channel.runPendingTasks();
assertThat(streamPromise.isSuccess()).isTrue();
assertThat(streamPromise2.isSuccess()).isTrue();
assertThat(channel.isOpen()).isTrue();
record.closeAndReleaseChild(streamPromise.getNow());
assertThat(channel.isOpen()).isTrue();
Thread.sleep(idleTimeoutMillis * 2);
channel.runPendingTasks();
assertThat(channel.isOpen()).isTrue();
}
@Test
public void acquireRequestResetsCloseTimer() throws InterruptedException {
int idleTimeoutMillis = 1000;
EmbeddedChannel channel = newHttp2Channel();
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 2, Duration.ofMillis(idleTimeoutMillis));
for (int i = 0; i < 20; ++i) {
Thread.sleep(idleTimeoutMillis / 10);
channel.runPendingTasks();
Promise<Channel> streamPromise = channel.eventLoop().newPromise();
assertThat(record.acquireStream(streamPromise)).isTrue();
channel.runPendingTasks();
assertThat(streamPromise.isSuccess()).isTrue();
assertThat(channel.isOpen()).isTrue();
record.closeAndReleaseChild(streamPromise.getNow());
channel.runPendingTasks();
}
assertThat(channel.isOpen()).isTrue();
Thread.sleep(idleTimeoutMillis * 2);
channel.runPendingTasks();
assertThat(channel.isOpen()).isFalse();
}
@Test
public void idleTimerDoesNotApplyBeforeFirstChannelIsCreated() throws InterruptedException {
int idleTimeoutMillis = 1000;
EmbeddedChannel channel = newHttp2Channel();
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 2, Duration.ofMillis(idleTimeoutMillis));
Thread.sleep(idleTimeoutMillis * 2);
channel.runPendingTasks();
assertThat(channel.isOpen()).isTrue();
}
@Test
public void availableStream0_reusableShouldBeFalse() {
loopGroup.register(channel).awaitUninterruptibly();
Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
channelPromise.setSuccess(channel);
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 0, Duration.ofSeconds(10));
assertThat(record.acquireStream(null)).isFalse();
}
@Test
public void acquireClaimedConnection_channelClosed_shouldThrowIOException() {
loopGroup.register(channel).awaitUninterruptibly();
Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 1, Duration.ofSeconds(10));
record.closeChildChannels();
record.acquireClaimedStream(channelPromise);
assertThatThrownBy(() -> channelPromise.get()).hasCauseInstanceOf(IOException.class);
}
@Test
public void closeChildChannels_shouldDeliverException() throws Exception {
EmbeddedChannel channel = newHttp2Channel();
loopGroup.register(channel).awaitUninterruptibly();
Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
channelPromise.setSuccess(channel);
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 2, Duration.ofSeconds(10));
Promise<Channel> streamPromise = channel.eventLoop().newPromise();
record.acquireStream(streamPromise);
channel.runPendingTasks();
Channel childChannel = streamPromise.get();
VerifyExceptionHandler verifyExceptionHandler = new VerifyExceptionHandler();
childChannel.pipeline().addFirst(verifyExceptionHandler);
IOException ioException = new IOException("foobar");
record.closeChildChannels(ioException);
assertThat(childChannel.pipeline().get(UnusedChannelExceptionHandler.class)).isNotNull();
assertThat(verifyExceptionHandler.exceptionCaught).hasStackTraceContaining("foobar")
.hasRootCauseInstanceOf(IOException.class);
// should be closed by UnusedChannelExceptionHandler
assertThat(childChannel.isOpen()).isFalse();
}
@Test
public void closeToNewStreams_AcquireStreamShouldReturnFalse() {
MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 2, Duration.ofSeconds(10));
Promise<Channel> streamPromise = channel.eventLoop().newPromise();
assertThat(record.acquireStream(streamPromise)).isTrue();
record.closeToNewStreams();
assertThat(record.acquireStream(streamPromise)).isFalse();
}
private static final class VerifyExceptionHandler extends ChannelInboundHandlerAdapter {
private Throwable exceptionCaught;
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
exceptionCaught = cause;
ctx.fireExceptionCaught(cause);
}
}
private EmbeddedChannel newHttp2Channel() {
EmbeddedChannel channel = new EmbeddedChannel(Http2FrameCodecBuilder.forClient().build(),
new Http2MultiplexHandler(new NoOpHandler()));
channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP2));
return channel;
}
private static class NoOpHandler extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel ch) { }
}
}
| 1,085 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2PingHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2;
import static java.time.temporal.ChronoUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http2.DefaultHttp2PingFrame;
import io.netty.handler.codec.http2.Http2PingFrame;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey;
public class Http2PingHandlerTest {
private static final int FAST_CHECKER_DURATION_MILLIS = 100;
private Http2PingHandler fastChecker;
private Http2PingHandler slowChecker;
@BeforeEach
public void setup() throws Exception {
this.fastChecker = new Http2PingHandler(FAST_CHECKER_DURATION_MILLIS);
this.slowChecker = new Http2PingHandler(30 * 1_000);
}
@Test
public void register_withoutProtocol_Fails() {
EmbeddedChannel channel = new EmbeddedChannel(slowChecker);
assertThat(channel.pipeline().get(Http2PingHandler.class)).isNull();
}
@Test
public void register_withIncompleteProtocol_doesNotPing() {
EmbeddedChannel channel = createChannelWithoutProtocol(fastChecker);
channel.runPendingTasks();
DefaultHttp2PingFrame sentFrame = channel.readOutbound();
assertThat(sentFrame).isNull();
}
@Test
public void register_withHttp1Protocol_doesNotPing() {
EmbeddedChannel channel = createHttp1Channel(fastChecker);
channel.runPendingTasks();
DefaultHttp2PingFrame sentFrame = channel.readOutbound();
assertThat(sentFrame).isNull();
}
@Test
public void register_WithHttp2Protocol_pingsImmediately() {
EmbeddedChannel channel = createHttp2Channel(slowChecker);
channel.runPendingTasks();
DefaultHttp2PingFrame sentFrame = channel.readOutbound();
assertThat(sentFrame).isNotNull();
assertThat(sentFrame.ack()).isFalse();
}
@Test
public void unregister_stopsRunning() throws InterruptedException {
EmbeddedChannel channel = createHttp2Channel(fastChecker);
channel.pipeline().remove(Http2PingHandler.class);
// Flush out any tasks that happened before we closed
channel.runPendingTasks();
while (channel.readOutbound() != null) {
// Discard
}
Thread.sleep(FAST_CHECKER_DURATION_MILLIS);
DefaultHttp2PingFrame sentFrame = channel.readOutbound();
assertThat(sentFrame).isNull();
}
@Test
public void ignoredPingsResultInOneChannelException() throws InterruptedException {
PipelineExceptionCatcher catcher = new PipelineExceptionCatcher();
EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher);
Thread.sleep(FAST_CHECKER_DURATION_MILLIS);
channel.runPendingTasks();
assertThat(catcher.caughtExceptions).hasSize(1);
assertThat(catcher.caughtExceptions.get(0)).isInstanceOf(IOException.class);
}
@Test
public void respondedToPingsResultInNoAction() {
PipelineExceptionCatcher catcher = new PipelineExceptionCatcher();
EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher);
channel.eventLoop().scheduleAtFixedRate(() -> channel.writeInbound(new DefaultHttp2PingFrame(0, true)),
0, FAST_CHECKER_DURATION_MILLIS, TimeUnit.MILLISECONDS);
Instant runEnd = Instant.now().plus(1, SECONDS);
while (Instant.now().isBefore(runEnd)) {
channel.runPendingTasks();
}
assertThat(catcher.caughtExceptions).isEmpty();
}
@Test
public void nonAckPingsResultInOneChannelException() {
PipelineExceptionCatcher catcher = new PipelineExceptionCatcher();
EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher);
channel.eventLoop().scheduleAtFixedRate(() -> channel.writeInbound(new DefaultHttp2PingFrame(0, false)),
0, FAST_CHECKER_DURATION_MILLIS, TimeUnit.MILLISECONDS);
Instant runEnd = Instant.now().plus(1, SECONDS);
while (Instant.now().isBefore(runEnd)) {
channel.runPendingTasks();
}
assertThat(catcher.caughtExceptions).hasSize(1);
assertThat(catcher.caughtExceptions.get(0)).isInstanceOf(IOException.class);
}
@Test
public void failedWriteResultsInOneChannelException() throws InterruptedException {
PipelineExceptionCatcher catcher = new PipelineExceptionCatcher();
EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher, new FailingWriter());
channel.runPendingTasks();
assertThat(catcher.caughtExceptions).hasSize(1);
assertThat(catcher.caughtExceptions.get(0)).isInstanceOf(IOException.class);
}
@Test
public void ackPingsAreNotForwardedToOtherHandlers() throws InterruptedException {
PingReadCatcher catcher = new PingReadCatcher();
EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher);
channel.writeInbound(new DefaultHttp2PingFrame(0, true));
channel.runPendingTasks();
assertThat(catcher.caughtPings).isEmpty();
}
private static EmbeddedChannel createChannelWithoutProtocol(ChannelHandler... handlers) {
EmbeddedChannel channel = new EmbeddedChannel();
channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).set(new CompletableFuture<>());
channel.pipeline().addLast(handlers);
return channel;
}
private static EmbeddedChannel createHttp1Channel(ChannelHandler... handlers) {
EmbeddedChannel channel = createChannelWithoutProtocol(handlers);
channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).get().complete(Protocol.HTTP1_1);
return channel;
}
private static EmbeddedChannel createHttp2Channel(ChannelHandler... handlers) {
EmbeddedChannel channel = createChannelWithoutProtocol(handlers);
channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).get().complete(Protocol.HTTP2);
return channel;
}
@Test
public void nonAckPingsAreForwardedToOtherHandlers() throws InterruptedException {
PingReadCatcher catcher = new PingReadCatcher();
EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher);
channel.writeInbound(new DefaultHttp2PingFrame(0, false));
channel.runPendingTasks();
assertThat(catcher.caughtPings).hasSize(1);
}
@Test
public void channelInactive_shouldCancelTaskAndForwardToOtherHandlers() {
EmbeddedChannel channel = createHttp2Channel(fastChecker);
ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class);
fastChecker.channelInactive(context);
Mockito.verify(context).fireChannelInactive();
channel.writeInbound(new DefaultHttp2PingFrame(0, false));
assertThat(channel.runScheduledPendingTasks()).isEqualTo(-1L);
}
private static final class PingReadCatcher extends SimpleChannelInboundHandler<Http2PingFrame> {
private final List<Http2PingFrame> caughtPings = Collections.synchronizedList(new ArrayList<>());
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2PingFrame msg) {
caughtPings.add(msg);
}
}
private static final class PipelineExceptionCatcher extends ChannelInboundHandlerAdapter {
private final List<Throwable> caughtExceptions = Collections.synchronizedList(new ArrayList<>());
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
caughtExceptions.add(cause);
super.exceptionCaught(ctx, cause);
}
}
private static final class FailingWriter extends ChannelOutboundHandlerAdapter {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
promise.setFailure(new IOException("Failed!"));
}
}
} | 1,086 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/FlushOnReadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class FlushOnReadTest {
@Mock
private ChannelHandlerContext mockCtx;
@Mock
private Channel mockChannel;
@Mock
private Channel mockParentChannel;
@Test
public void read_forwardsReadBeforeParentFlush() {
when(mockCtx.channel()).thenReturn(mockChannel);
when(mockChannel.parent()).thenReturn(mockParentChannel);
FlushOnReadHandler handler = FlushOnReadHandler.getInstance();
handler.read(mockCtx);
InOrder inOrder = Mockito.inOrder(mockCtx, mockParentChannel);
inOrder.verify(mockCtx).read();
inOrder.verify(mockParentChannel).flush();
}
@Test
public void getInstance_returnsSingleton() {
assertThat(FlushOnReadHandler.getInstance() == FlushOnReadHandler.getInstance()).isTrue();
}
}
| 1,087 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/utils/Http2TestUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.nio.netty.internal.http2.utils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2FrameLogger;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.logging.LogLevel;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey;
public final class Http2TestUtils {
public static final int INITIAL_WINDOW_SIZE = 1_048_576;
public static EmbeddedChannel newHttp2Channel() {
return newHttp2Channel(new NoOpHandler());
}
public static EmbeddedChannel newHttp2Channel(ChannelHandler channelHandler) {
Http2FrameCodec http2FrameCodec = Http2FrameCodecBuilder.forClient().initialSettings(
Http2Settings.defaultSettings().initialWindowSize(INITIAL_WINDOW_SIZE))
.frameLogger(new Http2FrameLogger(LogLevel.DEBUG)).build();
EmbeddedChannel channel = new EmbeddedChannel(http2FrameCodec,
new Http2MultiplexHandler(channelHandler));
channel.attr(ChannelAttributeKey.HTTP2_CONNECTION).set(http2FrameCodec.connection());
channel.attr(ChannelAttributeKey.HTTP2_INITIAL_WINDOW_SIZE).set(INITIAL_WINDOW_SIZE);
channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP2));
return channel;
}
private static class NoOpHandler extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel ch) {
}
}
}
| 1,088 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/ChannelPublisherTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class ChannelPublisherTest {
private EventLoopGroup group;
private Channel channel;
private Publisher<Channel> publisher;
private SubscriberProbe<Channel> subscriber;
@BeforeEach
public void start() throws Exception {
group = new NioEventLoopGroup();
EventLoop eventLoop = group.next();
HandlerPublisher<Channel> handlerPublisher = new HandlerPublisher<>(eventLoop, Channel.class);
Bootstrap bootstrap = new Bootstrap();
bootstrap
.channel(NioServerSocketChannel.class)
.group(eventLoop)
.option(ChannelOption.AUTO_READ, false)
.handler(handlerPublisher)
.localAddress("127.0.0.1", 0);
channel = bootstrap.bind().await().channel();
this.publisher = handlerPublisher;
subscriber = new SubscriberProbe<>();
}
@AfterEach
public void stop() throws Exception {
channel.unsafe().closeForcibly();
group.shutdownGracefully();
}
@Test
public void test() throws Exception {
publisher.subscribe(subscriber);
Subscription sub = subscriber.takeSubscription();
// Try one cycle
sub.request(1);
Socket socket1 = connect();
receiveConnection();
readWriteData(socket1, 1);
// Check back pressure
Socket socket2 = connect();
subscriber.expectNoElements();
// Now request the next connection
sub.request(1);
receiveConnection();
readWriteData(socket2, 2);
// Close the channel
channel.close();
subscriber.expectNoElements();
subscriber.expectComplete();
}
private Socket connect() throws Exception {
InetSocketAddress address = (InetSocketAddress) channel.localAddress();
return new Socket(address.getAddress(), address.getPort());
}
private void readWriteData(Socket socket, int data) throws Exception {
OutputStream os = socket.getOutputStream();
os.write(data);
os.flush();
InputStream is = socket.getInputStream();
int received = is.read();
socket.close();
assertEquals(received, data);
}
private void receiveConnection() throws Exception {
Channel channel = subscriber.take();
channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ctx.writeAndFlush(msg);
}
});
group.register(channel);
}
private class SubscriberProbe<T> implements Subscriber<T> {
final BlockingQueue<Subscription> subscriptions = new LinkedBlockingQueue<>();
final BlockingQueue<T> elements = new LinkedBlockingQueue<>();
final Promise<Void> promise = new DefaultPromise<>(group.next());
public void onSubscribe(Subscription s) {
subscriptions.add(s);
}
public void onNext(T t) {
elements.add(t);
}
public void onError(Throwable t) {
promise.setFailure(t);
}
public void onComplete() {
promise.setSuccess(null);
}
Subscription takeSubscription() throws Exception {
Subscription sub = subscriptions.poll(100, TimeUnit.MILLISECONDS);
assertNotNull(sub);
return sub;
}
T take() throws Exception {
T t = elements.poll(1000, TimeUnit.MILLISECONDS);
assertNotNull(t);
return t;
}
void expectNoElements() throws Exception {
T t = elements.poll(100, TimeUnit.MILLISECONDS);
assertNull(t);
}
void expectComplete() throws Exception {
promise.get(100, TimeUnit.MILLISECONDS);
}
}
}
| 1,089 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerPublisherVerificationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.local.LocalChannel;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import software.amazon.awssdk.http.nio.netty.internal.nrs.util.BatchedProducer;
import software.amazon.awssdk.http.nio.netty.internal.nrs.util.ClosedLoopChannel;
import software.amazon.awssdk.http.nio.netty.internal.nrs.util.ScheduledBatchedProducer;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class HandlerPublisherVerificationTest extends PublisherVerification<Long> {
private final int batchSize;
// The number of elements to publish initially, before the subscriber is received
private final int publishInitial;
// Whether we should use scheduled publishing (with a small delay)
private final boolean scheduled;
private ScheduledExecutorService executor;
private DefaultEventLoopGroup eventLoop;
@Factory(dataProvider = "data")
public HandlerPublisherVerificationTest(int batchSize, int publishInitial, boolean scheduled) {
super(new TestEnvironment(200));
this.batchSize = batchSize;
this.publishInitial = publishInitial;
this.scheduled = scheduled;
}
@DataProvider
public static Object[][] data() {
final int defaultBatchSize = 3;
final int defaultPublishInitial = 3;
final boolean defaultScheduled = false;
return new Object[][] {
{ defaultBatchSize, defaultPublishInitial, defaultScheduled },
{ 1, defaultPublishInitial, defaultScheduled },
{ defaultBatchSize, 0, defaultScheduled },
{ defaultBatchSize, defaultPublishInitial, true }
};
}
// I tried making this before/after class, but encountered a strange error where after 32 publishers were created,
// the following tests complained about the executor being shut down when I registered the channel. Though, it
// doesn't happen if you create 32 publishers in a single test.
@BeforeMethod
public void startEventLoop() {
eventLoop = new DefaultEventLoopGroup();
}
@AfterMethod
public void stopEventLoop() {
eventLoop.shutdownGracefully();
eventLoop = null;
}
@BeforeClass
public void startExecutor() {
executor = Executors.newSingleThreadScheduledExecutor();
}
@AfterClass
public void stopExecutor() {
executor.shutdown();
}
@Override
public Publisher<Long> createPublisher(final long elements) {
final BatchedProducer out;
if (scheduled) {
out = new ScheduledBatchedProducer(elements, batchSize, publishInitial, executor, 5);
} else {
out = new BatchedProducer(elements, batchSize, publishInitial, executor);
}
final ClosedLoopChannel channel = new ClosedLoopChannel();
channel.config().setAutoRead(false);
ChannelFuture registered = eventLoop.register(channel);
final HandlerPublisher<Long> publisher = new HandlerPublisher<>(registered.channel().eventLoop(), Long.class);
registered.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
channel.pipeline().addLast("out", out);
channel.pipeline().addLast("publisher", publisher);
for (long i = 0; i < publishInitial && i < elements; i++) {
channel.pipeline().fireChannelRead(i);
}
if (elements <= publishInitial) {
channel.pipeline().fireChannelInactive();
}
}
});
return publisher;
}
@Override
public Publisher<Long> createFailedPublisher() {
LocalChannel channel = new LocalChannel();
eventLoop.register(channel);
HandlerPublisher<Long> publisher = new HandlerPublisher<>(channel.eventLoop(), Long.class);
channel.pipeline().addLast("publisher", publisher);
channel.pipeline().fireExceptionCaught(new RuntimeException("failed"));
return publisher;
}
@Override
public void stochastic_spec103_mustSignalOnMethodsSequentially() throws Throwable {
try {
super.stochastic_spec103_mustSignalOnMethodsSequentially();
} catch (Throwable t) {
// CI is failing here, but maven doesn't tell us which parameters failed
System.out.println("Stochastic test failed with parameters batchSize=" + batchSize +
" publishInitial=" + publishInitial + " scheduled=" + scheduled);
throw t;
}
}
}
| 1,090 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerSubscriberTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.concurrent.AbstractEventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.internal.ObjectUtil;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Subscription;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class HandlerSubscriberTest {
private EmbeddedChannel channel;
private CustomEmbeddedEventLoop eventLoop;
private HandlerSubscriber<HttpContent> handler;
@BeforeEach
public void setup() throws Exception {
channel = new CustomEmbeddedChannel();
eventLoop = new CustomEmbeddedEventLoop();
eventLoop.register(channel).syncUninterruptibly();
handler = new HandlerSubscriber<>(eventLoop);
channel.pipeline().addLast(handler);
}
@AfterEach
public void teardown() {
channel.close();
}
/**
* Ensures that onNext invocations against the {@link HandlerSubscriber} do not order things based on which thread is calling
* onNext.
*/
@Test
public void onNextWritesInProperOrderFromAnyThread() {
HttpContent front = emptyHttpRequest();
HttpContent back = emptyHttpRequest();
handler.onSubscribe(doNothingSubscription());
eventLoop.inEventLoop(false);
handler.onNext(front);
eventLoop.inEventLoop(true);
handler.onNext(back);
eventLoop.runTasks();
Queue<Object> outboundMessages = channel.outboundMessages();
assertThat(outboundMessages).hasSize(2);
assertThat(outboundMessages.poll()).isSameAs(front);
assertThat(outboundMessages.poll()).isSameAs(back);
}
private DefaultFullHttpRequest emptyHttpRequest() {
return new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://fake.com");
}
private Subscription doNothingSubscription() {
return new Subscription() {
@Override
public void request(long n) { }
@Override
public void cancel() { }
};
}
private static class CustomEmbeddedChannel extends EmbeddedChannel {
public volatile CustomEmbeddedEventLoop loop;
private CustomEmbeddedChannel() {
super(false, false);
}
@Override
protected boolean isCompatible(EventLoop loop) {
return loop instanceof CustomEmbeddedEventLoop;
}
@Override
public void runPendingTasks() {
loop.runTasks();
}
}
private static class CustomEmbeddedEventLoop extends AbstractEventExecutor implements EventLoop {
private final Queue<Runnable> tasks = new ArrayDeque<>(2);
private volatile boolean inEventLoop = true;
@Override
public EventLoopGroup parent() {
return (EventLoopGroup) super.parent();
}
@Override
public EventLoop next() {
return (EventLoop) super.next();
}
@Override
public void execute(Runnable runnable) {
tasks.add(runnable);
}
public void runTasks() {
for (;;) {
Runnable task = tasks.poll();
if (task == null) {
break;
}
task.run();
}
}
@Override
public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
throw new UnsupportedOperationException();
}
@Override
public Future<?> terminationFuture() {
throw new UnsupportedOperationException();
}
@Override
@Deprecated
public void shutdown() {
throw new UnsupportedOperationException();
}
@Override
public boolean isShuttingDown() {
return false;
}
@Override
public boolean isShutdown() {
return false;
}
@Override
public boolean isTerminated() {
return false;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) {
return false;
}
@Override
public ChannelFuture register(Channel channel) {
((CustomEmbeddedChannel) channel).loop = this;
return register(new DefaultChannelPromise(channel, this));
}
@Override
public ChannelFuture register(ChannelPromise promise) {
ObjectUtil.checkNotNull(promise, "promise");
promise.channel().unsafe().register(this, promise);
return promise;
}
@Deprecated
@Override
public ChannelFuture register(Channel channel, ChannelPromise promise) {
channel.unsafe().register(this, promise);
return promise;
}
public void inEventLoop(boolean inEventLoop) {
this.inEventLoop = inEventLoop;
}
@Override
public boolean inEventLoop() {
return inEventLoop;
}
@Override
public boolean inEventLoop(Thread thread) {
return inEventLoop;
}
}
} | 1,091 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerSubscriberBlackboxVerificationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.embedded.EmbeddedChannel;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.reactivestreams.tck.SubscriberBlackboxVerification;
import org.reactivestreams.tck.TestEnvironment;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class HandlerSubscriberBlackboxVerificationTest extends SubscriberBlackboxVerification<Long> {
public HandlerSubscriberBlackboxVerificationTest() {
super(new TestEnvironment());
}
@Override
public Subscriber<Long> createSubscriber() {
// Embedded channel requires at least one handler when it's created, but HandlerSubscriber
// needs the channels event loop in order to be created, so start with a dummy, then replace.
ChannelHandler dummy = new ChannelDuplexHandler();
EmbeddedChannel channel = new EmbeddedChannel(dummy);
HandlerSubscriber<Long> subscriber = new HandlerSubscriber<>(channel.eventLoop(), 2, 4);
channel.pipeline().replace(dummy, "subscriber", subscriber);
return new SubscriberWithChannel<>(channel, subscriber);
}
@Override
public Long createElement(int element) {
return (long) element;
}
@Override
public void triggerRequest(Subscriber<? super Long> subscriber) {
EmbeddedChannel channel = ((SubscriberWithChannel) subscriber).channel;
channel.runPendingTasks();
while (channel.readOutbound() != null) {
channel.runPendingTasks();
}
channel.runPendingTasks();
}
/**
* Delegate subscriber that makes the embedded channel available so we can talk to it to trigger a request.
*/
private static class SubscriberWithChannel<T> implements Subscriber<T> {
final EmbeddedChannel channel;
final HandlerSubscriber<T> subscriber;
public SubscriberWithChannel(EmbeddedChannel channel, HandlerSubscriber<T> subscriber) {
this.channel = channel;
this.subscriber = subscriber;
}
public void onSubscribe(Subscription s) {
subscriber.onSubscribe(s);
}
public void onNext(T t) {
subscriber.onNext(t);
}
public void onError(Throwable t) {
subscriber.onError(t);
}
public void onComplete() {
subscriber.onComplete();
}
}
}
| 1,092 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerSubscriberWhiteboxVerificationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import org.reactivestreams.Subscriber;
import org.reactivestreams.tck.SubscriberWhiteboxVerification;
import org.reactivestreams.tck.TestEnvironment;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import software.amazon.awssdk.http.nio.netty.internal.nrs.util.ClosedLoopChannel;
import software.amazon.awssdk.http.nio.netty.internal.nrs.util.ProbeHandler;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class HandlerSubscriberWhiteboxVerificationTest extends SubscriberWhiteboxVerification<Long> {
private boolean workAroundIssue277;
public HandlerSubscriberWhiteboxVerificationTest() {
super(new TestEnvironment());
}
private DefaultEventLoopGroup eventLoop;
// I tried making this before/after class, but encountered a strange error where after 32 publishers were created,
// the following tests complained about the executor being shut down when I registered the channel. Though, it
// doesn't happen if you create 32 publishers in a single test.
@BeforeMethod
public void startEventLoop() {
workAroundIssue277 = false;
eventLoop = new DefaultEventLoopGroup();
}
@AfterMethod
public void stopEventLoop() {
eventLoop.shutdownGracefully();
eventLoop = null;
}
@Override
public Subscriber<Long> createSubscriber(WhiteboxSubscriberProbe<Long> probe) {
final ClosedLoopChannel channel = new ClosedLoopChannel();
channel.config().setAutoRead(false);
ChannelFuture registered = eventLoop.register(channel);
final HandlerSubscriber<Long> subscriber = new HandlerSubscriber<>(registered.channel().eventLoop(), 2, 4);
final ProbeHandler<Long> probeHandler = new ProbeHandler<>(probe, Long.class);
final Promise<Void> handlersInPlace = new DefaultPromise<>(eventLoop.next());
registered.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
channel.pipeline().addLast("probe", probeHandler);
channel.pipeline().addLast("subscriber", subscriber);
handlersInPlace.setSuccess(null);
// Channel needs to be active before the subscriber starts responding to demand
channel.pipeline().fireChannelActive();
}
});
if (workAroundIssue277) {
try {
// Wait for the pipeline to be setup, so we're ready to receive elements even if they aren't requested,
// because https://github.com/reactive-streams/reactive-streams-jvm/issues/277
handlersInPlace.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
return probeHandler.wrap(subscriber);
}
@Override
public void required_spec208_mustBePreparedToReceiveOnNextSignalsAfterHavingCalledSubscriptionCancel() throws Throwable {
// See https://github.com/reactive-streams/reactive-streams-jvm/issues/277
workAroundIssue277 = true;
super.required_spec208_mustBePreparedToReceiveOnNextSignalsAfterHavingCalledSubscriptionCancel();
}
@Override
public void required_spec308_requestMustRegisterGivenNumberElementsToBeProduced() throws Throwable {
workAroundIssue277 = true;
super.required_spec308_requestMustRegisterGivenNumberElementsToBeProduced();
}
@Override
public Long createElement(int element) {
return (long) element;
}
}
| 1,093 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/util/BatchedProducer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs.util;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import java.util.concurrent.Executor;
/**
* A batched producer.
*
* Responds to read requests with batches of elements according to batch size. When eofOn is reached, it closes the
* channel.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class BatchedProducer extends ChannelOutboundHandlerAdapter {
protected final long eofOn;
protected final int batchSize;
private final Executor executor;
protected long sequence;
public BatchedProducer(long eofOn, int batchSize, long sequence, Executor executor) {
this.eofOn = eofOn;
this.batchSize = batchSize;
this.sequence = sequence;
this.executor = executor;
}
private boolean cancelled = false;
@Override
public void read(final ChannelHandlerContext ctx) throws Exception {
if (cancelled) {
throw new IllegalStateException("Received demand after being cancelled");
}
executor.execute(() -> {
for (int i = 0; i < batchSize && sequence != eofOn; i++) {
ctx.fireChannelRead(sequence++);
}
if (eofOn == sequence) {
ctx.fireChannelInactive();
} else {
ctx.fireChannelReadComplete();
}
});
}
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
if (cancelled) {
throw new IllegalStateException("Cancelled twice");
}
cancelled = true;
}
}
| 1,094 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/util/PublisherProbe.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs.util;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class PublisherProbe<T> extends Probe implements Publisher<T> {
private final Publisher<T> publisher;
public PublisherProbe(Publisher<T> publisher, String name) {
super(name);
this.publisher = publisher;
}
@Override
public void subscribe(Subscriber<? super T> s) {
String sName = s == null ? "null" : s.getClass().getName();
log("invoke subscribe with subscriber " + sName);
publisher.subscribe(new SubscriberProbe<>(s, name, start));
log("finish subscribe");
}
}
| 1,095 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/util/ClosedLoopChannel.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs.util;
import io.netty.channel.AbstractChannel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultChannelConfig;
import io.netty.channel.EventLoop;
import java.net.SocketAddress;
/**
* A closed loop channel that sends no events and receives no events, for testing purposes.
*
* Any outgoing events that reach the channel will throw an exception. All events should be caught
* be inserting a handler that catches them and responds accordingly.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class ClosedLoopChannel extends AbstractChannel {
private final ChannelConfig config = new DefaultChannelConfig(this);
private static final ChannelMetadata metadata = new ChannelMetadata(false);
private volatile boolean open = true;
private volatile boolean active = true;
public ClosedLoopChannel() {
super(null);
}
public void setOpen(boolean open) {
this.open = open;
}
public void setActive(boolean active) {
this.active = active;
}
@Override
protected AbstractUnsafe newUnsafe() {
return new AbstractUnsafe() {
@Override
public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
throw new UnsupportedOperationException();
}
};
}
@Override
protected boolean isCompatible(EventLoop loop) {
return true;
}
@Override
protected SocketAddress localAddress0() {
throw new UnsupportedOperationException();
}
@Override
protected SocketAddress remoteAddress0() {
throw new UnsupportedOperationException();
}
@Override
protected void doBind(SocketAddress localAddress) throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected void doDisconnect() throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected void doClose() throws Exception {
this.open = false;
}
@Override
protected void doBeginRead() throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected void doWrite(ChannelOutboundBuffer in) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public ChannelConfig config() {
return config;
}
@Override
public boolean isOpen() {
return open;
}
@Override
public boolean isActive() {
return active;
}
@Override
public ChannelMetadata metadata() {
return metadata;
}
}
| 1,096 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/util/Probe.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs.util;
import java.util.Date;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class Probe {
protected final String name;
protected final Long start;
/**
* Create a new probe and log that it started.
*/
protected Probe(String name) {
this.name = name;
start = System.nanoTime();
log("Probe created at " + new Date());
}
/**
* Create a new probe with the start time from another probe.
*/
protected Probe(String name, long start) {
this.name = name;
this.start = start;
}
protected void log(String message) {
System.out.println(String.format("%10d %-5s %-15s %s", (System.nanoTime() - start) / 1000, name, Thread.currentThread().getName(), message));
}
}
| 1,097 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/util/SubscriberProbe.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs.util;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class SubscriberProbe<T> extends Probe implements Subscriber<T> {
private final Subscriber<T> subscriber;
public SubscriberProbe(Subscriber<T> subscriber, String name) {
super(name);
this.subscriber = subscriber;
}
SubscriberProbe(Subscriber<T> subscriber, String name, long start) {
super(name, start);
this.subscriber = subscriber;
}
@Override
public void onSubscribe(final Subscription s) {
String sName = s == null ? "null" : s.getClass().getName();
log("invoke onSubscribe with subscription " + sName);
subscriber.onSubscribe(new Subscription() {
@Override
public void request(long n) {
log("invoke request " + n);
s.request(n);
log("finish request");
}
@Override
public void cancel() {
log("invoke cancel");
s.cancel();
log("finish cancel");
}
});
log("finish onSubscribe");
}
@Override
public void onNext(T t) {
log("invoke onNext with message " + t);
subscriber.onNext(t);
log("finish onNext");
}
@Override
public void onError(Throwable t) {
String tName = t == null ? "null" : t.getClass().getName();
log("invoke onError with " + tName);
subscriber.onError(t);
log("finish onError");
}
@Override
public void onComplete() {
log("invoke onComplete");
subscriber.onComplete();
log("finish onComplete");
}
}
| 1,098 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/util/ProbeHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs.util;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.reactivestreams.tck.SubscriberWhiteboxVerification;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class ProbeHandler<T> extends ChannelDuplexHandler implements SubscriberWhiteboxVerification.SubscriberPuppet {
private static final int NO_CONTEXT = 0;
private static final int RUN = 1;
private static final int CANCEL = 2;
private final SubscriberWhiteboxVerification.WhiteboxSubscriberProbe<T> probe;
private final Class<T> clazz;
private final Queue<WriteEvent> queue = new LinkedList<>();
private final AtomicInteger state = new AtomicInteger(NO_CONTEXT);
private volatile ChannelHandlerContext ctx;
// Netty doesn't provide a way to send errors out, so we capture whether it was an error or complete here
private volatile Throwable receivedError = null;
public ProbeHandler(SubscriberWhiteboxVerification.WhiteboxSubscriberProbe<T> probe, Class<T> clazz) {
this.probe = probe;
this.clazz = clazz;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
if (!state.compareAndSet(NO_CONTEXT, RUN)) {
ctx.fireChannelInactive();
}
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
queue.add(new WriteEvent(clazz.cast(msg), promise));
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception {
if (receivedError == null) {
probe.registerOnComplete();
} else {
probe.registerOnError(receivedError);
}
}
@Override
public void flush(ChannelHandlerContext ctx) throws Exception {
while (!queue.isEmpty()) {
WriteEvent event = queue.remove();
probe.registerOnNext(event.msg);
event.future.setSuccess();
}
}
@Override
public void triggerRequest(long elements) {
// No need, the channel automatically requests
}
@Override
public void signalCancel() {
if (!state.compareAndSet(NO_CONTEXT, CANCEL)) {
ctx.fireChannelInactive();
}
}
private class WriteEvent {
final T msg;
final ChannelPromise future;
private WriteEvent(T msg, ChannelPromise future) {
this.msg = msg;
this.future = future;
}
}
public Subscriber<T> wrap(final Subscriber<T> subscriber) {
return new Subscriber<T>() {
public void onSubscribe(Subscription s) {
probe.registerOnSubscribe(ProbeHandler.this);
subscriber.onSubscribe(s);
}
public void onNext(T t) {
subscriber.onNext(t);
}
public void onError(Throwable t) {
receivedError = t;
subscriber.onError(t);
}
public void onComplete() {
subscriber.onComplete();
}
};
}
}
| 1,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.