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/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/coldstart/V2DefaultClientCreationBenchmark.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.benchmark.coldstart;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.profile.StackProfiler;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.CommandLineOptionException;
import org.openjdk.jmh.runner.options.CommandLineOptions;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* Benchmark for creating the clients
*/
@State(Scope.Benchmark)
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 3)
@Measurement(iterations = 5)
@Fork(3)
public class V2DefaultClientCreationBenchmark implements SdkClientCreationBenchmark {
private DynamoDbClient client;
@Override
@Benchmark
public void createClient(Blackhole blackhole) throws Exception {
client = DynamoDbClient.builder()
.endpointDiscoveryEnabled(false)
.httpClient(ApacheHttpClient.builder().build()).build();
blackhole.consume(client);
}
@TearDown(Level.Trial)
public void tearDown() throws Exception {
if (client != null) {
client.close();
}
}
public static void main(String... args) throws RunnerException, CommandLineOptionException {
Options opt = new OptionsBuilder()
.parent(new CommandLineOptions())
.include(V2DefaultClientCreationBenchmark.class.getSimpleName())
.addProfiler(StackProfiler.class)
.build();
Collection<RunResult> run = new Runner(opt).run();
}
}
| 2,500 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/coldstart/V1ClientCreationBenchmark.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.benchmark.coldstart;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.profile.StackProfiler;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.CommandLineOptionException;
import org.openjdk.jmh.runner.options.CommandLineOptions;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
/**
* Benchmark for creating the clients
*/
@State(Scope.Benchmark)
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 3)
@Measurement(iterations = 5)
@Fork(3)
public class V1ClientCreationBenchmark implements SdkClientCreationBenchmark {
private AmazonDynamoDB client;
@Override
@Benchmark
public void createClient(Blackhole blackhole) throws Exception {
client = AmazonDynamoDBClient.builder().build();
blackhole.consume(client);
}
@TearDown(Level.Trial)
public void tearDown() throws Exception {
if (client != null) {
client.shutdown();
}
}
public static void main(String... args) throws RunnerException, CommandLineOptionException {
Options opt = new OptionsBuilder()
.parent(new CommandLineOptions())
.include(V1ClientCreationBenchmark.class.getSimpleName())
.addProfiler(StackProfiler.class)
.build();
Collection<RunResult> run = new Runner(opt).run();
}
}
| 2,501 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/coldstart/SdkClientCreationBenchmark.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.benchmark.coldstart;
import org.openjdk.jmh.infra.Blackhole;
public interface SdkClientCreationBenchmark {
void createClient(Blackhole blackhole) throws Exception;
}
| 2,502 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/coldstart/V2OptimizedClientCreationBenchmark.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.benchmark.coldstart;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.profile.StackProfiler;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.CommandLineOptionException;
import org.openjdk.jmh.runner.options.CommandLineOptions;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* Benchmark for creating the clients
*/
@State(Scope.Benchmark)
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 3)
@Measurement(iterations = 5)
@Fork(3)
public class V2OptimizedClientCreationBenchmark implements SdkClientCreationBenchmark {
private DynamoDbClient client;
@Override
@Benchmark
public void createClient(Blackhole blackhole) throws Exception {
client = DynamoDbClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("test", "test")))
.httpClient(ApacheHttpClient.builder().build())
.overrideConfiguration(ClientOverrideConfiguration.builder().build())
.endpointDiscoveryEnabled(false)
.build();
blackhole.consume(client);
}
@TearDown(Level.Trial)
public void tearDown() throws Exception {
if (client != null) {
client.close();
}
}
public static void main(String... args) throws RunnerException, CommandLineOptionException {
Options opt = new OptionsBuilder()
.parent(new CommandLineOptions())
.include(V2OptimizedClientCreationBenchmark.class.getSimpleName())
.addProfiler(StackProfiler.class)
.build();
Collection<RunResult> run = new Runner(opt).run();
}
}
| 2,503 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/MockH2Server.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.benchmark.utils;
import java.io.IOException;
import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory;
import org.eclipse.jetty.http2.HTTP2Cipher;
import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory;
import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
/**
* Local h2 server used to stub fixed response.
*
* See:
* https://git.eclipse.org/c/jetty/org.eclipse.jetty.project
* .git/tree/examples/embedded/src/main/java/org/eclipse/jetty/embedded/Http2Server.java
*/
public class MockH2Server extends BaseMockServer {
private final Server server;
public MockH2Server(boolean usingAlpn) throws IOException {
super();
server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(httpPort);
// HTTP Configuration
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setSecureScheme("https");
httpConfiguration.setSecurePort(httpsPort);
httpConfiguration.setSendXPoweredBy(true);
httpConfiguration.setSendServerVersion(true);
// HTTP Connector
ServerConnector http = new ServerConnector(server,
new HttpConnectionFactory(httpConfiguration),
new HTTP2CServerConnectionFactory(httpConfiguration));
http.setPort(httpPort);
server.addConnector(http);
// HTTPS Configuration
HttpConfiguration https = new HttpConfiguration();
https.addCustomizer(new SecureRequestCustomizer());
// SSL Context Factory for HTTPS and HTTP/2
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(true);
sslContextFactory.setValidateCerts(false);
sslContextFactory.setNeedClientAuth(false);
sslContextFactory.setWantClientAuth(false);
sslContextFactory.setValidatePeerCerts(false);
sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR);
sslContextFactory.setKeyStorePassword("password");
sslContextFactory.setKeyStorePath(MockServer.class.getResource("mock-keystore.jks").toExternalForm());
// HTTP/2 Connection Factory
HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(https);
// SSL Connection Factory
SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "h2");
ServerConnector http2Connector;
if (usingAlpn) {
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
alpn.setDefaultProtocol("h2");
// HTTP/2 Connector
http2Connector = new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(https));
} else {
http2Connector = new ServerConnector(server, ssl, h2, new HttpConnectionFactory(https));
}
http2Connector.setPort(httpsPort);
server.addConnector(http2Connector);
ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new AlwaysSuccessServlet()), "/*");
server.setHandler(context);
}
public void start() throws Exception {
server.start();
}
public void stop() throws Exception {
server.stop();
}
} | 2,504 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/BenchmarkProcessorOutput.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.benchmark.utils;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.benchmark.stats.SdkBenchmarkResult;
/**
* The output object of the benchmark processor. This contains the results of the all the benchmarks that were run, and the
* list of benchmarks that failed.
*/
public final class BenchmarkProcessorOutput {
private final Map<String, SdkBenchmarkResult> benchmarkResults;
private final List<String> failedBenchmarks;
@JsonCreator
public BenchmarkProcessorOutput(Map<String, SdkBenchmarkResult> benchmarkResults, List<String> failedBenchmarks) {
this.benchmarkResults = benchmarkResults;
this.failedBenchmarks = failedBenchmarks;
}
public Map<String, SdkBenchmarkResult> getBenchmarkResults() {
return benchmarkResults;
}
public List<String> getFailedBenchmarks() {
return failedBenchmarks;
}
}
| 2,505 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/BenchmarkUtils.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.benchmark.utils;
import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.DEFAULT_JDK_SSL_PROVIDER;
import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.OPEN_SSL_PROVIDER;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslProvider;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.commons.math3.stat.inference.TestUtils;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.util.Statistics;
import software.amazon.awssdk.benchmark.stats.SdkBenchmarkStatistics;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.Logger;
/**
* Contains utilities methods used by the benchmarks
*/
public final class BenchmarkUtils {
private static final Logger logger = Logger.loggerFor(BenchmarkConstant.class);
private BenchmarkUtils() {
}
public static void countDownUponCompletion(Blackhole blackhole,
CompletableFuture<?> completableFuture,
CountDownLatch countDownLatch) {
completableFuture.whenComplete((r, t) -> {
if (t != null) {
logger.error(() -> "Exception returned from the response ", t);
blackhole.consume(t);
} else {
blackhole.consume(r);
}
countDownLatch.countDown();
});
}
public static SslProvider getSslProvider(String sslProviderValue) {
switch (sslProviderValue) {
case DEFAULT_JDK_SSL_PROVIDER:
return SslProvider.JDK;
case OPEN_SSL_PROVIDER:
return SslProvider.OPENSSL;
default:
return SslContext.defaultClientProvider();
}
}
public static void awaitCountdownLatchUninterruptibly(CountDownLatch countDownLatch, int timeout, TimeUnit unit) {
try {
if (!countDownLatch.await(timeout, unit)) {
throw new RuntimeException("Countdown latch did not successfully return within " + timeout + " " + unit);
}
} catch (InterruptedException e) {
// No need to re-interrupt.
logger.error(() -> "InterruptedException thrown ", e);
}
}
public static AttributeMap.Builder trustAllTlsAttributeMapBuilder() {
return AttributeMap.builder().put(TRUST_ALL_CERTIFICATES, true);
}
/**
* Returns an unused port in the localhost.
*/
public static int getUnusedPort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
socket.setReuseAddress(true);
return socket.getLocalPort();
}
}
/**
* Compare the results statistically.
*
* See {@link Statistics#compareTo(Statistics, double)}
*
* @param current the current result
* @param other the other result to compare with
* @param confidence the confidence level
* @return a negative integer, zero, or a positive integer as this statistics
* is less than, equal to, or greater than the specified statistics.
*/
public static int compare(SdkBenchmarkStatistics current, SdkBenchmarkStatistics other, double confidence) {
if (isDifferent(current, other, confidence)) {
logger.info(() -> "isDifferent ? " + true);
double t = current.getMean();
double o = other.getMean();
return (t > o) ? -1 : 1;
}
return 0;
}
/**
* See {@link Statistics#compareTo(Statistics)}
*/
public static int compare(SdkBenchmarkStatistics current, SdkBenchmarkStatistics other) {
return compare(current, other, 0.99);
}
private static boolean isDifferent(SdkBenchmarkStatistics current, SdkBenchmarkStatistics other, double confidence) {
return TestUtils.tTest(current, other, 1 - confidence);
}
}
| 2,506 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/MockHttpClient.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.benchmark.utils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpResponse;
/**
* Mock implementation of {@link SdkHttpClient} to return mock response.
*/
public final class MockHttpClient implements SdkHttpClient {
private String successResponseContent;
private String errorResponseContent;
public MockHttpClient(String successResponseContent, String errorResponseContent) {
this.successResponseContent = successResponseContent;
this.errorResponseContent = errorResponseContent;
}
@Override
public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) {
if (request.httpRequest().firstMatchingHeader("stub-error").isPresent()) {
return new MockHttpRequest(errorResponse());
}
return new MockHttpRequest(successResponse());
}
@Override
public void close() {
}
private class MockHttpRequest implements ExecutableHttpRequest {
private final HttpExecuteResponse response;
private MockHttpRequest(HttpExecuteResponse response) {
this.response = response;
}
@Override
public HttpExecuteResponse call() throws IOException {
return response;
}
@Override
public void abort() {
}
}
private HttpExecuteResponse successResponse() {
AbortableInputStream inputStream =
AbortableInputStream.create(new ByteArrayInputStream(successResponseContent.getBytes()));
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(200)
.build())
.responseBody(inputStream)
.build();
}
private HttpExecuteResponse errorResponse() {
AbortableInputStream inputStream =
AbortableInputStream.create(new ByteArrayInputStream(errorResponseContent.getBytes()));
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(500)
.build())
.responseBody(inputStream)
.build();
}
} | 2,507 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/AlwaysSuccessServlet.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.benchmark.utils;
import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.JSON_BODY;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpStatus;
/**
* Always succeeds with with a 200 response.
*/
public class AlwaysSuccessServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setStatus(HttpStatus.OK_200);
response.setContentType("application/json");
response.setContentLength(JSON_BODY.getBytes(StandardCharsets.UTF_8).length);
response.getOutputStream().print(JSON_BODY);
}
}
| 2,508 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/BenchmarkConstant.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.benchmark.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.protocolec2.model.AllTypesRequest;
/**
* Contains constants used by the benchmarks
*/
@SuppressWarnings("unchecked")
public final class BenchmarkConstant {
public static final String DEFAULT_JDK_SSL_PROVIDER = "jdk";
public static final String OPEN_SSL_PROVIDER = "openssl";
public static final int CONCURRENT_CALLS = 50;
public static final Instant TIMESTAMP_MEMBER = LocalDateTime.now().toInstant(ZoneOffset.UTC);
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static final String ERROR_JSON_BODY = "{}";
public static final String JSON_BODY = "{\"StringMember\":\"foo\",\"IntegerMember\":123,\"BooleanMember\":true,"
+ "\"FloatMember\":123.0,\"DoubleMember\":123.9,\"LongMember\":123,"
+ "\"SimpleList\":[\"so simple\"],"
+ "\"ListOfStructs\":[{\"StringMember\":\"listOfStructs1\"}],"
+ "\"TimestampMember\":1540982918.887,"
+ "\"StructWithNestedTimestampMember\":{\"NestedTimestamp\":1540982918.908},"
+ "\"BlobArg\":\"aGVsbG8gd29ybGQ=\"}";
public static final String XML_BODY = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><AllTypesResponse "
+ "xmlns=\"https://restxml/\"><stringMember>foo</stringMember><integerMember>123"
+ "</integerMember><booleanMember>true</booleanMember><floatMember>123"
+ ".0</floatMember><doubleMember>123"
+ ".9</doubleMember><longMember>123</longMember><simpleList><member>so "
+ "simple</member></simpleList><listOfStructs><member><StringMember>listOfStructs1"
+ "</StringMember></member></listOfStructs><timestampMember>2018-10-31T10:51:12"
+ ".302183Z</timestampMember><structWithNestedTimestampMember><NestedTimestamp>2018"
+ "-10-31T10:51:12.311305Z</NestedTimestamp></structWithNestedTimestampMember"
+ "><blobArg>aGVsbG8gd29ybGQ=</blobArg></AllTypesResponse>";
public static final String ERROR_XML_BODY = "<ErrorResponse>"
+ " <Error>"
+ " <Code>ImplicitPayloadException</Code>"
+ " <Message>this is the service message</Message>"
+ " <StringMember>foo</StringMember>"
+ " <IntegerMember>42</IntegerMember>"
+ " <LongMember>9001</LongMember>"
+ " <DoubleMember>1234.56</DoubleMember>"
+ " <FloatMember>789.10</FloatMember>"
+ " <TimestampMember>2015-01-25T08:00:12Z</TimestampMember>"
+ " <BooleanMember>true</BooleanMember>"
+ " <BlobMember>dGhlcmUh</BlobMember>"
+ " <ListMember>"
+ " <member>valOne</member>"
+ " <member>valTwo</member>"
+ " </ListMember>"
+ " <MapMember>"
+ " <entry>"
+ " <key>keyOne</key>"
+ " <value>valOne</value>"
+ " </entry>"
+ " <entry>"
+ " <key>keyTwo</key>"
+ " <value>valTwo</value>"
+ " </entry>"
+ " </MapMember>"
+ " <SimpleStructMember>"
+ " <StringMember>foobar</StringMember>"
+ " </SimpleStructMember>"
+ " </Error>"
+ "</ErrorResponse>";
public static final software.amazon.awssdk.services.protocolrestxml.model.AllTypesRequest XML_ALL_TYPES_REQUEST =
software.amazon.awssdk.services.protocolrestxml.model.AllTypesRequest.builder()
.stringMember("foo")
.integerMember(123)
.booleanMember(true)
.floatMember(123.0f)
.doubleMember(123.9)
.longMember(123L)
.simpleStructMember(b -> b.stringMember(
"bar"))
.simpleList("so simple")
.listOfStructs(b -> b.stringMember(
"listOfStructs1").stringMember(
"listOfStructs1"))
.timestampMember(
TIMESTAMP_MEMBER)
.structWithNestedTimestampMember(
b -> b.nestedTimestamp(TIMESTAMP_MEMBER))
.blobArg(SdkBytes.fromUtf8String("hello "
+ "world"))
.build();
public static final software.amazon.awssdk.services.protocolquery.model.AllTypesRequest QUERY_ALL_TYPES_REQUEST =
software.amazon.awssdk.services.protocolquery.model.AllTypesRequest.builder()
.stringMember("foo")
.integerMember(123)
.booleanMember(true)
.floatMember(123.0f)
.doubleMember(123.9)
.longMember(123L)
.simpleStructMember(b -> b.stringMember(
"bar"))
.simpleList("so simple")
.listOfStructs(b -> b.stringMember(
"listOfStructs1").stringMember(
"listOfStructs1"))
.timestampMember(
TIMESTAMP_MEMBER)
.structWithNestedTimestampMember(
b -> b.nestedTimestamp(
TIMESTAMP_MEMBER))
.blobArg(SdkBytes.fromUtf8String("hello " +
"world"))
.build();
public static final software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest JSON_ALL_TYPES_REQUEST =
software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest.builder()
.stringMember("foo")
.integerMember(123)
.booleanMember(true)
.floatMember(123.0f)
.doubleMember(123.9)
.longMember(123L)
.simpleList("so simple")
.listOfStructs(b -> b.stringMember(
"listOfStructs1").stringMember(
"listOfStructs1"))
.timestampMember(
TIMESTAMP_MEMBER)
.structWithNestedTimestampMember(
b -> b.nestedTimestamp(
TIMESTAMP_MEMBER))
.blobArg(SdkBytes.fromUtf8String("hello "
+ "world"))
.build();
public static final AllTypesRequest EC2_ALL_TYPES_REQUEST =
AllTypesRequest.builder()
.stringMember("foo")
.integerMember(123)
.booleanMember(true)
.floatMember(123.0f)
.doubleMember(123.9)
.longMember(123L)
.simpleStructMember(b -> b.stringMember(
"bar"))
.simpleList("so simple")
.listOfStructs(b -> b.stringMember(
"listOfStructs1").stringMember(
"listOfStructs1"))
.timestampMember(TIMESTAMP_MEMBER)
.structWithNestedTimestampMember(b -> b.nestedTimestamp(
TIMESTAMP_MEMBER))
.blobArg(SdkBytes.fromUtf8String("hello "
+ "world"))
.build();
private BenchmarkConstant() {
}
}
| 2,509 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/MockServer.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.benchmark.utils;
import java.io.IOException;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
public class MockServer extends BaseMockServer {
private Server server;
private ServerConnector connector;
private ServerConnector sslConnector;
public MockServer() throws IOException {
server = new Server();
connector = new ServerConnector(server);
connector.setPort(httpPort);
HttpConfiguration https = new HttpConfiguration();
https.addCustomizer(new SecureRequestCustomizer());
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(true);
sslContextFactory.setValidateCerts(false);
sslContextFactory.setNeedClientAuth(false);
sslContextFactory.setWantClientAuth(false);
sslContextFactory.setValidatePeerCerts(false);
sslContextFactory.setKeyStorePassword("password");
sslContextFactory.setKeyStorePath(MockServer.class.getResource("mock-keystore.jks").toExternalForm());
sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory,
HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(https));
sslConnector.setPort(httpsPort);
server.setConnectors(new Connector[] {connector, sslConnector});
ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new AlwaysSuccessServlet()), "/*");
server.setHandler(context);
}
public void start() throws Exception {
server.start();
}
public void stop() throws Exception {
server.stop();
sslConnector.stop();
connector.stop();
}
} | 2,510 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/BaseMockServer.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.benchmark.utils;
import java.io.IOException;
import java.net.URI;
public abstract class BaseMockServer {
protected int httpPort;
protected int httpsPort;
public BaseMockServer() throws IOException {
httpPort = BenchmarkUtils.getUnusedPort();
httpsPort = BenchmarkUtils.getUnusedPort();
}
public URI getHttpUri() {
return URI.create(String.format("http://localhost:%s", httpPort));
}
public URI getHttpsUri() {
return URI.create(String.format("https://localhost:%s", httpsPort));
}
}
| 2,511 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientUpdateV1MapperComparisonBenchmark.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.model.UpdateItemResult;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Fork(2)
@State(Scope.Benchmark)
public class EnhancedClientUpdateV1MapperComparisonBenchmark {
private static final V2ItemFactory V2_ITEM_FACTORY = new V2ItemFactory();
private static final V1ItemFactory V1_ITEM_FACTORY = new V1ItemFactory();
private static final DynamoDBMapperConfig MAPPER_CONFIG =
DynamoDBMapperConfig.builder()
.withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.UPDATE)
.build();
@Benchmark
public void v2Update(TestState s) {
s.v2Table.updateItem(s.testItem.v2Bean);
}
@Benchmark
public void v1Update(TestState s) {
s.v1DdbMapper.save(s.testItem.v1Bean);
}
private static DynamoDbClient getV2Client(Blackhole bh, UpdateItemResponse updateItemResponse) {
return new V2TestDynamoDbUpdateItemClient(bh, updateItemResponse);
}
private static AmazonDynamoDB getV1Client(Blackhole bh, UpdateItemResult updateItemResult) {
return new V1TestDynamoDbUpdateItemClient(bh, updateItemResult);
}
@State(Scope.Benchmark)
public static class TestState {
@Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"})
public TestItem testItem;
private DynamoDbTable v2Table;
private DynamoDBMapper v1DdbMapper;
@Setup
public void setup(Blackhole bh) {
DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getV2Client(bh, testItem.v2UpdateItemResponse))
.build();
v2Table = v2DdbEnh.table(testItem.name(), testItem.schema);
v1DdbMapper = new DynamoDBMapper(getV1Client(bh, testItem.v1UpdateItemResult), MAPPER_CONFIG);
}
public enum TestItem {
TINY(
V2ItemFactory.TINY_BEAN_TABLE_SCHEMA,
V2_ITEM_FACTORY.tinyBean(),
UpdateItemResponse.builder().attributes(V2_ITEM_FACTORY.tiny()).build(),
V1_ITEM_FACTORY.v1TinyBean(),
new UpdateItemResult().withAttributes(V1_ITEM_FACTORY.tiny())
),
SMALL(
V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA,
V2_ITEM_FACTORY.smallBean(),
UpdateItemResponse.builder().attributes(V2_ITEM_FACTORY.small()).build(),
V1_ITEM_FACTORY.v1SmallBean(),
new UpdateItemResult().withAttributes(V1_ITEM_FACTORY.small())
),
HUGE(
V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA,
V2_ITEM_FACTORY.hugeBean(),
UpdateItemResponse.builder().attributes(V2_ITEM_FACTORY.huge()).build(),
V1_ITEM_FACTORY.v1hugeBean(),
new UpdateItemResult().withAttributes(V1_ITEM_FACTORY.huge())
),
HUGE_FLAT(
V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA,
V2_ITEM_FACTORY.hugeBeanFlat(),
UpdateItemResponse.builder().attributes(V2_ITEM_FACTORY.hugeFlat()).build(),
V1_ITEM_FACTORY.v1HugeBeanFlat(),
new UpdateItemResult().withAttributes(V1_ITEM_FACTORY.hugeFlat())
),
;
// V2
private TableSchema schema;
private Object v2Bean;
private UpdateItemResponse v2UpdateItemResponse;
// V1
private Object v1Bean;
private UpdateItemResult v1UpdateItemResult;
TestItem(TableSchema<?> schema,
Object v2Bean,
UpdateItemResponse v2UpdateItemResponse,
Object v1Bean,
UpdateItemResult v1UpdateItemResult) {
this.schema = schema;
this.v2Bean = v2Bean;
this.v2UpdateItemResponse = v2UpdateItemResponse;
this.v1Bean = v1Bean;
this.v1UpdateItemResult = v1UpdateItemResult;
}
}
}
}
| 2,512 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbUpdateItemClient.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.model.UpdateItemRequest;
import com.amazonaws.services.dynamodbv2.model.UpdateItemResult;
import org.openjdk.jmh.infra.Blackhole;
public class V1TestDynamoDbUpdateItemClient extends V1TestDynamoDbBaseClient {
private final UpdateItemResult updateItemResult;
public V1TestDynamoDbUpdateItemClient(Blackhole bh, UpdateItemResult updateItemResult) {
super(bh);
this.updateItemResult = updateItemResult;
}
@Override
public UpdateItemResult updateItem(UpdateItemRequest request) {
bh.consume(request);
return updateItemResult;
}
}
| 2,513 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/ItemFactory.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.benchmark.enhanced.dynamodb;
import com.amazonaws.util.ImmutableMapParameter;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import software.amazon.awssdk.core.SdkBytes;
abstract class ItemFactory<T> {
private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
private static final Random RNG = new Random();
public final Map<String, T> tiny() {
return asItem(tinyBean());
}
public final Map<String, T> small() {
return asItem(smallBean());
}
public final Map<String, T> huge() {
return asItem(hugeBean());
}
public final Map<String, T> hugeFlat() {
return asItem(hugeBeanFlat());
}
public final TinyBean tinyBean() {
TinyBean b = new TinyBean();
b.setStringAttr(randomS());
return b;
}
public final SmallBean smallBean() {
SmallBean b = new SmallBean();
b.setStringAttr(randomS());
b.setBinaryAttr(randomBytes());
b.setListAttr(Arrays.asList(randomS(), randomS(), randomS()));
return b;
}
public final HugeBean hugeBean() {
HugeBean b = new HugeBean();
b.setHashKey(randomS());
b.setStringAttr(randomS());
b.setBinaryAttr(randomBytes());
b.setListAttr(IntStream.range(0, 32).mapToObj(i -> randomS()).collect(Collectors.toList()));
Map<String, SdkBytes> mapAttr1 = new HashMap<>();
mapAttr1.put("key1", randomBytes());
mapAttr1.put("key2", randomBytes());
mapAttr1.put("key3", randomBytes());
b.setMapAttr1(mapAttr1);
Map<String, List<SdkBytes>> mapAttr2 = new HashMap<>();
mapAttr2.put("key1", Arrays.asList(randomBytes()));
mapAttr2.put("key2", IntStream.range(0, 2).mapToObj(i -> randomBytes()).collect(Collectors.toList()));
mapAttr2.put("key3", IntStream.range(0, 4).mapToObj(i -> randomBytes()).collect(Collectors.toList()));
mapAttr2.put("key4", IntStream.range(0, 8).mapToObj(i -> randomBytes()).collect(Collectors.toList()));
mapAttr2.put("key5", IntStream.range(0, 16).mapToObj(i -> randomBytes()).collect(Collectors.toList()));
b.setMapAttr2(mapAttr2);
ImmutableMapParameter.Builder<String, List<Map<String, List<SdkBytes>>>> mapAttr3Builder =
ImmutableMapParameter.builder();
List<Map<String, List<SdkBytes>>> value = Arrays.asList(
ImmutableMapParameter.<String, List<SdkBytes>>builder()
.put("key1", IntStream.range(0, 2).mapToObj(i -> randomBytes()).collect(Collectors.toList()))
.build(),
ImmutableMapParameter.<String, List<SdkBytes>>builder()
.put("key2", IntStream.range(0, 4).mapToObj(i -> randomBytes()).collect(Collectors.toList()))
.build(),
ImmutableMapParameter.<String, List<SdkBytes>>builder()
.put("key3", IntStream.range(0, 8).mapToObj(i -> randomBytes()).collect(Collectors.toList()))
.build()
);
mapAttr3Builder.put("key1", value)
.put("key2", value)
.build();
b.setMapAttr3(mapAttr3Builder.build());
return b;
}
public HugeBeanFlat hugeBeanFlat() {
HugeBeanFlat b = new HugeBeanFlat();
Class<HugeBeanFlat> clazz = HugeBeanFlat.class;
for (int i = 1; i <= 63; ++i) {
try {
Method setter = clazz.getMethod("setStringAttr" + i, String.class);
setter.setAccessible(true);
setter.invoke(b, randomS());
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
return b;
}
protected abstract Map<String, T> asItem(TinyBean b);
protected abstract Map<String, T> asItem(SmallBean b);
protected abstract Map<String, T> asItem(HugeBean b);
protected final Map<String, T> asItem(HugeBeanFlat b) {
Map<String, T> item = new HashMap<>();
Class<HugeBeanFlat> clazz = HugeBeanFlat.class;
for (int i = 1; i <= 63; ++i) {
try {
Method getter = clazz.getMethod("getStringAttr" + i);
getter.setAccessible(true);
item.put("stringAttr" + i, av((String) getter.invoke(b)));
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
return item;
}
protected abstract T av(String val);
protected abstract T av(List<T> val);
protected abstract T av(Map<String, T> val);
protected abstract T av(SdkBytes val);
private static String randomS(int len) {
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; ++i) {
sb.append(ALPHA.charAt(RNG.nextInt(ALPHA.length())));
}
return sb.toString();
}
private static String randomS() {
return randomS(16);
}
private static ByteBuffer randomB(int len) {
byte[] b = new byte[len];
RNG.nextBytes(b);
return ByteBuffer.wrap(b);
}
private static ByteBuffer randomB() {
return randomB(16);
}
private static SdkBytes randomBytes() {
return SdkBytes.fromByteBuffer(randomB());
}
public static class TinyBean {
private String stringAttr;
public String getStringAttr() {
return stringAttr;
}
public void setStringAttr(String stringAttr) {
this.stringAttr = stringAttr;
}
}
public static class SmallBean {
private String stringAttr;
private SdkBytes binaryAttr;
private List<String> listAttr;
public String getStringAttr() {
return stringAttr;
}
public void setStringAttr(String stringAttr) {
this.stringAttr = stringAttr;
}
public SdkBytes getBinaryAttr() {
return binaryAttr;
}
public void setBinaryAttr(SdkBytes binaryAttr) {
this.binaryAttr = binaryAttr;
}
public List<String> getListAttr() {
return listAttr;
}
public void setListAttr(List<String> listAttr) {
this.listAttr = listAttr;
}
}
public static class HugeBean {
private String hashKey;
private String stringAttr;
private SdkBytes binaryAttr;
private List<String> listAttr;
private Map<String, SdkBytes> mapAttr1;
private Map<String, List<SdkBytes>> mapAttr2;
private Map<String, List<Map<String, List<SdkBytes>>>> mapAttr3;
public String getHashKey() {
return hashKey;
}
public void setHashKey(String hashKey) {
this.hashKey = hashKey;
}
public String getStringAttr() {
return stringAttr;
}
public void setStringAttr(String stringAttr) {
this.stringAttr = stringAttr;
}
public SdkBytes getBinaryAttr() {
return binaryAttr;
}
public void setBinaryAttr(SdkBytes binaryAttr) {
this.binaryAttr = binaryAttr;
}
public List<String> getListAttr() {
return listAttr;
}
public void setListAttr(List<String> listAttr) {
this.listAttr = listAttr;
}
public Map<String, SdkBytes> getMapAttr1() {
return mapAttr1;
}
public void setMapAttr1(Map<String, SdkBytes> mapAttr1) {
this.mapAttr1 = mapAttr1;
}
public Map<String, List<SdkBytes>> getMapAttr2() {
return mapAttr2;
}
public void setMapAttr2(Map<String, List<SdkBytes>> mapAttr2) {
this.mapAttr2 = mapAttr2;
}
public Map<String, List<Map<String, List<SdkBytes>>>> getMapAttr3() {
return mapAttr3;
}
public void setMapAttr3(Map<String, List<Map<String, List<SdkBytes>>>> mapAttr3) {
this.mapAttr3 = mapAttr3;
}
}
public static class HugeBeanFlat {
private String stringAttr1;
private String stringAttr2;
private String stringAttr3;
private String stringAttr4;
private String stringAttr5;
private String stringAttr6;
private String stringAttr7;
private String stringAttr8;
private String stringAttr9;
private String stringAttr10;
private String stringAttr11;
private String stringAttr12;
private String stringAttr13;
private String stringAttr14;
private String stringAttr15;
private String stringAttr16;
private String stringAttr17;
private String stringAttr18;
private String stringAttr19;
private String stringAttr20;
private String stringAttr21;
private String stringAttr22;
private String stringAttr23;
private String stringAttr24;
private String stringAttr25;
private String stringAttr26;
private String stringAttr27;
private String stringAttr28;
private String stringAttr29;
private String stringAttr30;
private String stringAttr31;
private String stringAttr32;
private String stringAttr33;
private String stringAttr34;
private String stringAttr35;
private String stringAttr36;
private String stringAttr37;
private String stringAttr38;
private String stringAttr39;
private String stringAttr40;
private String stringAttr41;
private String stringAttr42;
private String stringAttr43;
private String stringAttr44;
private String stringAttr45;
private String stringAttr46;
private String stringAttr47;
private String stringAttr48;
private String stringAttr49;
private String stringAttr50;
private String stringAttr51;
private String stringAttr52;
private String stringAttr53;
private String stringAttr54;
private String stringAttr55;
private String stringAttr56;
private String stringAttr57;
private String stringAttr58;
private String stringAttr59;
private String stringAttr60;
private String stringAttr61;
private String stringAttr62;
private String stringAttr63;
public String getStringAttr1() {
return stringAttr1;
}
public void setStringAttr1(String stringAttr1) {
this.stringAttr1 = stringAttr1;
}
public String getStringAttr2() {
return stringAttr2;
}
public void setStringAttr2(String stringAttr2) {
this.stringAttr2 = stringAttr2;
}
public String getStringAttr3() {
return stringAttr3;
}
public void setStringAttr3(String stringAttr3) {
this.stringAttr3 = stringAttr3;
}
public String getStringAttr4() {
return stringAttr4;
}
public void setStringAttr4(String stringAttr4) {
this.stringAttr4 = stringAttr4;
}
public String getStringAttr5() {
return stringAttr5;
}
public void setStringAttr5(String stringAttr5) {
this.stringAttr5 = stringAttr5;
}
public String getStringAttr6() {
return stringAttr6;
}
public void setStringAttr6(String stringAttr6) {
this.stringAttr6 = stringAttr6;
}
public String getStringAttr7() {
return stringAttr7;
}
public void setStringAttr7(String stringAttr7) {
this.stringAttr7 = stringAttr7;
}
public String getStringAttr8() {
return stringAttr8;
}
public void setStringAttr8(String stringAttr8) {
this.stringAttr8 = stringAttr8;
}
public String getStringAttr9() {
return stringAttr9;
}
public void setStringAttr9(String stringAttr9) {
this.stringAttr9 = stringAttr9;
}
public String getStringAttr10() {
return stringAttr10;
}
public void setStringAttr10(String stringAttr10) {
this.stringAttr10 = stringAttr10;
}
public String getStringAttr11() {
return stringAttr11;
}
public void setStringAttr11(String stringAttr11) {
this.stringAttr11 = stringAttr11;
}
public String getStringAttr12() {
return stringAttr12;
}
public void setStringAttr12(String stringAttr12) {
this.stringAttr12 = stringAttr12;
}
public String getStringAttr13() {
return stringAttr13;
}
public void setStringAttr13(String stringAttr13) {
this.stringAttr13 = stringAttr13;
}
public String getStringAttr14() {
return stringAttr14;
}
public void setStringAttr14(String stringAttr14) {
this.stringAttr14 = stringAttr14;
}
public String getStringAttr15() {
return stringAttr15;
}
public void setStringAttr15(String stringAttr15) {
this.stringAttr15 = stringAttr15;
}
public String getStringAttr16() {
return stringAttr16;
}
public void setStringAttr16(String stringAttr16) {
this.stringAttr16 = stringAttr16;
}
public String getStringAttr17() {
return stringAttr17;
}
public void setStringAttr17(String stringAttr17) {
this.stringAttr17 = stringAttr17;
}
public String getStringAttr18() {
return stringAttr18;
}
public void setStringAttr18(String stringAttr18) {
this.stringAttr18 = stringAttr18;
}
public String getStringAttr19() {
return stringAttr19;
}
public void setStringAttr19(String stringAttr19) {
this.stringAttr19 = stringAttr19;
}
public String getStringAttr20() {
return stringAttr20;
}
public void setStringAttr20(String stringAttr20) {
this.stringAttr20 = stringAttr20;
}
public String getStringAttr21() {
return stringAttr21;
}
public void setStringAttr21(String stringAttr21) {
this.stringAttr21 = stringAttr21;
}
public String getStringAttr22() {
return stringAttr22;
}
public void setStringAttr22(String stringAttr22) {
this.stringAttr22 = stringAttr22;
}
public String getStringAttr23() {
return stringAttr23;
}
public void setStringAttr23(String stringAttr23) {
this.stringAttr23 = stringAttr23;
}
public String getStringAttr24() {
return stringAttr24;
}
public void setStringAttr24(String stringAttr24) {
this.stringAttr24 = stringAttr24;
}
public String getStringAttr25() {
return stringAttr25;
}
public void setStringAttr25(String stringAttr25) {
this.stringAttr25 = stringAttr25;
}
public String getStringAttr26() {
return stringAttr26;
}
public void setStringAttr26(String stringAttr26) {
this.stringAttr26 = stringAttr26;
}
public String getStringAttr27() {
return stringAttr27;
}
public void setStringAttr27(String stringAttr27) {
this.stringAttr27 = stringAttr27;
}
public String getStringAttr28() {
return stringAttr28;
}
public void setStringAttr28(String stringAttr28) {
this.stringAttr28 = stringAttr28;
}
public String getStringAttr29() {
return stringAttr29;
}
public void setStringAttr29(String stringAttr29) {
this.stringAttr29 = stringAttr29;
}
public String getStringAttr30() {
return stringAttr30;
}
public void setStringAttr30(String stringAttr30) {
this.stringAttr30 = stringAttr30;
}
public String getStringAttr31() {
return stringAttr31;
}
public void setStringAttr31(String stringAttr31) {
this.stringAttr31 = stringAttr31;
}
public String getStringAttr32() {
return stringAttr32;
}
public void setStringAttr32(String stringAttr32) {
this.stringAttr32 = stringAttr32;
}
public String getStringAttr33() {
return stringAttr33;
}
public void setStringAttr33(String stringAttr33) {
this.stringAttr33 = stringAttr33;
}
public String getStringAttr34() {
return stringAttr34;
}
public void setStringAttr34(String stringAttr34) {
this.stringAttr34 = stringAttr34;
}
public String getStringAttr35() {
return stringAttr35;
}
public void setStringAttr35(String stringAttr35) {
this.stringAttr35 = stringAttr35;
}
public String getStringAttr36() {
return stringAttr36;
}
public void setStringAttr36(String stringAttr36) {
this.stringAttr36 = stringAttr36;
}
public String getStringAttr37() {
return stringAttr37;
}
public void setStringAttr37(String stringAttr37) {
this.stringAttr37 = stringAttr37;
}
public String getStringAttr38() {
return stringAttr38;
}
public void setStringAttr38(String stringAttr38) {
this.stringAttr38 = stringAttr38;
}
public String getStringAttr39() {
return stringAttr39;
}
public void setStringAttr39(String stringAttr39) {
this.stringAttr39 = stringAttr39;
}
public String getStringAttr40() {
return stringAttr40;
}
public void setStringAttr40(String stringAttr40) {
this.stringAttr40 = stringAttr40;
}
public String getStringAttr41() {
return stringAttr41;
}
public void setStringAttr41(String stringAttr41) {
this.stringAttr41 = stringAttr41;
}
public String getStringAttr42() {
return stringAttr42;
}
public void setStringAttr42(String stringAttr42) {
this.stringAttr42 = stringAttr42;
}
public String getStringAttr43() {
return stringAttr43;
}
public void setStringAttr43(String stringAttr43) {
this.stringAttr43 = stringAttr43;
}
public String getStringAttr44() {
return stringAttr44;
}
public void setStringAttr44(String stringAttr44) {
this.stringAttr44 = stringAttr44;
}
public String getStringAttr45() {
return stringAttr45;
}
public void setStringAttr45(String stringAttr45) {
this.stringAttr45 = stringAttr45;
}
public String getStringAttr46() {
return stringAttr46;
}
public void setStringAttr46(String stringAttr46) {
this.stringAttr46 = stringAttr46;
}
public String getStringAttr47() {
return stringAttr47;
}
public void setStringAttr47(String stringAttr47) {
this.stringAttr47 = stringAttr47;
}
public String getStringAttr48() {
return stringAttr48;
}
public void setStringAttr48(String stringAttr48) {
this.stringAttr48 = stringAttr48;
}
public String getStringAttr49() {
return stringAttr49;
}
public void setStringAttr49(String stringAttr49) {
this.stringAttr49 = stringAttr49;
}
public String getStringAttr50() {
return stringAttr50;
}
public void setStringAttr50(String stringAttr50) {
this.stringAttr50 = stringAttr50;
}
public String getStringAttr51() {
return stringAttr51;
}
public void setStringAttr51(String stringAttr51) {
this.stringAttr51 = stringAttr51;
}
public String getStringAttr52() {
return stringAttr52;
}
public void setStringAttr52(String stringAttr52) {
this.stringAttr52 = stringAttr52;
}
public String getStringAttr53() {
return stringAttr53;
}
public void setStringAttr53(String stringAttr53) {
this.stringAttr53 = stringAttr53;
}
public String getStringAttr54() {
return stringAttr54;
}
public void setStringAttr54(String stringAttr54) {
this.stringAttr54 = stringAttr54;
}
public String getStringAttr55() {
return stringAttr55;
}
public void setStringAttr55(String stringAttr55) {
this.stringAttr55 = stringAttr55;
}
public String getStringAttr56() {
return stringAttr56;
}
public void setStringAttr56(String stringAttr56) {
this.stringAttr56 = stringAttr56;
}
public String getStringAttr57() {
return stringAttr57;
}
public void setStringAttr57(String stringAttr57) {
this.stringAttr57 = stringAttr57;
}
public String getStringAttr58() {
return stringAttr58;
}
public void setStringAttr58(String stringAttr58) {
this.stringAttr58 = stringAttr58;
}
public String getStringAttr59() {
return stringAttr59;
}
public void setStringAttr59(String stringAttr59) {
this.stringAttr59 = stringAttr59;
}
public String getStringAttr60() {
return stringAttr60;
}
public void setStringAttr60(String stringAttr60) {
this.stringAttr60 = stringAttr60;
}
public String getStringAttr61() {
return stringAttr61;
}
public void setStringAttr61(String stringAttr61) {
this.stringAttr61 = stringAttr61;
}
public String getStringAttr62() {
return stringAttr62;
}
public void setStringAttr62(String stringAttr62) {
this.stringAttr62 = stringAttr62;
}
public String getStringAttr63() {
return stringAttr63;
}
public void setStringAttr63(String stringAttr63) {
this.stringAttr63 = stringAttr63;
}
}
}
| 2,514 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbQueryClient.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.benchmark.enhanced.dynamodb;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.paginators.QueryIterable;
public final class V2TestDynamoDbQueryClient extends V2TestDynamoDbBaseClient {
private final QueryResponse queryResponse;
public V2TestDynamoDbQueryClient(Blackhole bh, QueryResponse queryResponse) {
super(bh);
this.queryResponse = queryResponse;
}
@Override
public QueryResponse query(QueryRequest queryRequest) {
bh.consume(queryRequest);
return this.queryResponse;
}
@Override
public QueryIterable queryPaginator(QueryRequest queryRequest) {
return new QueryIterable(this, queryRequest);
}
}
| 2,515 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbDeleteItemClient.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.model.DeleteItemRequest;
import com.amazonaws.services.dynamodbv2.model.DeleteItemResult;
import org.openjdk.jmh.infra.Blackhole;
public class V1TestDynamoDbDeleteItemClient extends V1TestDynamoDbBaseClient {
private static final DeleteItemResult DELETE_ITEM_RESULT = new DeleteItemResult();
public V1TestDynamoDbDeleteItemClient(Blackhole bh) {
super(bh);
}
@Override
public DeleteItemResult deleteItem(DeleteItemRequest request) {
bh.consume(request);
return DELETE_ITEM_RESULT;
}
}
| 2,516 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2ItemFactory.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.benchmark.enhanced.dynamodb;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import com.amazonaws.util.ImmutableMapParameter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
public final class V2ItemFactory extends ItemFactory<AttributeValue> {
public static final TableSchema<ItemFactory.TinyBean> TINY_BEAN_TABLE_SCHEMA =
TableSchema.builder(ItemFactory.TinyBean.class)
.newItemSupplier(ItemFactory.TinyBean::new)
.addAttribute(String.class, a -> a.name("stringAttr")
.getter(ItemFactory.TinyBean::getStringAttr)
.setter(ItemFactory.TinyBean::setStringAttr)
.tags(primaryPartitionKey()))
.build();
public static final TableSchema<ItemFactory.SmallBean> SMALL_BEAN_TABLE_SCHEMA =
TableSchema.builder(ItemFactory.SmallBean.class)
.newItemSupplier(ItemFactory.SmallBean::new)
.addAttribute(String.class, a -> a.name("stringAttr")
.getter(ItemFactory.SmallBean::getStringAttr)
.setter(ItemFactory.SmallBean::setStringAttr)
.tags(primaryPartitionKey()))
.addAttribute(SdkBytes.class, a -> a.name("binaryAttr")
.getter(ItemFactory.SmallBean::getBinaryAttr)
.setter(ItemFactory.SmallBean::setBinaryAttr))
.addAttribute(EnhancedType.listOf(String.class), a -> a.name("listAttr")
.getter(ItemFactory.SmallBean::getListAttr)
.setter(ItemFactory.SmallBean::setListAttr))
.build();
public static final TableSchema<ItemFactory.HugeBean> HUGE_BEAN_TABLE_SCHEMA =
TableSchema.builder(ItemFactory.HugeBean.class)
.newItemSupplier(ItemFactory.HugeBean::new)
.addAttribute(String.class, a -> a.name("stringAttr")
.getter(ItemFactory.HugeBean::getStringAttr)
.setter(ItemFactory.HugeBean::setStringAttr)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("hashKey")
.getter(ItemFactory.HugeBean::getHashKey)
.setter(ItemFactory.HugeBean::setHashKey))
.addAttribute(SdkBytes.class, a -> a.name("binaryAttr")
.getter(ItemFactory.HugeBean::getBinaryAttr)
.setter(ItemFactory.HugeBean::setBinaryAttr))
.addAttribute(EnhancedType.listOf(String.class), a -> a.name("listAttr")
.getter(ItemFactory.HugeBean::getListAttr)
.setter(ItemFactory.HugeBean::setListAttr))
.addAttribute(new EnhancedType<Map<String, SdkBytes>>() {
}, a -> a.name("mapAttr1")
.getter(ItemFactory.HugeBean::getMapAttr1)
.setter(ItemFactory.HugeBean::setMapAttr1))
.addAttribute(new EnhancedType<Map<String, List<SdkBytes>>>() {
}, a -> a.name("mapAttr2")
.getter(ItemFactory.HugeBean::getMapAttr2)
.setter(ItemFactory.HugeBean::setMapAttr2))
.addAttribute(new EnhancedType<Map<String, List<Map<String, List<SdkBytes>>>>>() {
}, a -> a.name("mapAttr3")
.getter(ItemFactory.HugeBean::getMapAttr3)
.setter(ItemFactory.HugeBean::setMapAttr3))
.build();
public static final TableSchema<ItemFactory.HugeBeanFlat> HUGE_BEAN_FLAT_TABLE_SCHEMA =
TableSchema.builder(ItemFactory.HugeBeanFlat.class)
.newItemSupplier(ItemFactory.HugeBeanFlat::new)
.addAttribute(String.class, a -> a.name("stringAttr")
.getter(ItemFactory.HugeBeanFlat::getStringAttr1)
.setter(ItemFactory.HugeBeanFlat::setStringAttr1)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("stringAttr2")
.getter(ItemFactory.HugeBeanFlat::getStringAttr2)
.setter(ItemFactory.HugeBeanFlat::setStringAttr2))
.addAttribute(String.class, a -> a.name("stringAttr3")
.getter(ItemFactory.HugeBeanFlat::getStringAttr3)
.setter(ItemFactory.HugeBeanFlat::setStringAttr3))
.addAttribute(String.class, a -> a.name("stringAttr4")
.getter(ItemFactory.HugeBeanFlat::getStringAttr4)
.setter(ItemFactory.HugeBeanFlat::setStringAttr4))
.addAttribute(String.class, a -> a.name("stringAttr5")
.getter(ItemFactory.HugeBeanFlat::getStringAttr5)
.setter(ItemFactory.HugeBeanFlat::setStringAttr5))
.addAttribute(String.class, a -> a.name("stringAttr6")
.getter(ItemFactory.HugeBeanFlat::getStringAttr6)
.setter(ItemFactory.HugeBeanFlat::setStringAttr6))
.addAttribute(String.class, a -> a.name("stringAttr7")
.getter(ItemFactory.HugeBeanFlat::getStringAttr7)
.setter(ItemFactory.HugeBeanFlat::setStringAttr7))
.addAttribute(String.class, a -> a.name("stringAttr8")
.getter(ItemFactory.HugeBeanFlat::getStringAttr8)
.setter(ItemFactory.HugeBeanFlat::setStringAttr8))
.addAttribute(String.class, a -> a.name("stringAttr9")
.getter(ItemFactory.HugeBeanFlat::getStringAttr9)
.setter(ItemFactory.HugeBeanFlat::setStringAttr9))
.addAttribute(String.class, a -> a.name("stringAttr10")
.getter(ItemFactory.HugeBeanFlat::getStringAttr10)
.setter(ItemFactory.HugeBeanFlat::setStringAttr10))
.addAttribute(String.class, a -> a.name("stringAttr11")
.getter(ItemFactory.HugeBeanFlat::getStringAttr11)
.setter(ItemFactory.HugeBeanFlat::setStringAttr11))
.addAttribute(String.class, a -> a.name("stringAttr12")
.getter(ItemFactory.HugeBeanFlat::getStringAttr12)
.setter(ItemFactory.HugeBeanFlat::setStringAttr12))
.addAttribute(String.class, a -> a.name("stringAttr13")
.getter(ItemFactory.HugeBeanFlat::getStringAttr13)
.setter(ItemFactory.HugeBeanFlat::setStringAttr13))
.addAttribute(String.class, a -> a.name("stringAttr14")
.getter(ItemFactory.HugeBeanFlat::getStringAttr14)
.setter(ItemFactory.HugeBeanFlat::setStringAttr14))
.addAttribute(String.class, a -> a.name("stringAttr15")
.getter(ItemFactory.HugeBeanFlat::getStringAttr15)
.setter(ItemFactory.HugeBeanFlat::setStringAttr15))
.addAttribute(String.class, a -> a.name("stringAttr16")
.getter(ItemFactory.HugeBeanFlat::getStringAttr16)
.setter(ItemFactory.HugeBeanFlat::setStringAttr16))
.addAttribute(String.class, a -> a.name("stringAttr17")
.getter(ItemFactory.HugeBeanFlat::getStringAttr17)
.setter(ItemFactory.HugeBeanFlat::setStringAttr17))
.addAttribute(String.class, a -> a.name("stringAttr18")
.getter(ItemFactory.HugeBeanFlat::getStringAttr18)
.setter(ItemFactory.HugeBeanFlat::setStringAttr18))
.addAttribute(String.class, a -> a.name("stringAttr19")
.getter(ItemFactory.HugeBeanFlat::getStringAttr19)
.setter(ItemFactory.HugeBeanFlat::setStringAttr19))
.addAttribute(String.class, a -> a.name("stringAttr20")
.getter(ItemFactory.HugeBeanFlat::getStringAttr20)
.setter(ItemFactory.HugeBeanFlat::setStringAttr20))
.addAttribute(String.class, a -> a.name("stringAttr21")
.getter(ItemFactory.HugeBeanFlat::getStringAttr21)
.setter(ItemFactory.HugeBeanFlat::setStringAttr21))
.addAttribute(String.class, a -> a.name("stringAttr22")
.getter(ItemFactory.HugeBeanFlat::getStringAttr22)
.setter(ItemFactory.HugeBeanFlat::setStringAttr22))
.addAttribute(String.class, a -> a.name("stringAttr23")
.getter(ItemFactory.HugeBeanFlat::getStringAttr23)
.setter(ItemFactory.HugeBeanFlat::setStringAttr23))
.addAttribute(String.class, a -> a.name("stringAttr24")
.getter(ItemFactory.HugeBeanFlat::getStringAttr24)
.setter(ItemFactory.HugeBeanFlat::setStringAttr24))
.addAttribute(String.class, a -> a.name("stringAttr25")
.getter(ItemFactory.HugeBeanFlat::getStringAttr25)
.setter(ItemFactory.HugeBeanFlat::setStringAttr25))
.addAttribute(String.class, a -> a.name("stringAttr26")
.getter(ItemFactory.HugeBeanFlat::getStringAttr26)
.setter(ItemFactory.HugeBeanFlat::setStringAttr26))
.addAttribute(String.class, a -> a.name("stringAttr27")
.getter(ItemFactory.HugeBeanFlat::getStringAttr27)
.setter(ItemFactory.HugeBeanFlat::setStringAttr27))
.addAttribute(String.class, a -> a.name("stringAttr28")
.getter(ItemFactory.HugeBeanFlat::getStringAttr28)
.setter(ItemFactory.HugeBeanFlat::setStringAttr28))
.addAttribute(String.class, a -> a.name("stringAttr29")
.getter(ItemFactory.HugeBeanFlat::getStringAttr29)
.setter(ItemFactory.HugeBeanFlat::setStringAttr29))
.addAttribute(String.class, a -> a.name("stringAttr30")
.getter(ItemFactory.HugeBeanFlat::getStringAttr30)
.setter(ItemFactory.HugeBeanFlat::setStringAttr30))
.addAttribute(String.class, a -> a.name("stringAttr31")
.getter(ItemFactory.HugeBeanFlat::getStringAttr31)
.setter(ItemFactory.HugeBeanFlat::setStringAttr31))
.addAttribute(String.class, a -> a.name("stringAttr32")
.getter(ItemFactory.HugeBeanFlat::getStringAttr32)
.setter(ItemFactory.HugeBeanFlat::setStringAttr32))
.addAttribute(String.class, a -> a.name("stringAttr33")
.getter(ItemFactory.HugeBeanFlat::getStringAttr33)
.setter(ItemFactory.HugeBeanFlat::setStringAttr33))
.addAttribute(String.class, a -> a.name("stringAttr34")
.getter(ItemFactory.HugeBeanFlat::getStringAttr34)
.setter(ItemFactory.HugeBeanFlat::setStringAttr34))
.addAttribute(String.class, a -> a.name("stringAttr35")
.getter(ItemFactory.HugeBeanFlat::getStringAttr35)
.setter(ItemFactory.HugeBeanFlat::setStringAttr35))
.addAttribute(String.class, a -> a.name("stringAttr36")
.getter(ItemFactory.HugeBeanFlat::getStringAttr36)
.setter(ItemFactory.HugeBeanFlat::setStringAttr36))
.addAttribute(String.class, a -> a.name("stringAttr37")
.getter(ItemFactory.HugeBeanFlat::getStringAttr37)
.setter(ItemFactory.HugeBeanFlat::setStringAttr37))
.addAttribute(String.class, a -> a.name("stringAttr38")
.getter(ItemFactory.HugeBeanFlat::getStringAttr38)
.setter(ItemFactory.HugeBeanFlat::setStringAttr38))
.addAttribute(String.class, a -> a.name("stringAttr39")
.getter(ItemFactory.HugeBeanFlat::getStringAttr39)
.setter(ItemFactory.HugeBeanFlat::setStringAttr39))
.addAttribute(String.class, a -> a.name("stringAttr40")
.getter(ItemFactory.HugeBeanFlat::getStringAttr40)
.setter(ItemFactory.HugeBeanFlat::setStringAttr40))
.addAttribute(String.class, a -> a.name("stringAttr41")
.getter(ItemFactory.HugeBeanFlat::getStringAttr41)
.setter(ItemFactory.HugeBeanFlat::setStringAttr41))
.addAttribute(String.class, a -> a.name("stringAttr42")
.getter(ItemFactory.HugeBeanFlat::getStringAttr42)
.setter(ItemFactory.HugeBeanFlat::setStringAttr42))
.addAttribute(String.class, a -> a.name("stringAttr43")
.getter(ItemFactory.HugeBeanFlat::getStringAttr43)
.setter(ItemFactory.HugeBeanFlat::setStringAttr43))
.addAttribute(String.class, a -> a.name("stringAttr44")
.getter(ItemFactory.HugeBeanFlat::getStringAttr44)
.setter(ItemFactory.HugeBeanFlat::setStringAttr44))
.addAttribute(String.class, a -> a.name("stringAttr45")
.getter(ItemFactory.HugeBeanFlat::getStringAttr45)
.setter(ItemFactory.HugeBeanFlat::setStringAttr45))
.addAttribute(String.class, a -> a.name("stringAttr46")
.getter(ItemFactory.HugeBeanFlat::getStringAttr46)
.setter(ItemFactory.HugeBeanFlat::setStringAttr46))
.addAttribute(String.class, a -> a.name("stringAttr47")
.getter(ItemFactory.HugeBeanFlat::getStringAttr47)
.setter(ItemFactory.HugeBeanFlat::setStringAttr47))
.addAttribute(String.class, a -> a.name("stringAttr48")
.getter(ItemFactory.HugeBeanFlat::getStringAttr48)
.setter(ItemFactory.HugeBeanFlat::setStringAttr48))
.addAttribute(String.class, a -> a.name("stringAttr49")
.getter(ItemFactory.HugeBeanFlat::getStringAttr49)
.setter(ItemFactory.HugeBeanFlat::setStringAttr49))
.addAttribute(String.class, a -> a.name("stringAttr50")
.getter(ItemFactory.HugeBeanFlat::getStringAttr50)
.setter(ItemFactory.HugeBeanFlat::setStringAttr50))
.addAttribute(String.class, a -> a.name("stringAttr51")
.getter(ItemFactory.HugeBeanFlat::getStringAttr51)
.setter(ItemFactory.HugeBeanFlat::setStringAttr51))
.addAttribute(String.class, a -> a.name("stringAttr52")
.getter(ItemFactory.HugeBeanFlat::getStringAttr52)
.setter(ItemFactory.HugeBeanFlat::setStringAttr52))
.addAttribute(String.class, a -> a.name("stringAttr53")
.getter(ItemFactory.HugeBeanFlat::getStringAttr53)
.setter(ItemFactory.HugeBeanFlat::setStringAttr53))
.addAttribute(String.class, a -> a.name("stringAttr54")
.getter(ItemFactory.HugeBeanFlat::getStringAttr54)
.setter(ItemFactory.HugeBeanFlat::setStringAttr54))
.addAttribute(String.class, a -> a.name("stringAttr55")
.getter(ItemFactory.HugeBeanFlat::getStringAttr55)
.setter(ItemFactory.HugeBeanFlat::setStringAttr55))
.addAttribute(String.class, a -> a.name("stringAttr56")
.getter(ItemFactory.HugeBeanFlat::getStringAttr56)
.setter(ItemFactory.HugeBeanFlat::setStringAttr56))
.addAttribute(String.class, a -> a.name("stringAttr57")
.getter(ItemFactory.HugeBeanFlat::getStringAttr57)
.setter(ItemFactory.HugeBeanFlat::setStringAttr57))
.addAttribute(String.class, a -> a.name("stringAttr58")
.getter(ItemFactory.HugeBeanFlat::getStringAttr58)
.setter(ItemFactory.HugeBeanFlat::setStringAttr58))
.addAttribute(String.class, a -> a.name("stringAttr59")
.getter(ItemFactory.HugeBeanFlat::getStringAttr59)
.setter(ItemFactory.HugeBeanFlat::setStringAttr59))
.addAttribute(String.class, a -> a.name("stringAttr60")
.getter(ItemFactory.HugeBeanFlat::getStringAttr60)
.setter(ItemFactory.HugeBeanFlat::setStringAttr60))
.addAttribute(String.class, a -> a.name("stringAttr61")
.getter(ItemFactory.HugeBeanFlat::getStringAttr61)
.setter(ItemFactory.HugeBeanFlat::setStringAttr61))
.addAttribute(String.class, a -> a.name("stringAttr62")
.getter(ItemFactory.HugeBeanFlat::getStringAttr62)
.setter(ItemFactory.HugeBeanFlat::setStringAttr62))
.addAttribute(String.class, a -> a.name("stringAttr63")
.getter(ItemFactory.HugeBeanFlat::getStringAttr63)
.setter(ItemFactory.HugeBeanFlat::setStringAttr63))
.build();
@Override
protected Map<String, AttributeValue> asItem(TinyBean b) {
ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder();
builder.put("stringAttr", av(b.getStringAttr()));
return builder.build();
}
@Override
protected Map<String, AttributeValue> asItem(SmallBean b) {
ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder();
builder.put("stringAttr", av(b.getStringAttr()));
builder.put("binaryAttr", av(b.getBinaryAttr()));
List<AttributeValue> listAttr = b.getListAttr().stream().map(this::av).collect(Collectors.toList());
builder.put("listAttr", av(listAttr));
return builder.build();
}
@Override
protected Map<String, AttributeValue> asItem(HugeBean b) {
ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder();
builder.put("hashKey", av(b.getHashKey()));
builder.put("stringAttr", av(b.getStringAttr()));
builder.put("binaryAttr", av(b.getBinaryAttr()));
List<AttributeValue> listAttr = b.getListAttr().stream().map(this::av).collect(Collectors.toList());
builder.put("listAttr", av(listAttr));
Map<String, AttributeValue> mapAttr1 = b.getMapAttr1().entrySet().stream().collect(
Collectors.toMap(Map.Entry::getKey,
e -> av(e.getValue())));
builder.put("mapAttr1", av(mapAttr1));
Map<String, AttributeValue> mapAttr2 = b.getMapAttr2().entrySet().stream().collect(
Collectors.toMap(Map.Entry::getKey,
e -> av(e.getValue().stream().map(this::av).collect(Collectors.toList()))));
builder.put("mapAttr2", av(mapAttr2));
Map<String, AttributeValue> mapAttr3 = b.getMapAttr3().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
e -> {
List<Map<String, List<SdkBytes>>> value = e.getValue();
AttributeValue valueAv = av(value.stream().map(m -> av(m.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
ee -> av(ee.getValue().stream().map(this::av).collect(Collectors.toList()))))))
.collect(Collectors.toList()));
return valueAv;
}));
builder.put("mapAttr3", av(mapAttr3));
return builder.build();
}
@Override
protected AttributeValue av(String val) {
return AttributeValue.builder().s(val).build();
}
@Override
protected AttributeValue av(List<AttributeValue> val) {
return AttributeValue.builder().l(val).build();
}
@Override
protected AttributeValue av(Map<String, AttributeValue> val) {
return AttributeValue.builder().m(val).build();
}
@Override
protected AttributeValue av(SdkBytes val) {
return AttributeValue.builder().b(val).build();
}
}
| 2,517 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbDeleteItemClient.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.benchmark.enhanced.dynamodb;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
public final class V2TestDynamoDbDeleteItemClient extends V2TestDynamoDbBaseClient {
private static final DeleteItemResponse DELETE_ITEM_RESPONSE = DeleteItemResponse.builder().build();
public V2TestDynamoDbDeleteItemClient(Blackhole bh) {
super(bh);
}
@Override
public DeleteItemResponse deleteItem(DeleteItemRequest deleteItemRequest) {
bh.consume(deleteItemRequest);
return DELETE_ITEM_RESPONSE;
}
}
| 2,518 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientPutV1MapperComparisonBenchmark.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Fork(2)
@State(Scope.Benchmark)
public class EnhancedClientPutV1MapperComparisonBenchmark {
private static final V2ItemFactory V2_ITEM_FACTORY = new V2ItemFactory();
private static final V1ItemFactory V1_ITEM_FACTORY = new V1ItemFactory();
private static final DynamoDBMapperConfig MAPPER_CONFIG =
DynamoDBMapperConfig.builder()
.withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.PUT)
.build();
@Benchmark
public void v2Put(TestState s) {
s.v2Table.putItem(s.testItem.v2Bean);
}
@Benchmark
public void v1Put(TestState s) {
s.v1DdbMapper.save(s.testItem.v1Bean);
}
private static DynamoDbClient getV2Client(Blackhole bh) {
return new V2TestDynamoDbPutItemClient(bh);
}
private static AmazonDynamoDB getV1Client(Blackhole bh) {
return new V1TestDynamoDbPutItemClient(bh);
}
@State(Scope.Benchmark)
public static class TestState {
@Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"})
public TestItem testItem;
private DynamoDbTable v2Table;
private DynamoDBMapper v1DdbMapper;
@Setup
public void setup(Blackhole bh) {
DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getV2Client(bh))
.build();
v2Table = v2DdbEnh.table(testItem.name(), testItem.schema);
v1DdbMapper = new DynamoDBMapper(getV1Client(bh), MAPPER_CONFIG);
}
public enum TestItem {
TINY(
V2ItemFactory.TINY_BEAN_TABLE_SCHEMA,
V2_ITEM_FACTORY.tinyBean(),
V1_ITEM_FACTORY.v1TinyBean()
),
SMALL(
V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA,
V2_ITEM_FACTORY.smallBean(),
V1_ITEM_FACTORY.v1SmallBean()
),
HUGE(
V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA,
V2_ITEM_FACTORY.hugeBean(),
V1_ITEM_FACTORY.v1hugeBean()
),
HUGE_FLAT(
V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA,
V2_ITEM_FACTORY.hugeBeanFlat(),
V1_ITEM_FACTORY.v1HugeBeanFlat()
),
;
// V2
private TableSchema<?> schema;
private Object v2Bean;
// V1
private Object v1Bean;
TestItem(TableSchema<?> schema,
Object v2Bean,
Object v1Bean) {
this.schema = schema;
this.v2Bean = v2Bean;
this.v1Bean = v1Bean;
}
}
}
}
| 2,519 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbPutItemClient.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.model.PutItemRequest;
import com.amazonaws.services.dynamodbv2.model.PutItemResult;
import org.openjdk.jmh.infra.Blackhole;
public class V1TestDynamoDbPutItemClient extends V1TestDynamoDbBaseClient {
private static final PutItemResult PUT_ITEM_RESULT = new PutItemResult();
public V1TestDynamoDbPutItemClient(Blackhole bh) {
super(bh);
}
@Override
public PutItemResult putItem(PutItemRequest request) {
bh.consume(request);
return PUT_ITEM_RESULT;
}
}
| 2,520 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbGetItemClient.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.model.GetItemRequest;
import com.amazonaws.services.dynamodbv2.model.GetItemResult;
import org.openjdk.jmh.infra.Blackhole;
public class V1TestDynamoDbGetItemClient extends V1TestDynamoDbBaseClient {
private final GetItemResult getItemResult;
public V1TestDynamoDbGetItemClient(Blackhole bh, GetItemResult getItemResult) {
super(bh);
this.getItemResult = getItemResult;
}
@Override
public GetItemResult getItem(GetItemRequest request) {
bh.consume(request);
return getItemResult;
}
}
| 2,521 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbBaseClient.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.AbstractAmazonDynamoDB;
import org.openjdk.jmh.infra.Blackhole;
abstract class V1TestDynamoDbBaseClient extends AbstractAmazonDynamoDB {
protected final Blackhole bh;
protected V1TestDynamoDbBaseClient(Blackhole bh) {
this.bh = bh;
}
}
| 2,522 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbScanClient.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.benchmark.enhanced.dynamodb;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
import software.amazon.awssdk.services.dynamodb.paginators.ScanIterable;
public final class V2TestDynamoDbScanClient extends V2TestDynamoDbBaseClient {
private final ScanResponse scanResponse;
public V2TestDynamoDbScanClient(Blackhole bh, ScanResponse scanResponse) {
super(bh);
this.scanResponse = scanResponse;
}
@Override
public ScanResponse scan(ScanRequest scanRequest) {
bh.consume(scanRequest);
return this.scanResponse;
}
@Override
public ScanIterable scanPaginator(ScanRequest scanRequest) {
return new ScanIterable(this, scanRequest);
}
}
| 2,523 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbUpdateItemClient.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.benchmark.enhanced.dynamodb;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
public final class V2TestDynamoDbUpdateItemClient extends V2TestDynamoDbBaseClient {
private final UpdateItemResponse updateItemResponse;
public V2TestDynamoDbUpdateItemClient(Blackhole bh, UpdateItemResponse updateItemResponse) {
super(bh);
this.updateItemResponse = updateItemResponse;
}
@Override
public UpdateItemResponse updateItem(UpdateItemRequest updateItemRequest) {
bh.consume(updateItemRequest);
return this.updateItemResponse;
}
}
| 2,524 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbGetItemClient.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.benchmark.enhanced.dynamodb;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
public final class V2TestDynamoDbGetItemClient extends V2TestDynamoDbBaseClient {
private final GetItemResponse getItemResponse;
public V2TestDynamoDbGetItemClient(Blackhole bh, GetItemResponse getItemResponse) {
super(bh);
this.getItemResponse = getItemResponse;
}
@Override
public GetItemResponse getItem(GetItemRequest getItemRequest) {
bh.consume(getItemRequest);
return getItemResponse;
}
}
| 2,525 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1ItemFactory.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.util.ImmutableMapParameter;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import software.amazon.awssdk.core.SdkBytes;
public final class V1ItemFactory extends ItemFactory<AttributeValue> {
public V1HugeBean v1hugeBean() {
return V1HugeBean.fromHugeBean(super.hugeBean());
}
public V1TinyBean v1TinyBean() {
return V1TinyBean.fromTinyBean(super.tinyBean());
}
public V1SmallBean v1SmallBean() {
return V1SmallBean.fromSmallBean(super.smallBean());
}
public V1HugeBeanFlat v1HugeBeanFlat() {
return V1HugeBeanFlat.fromHugeBeanFlat(super.hugeBeanFlat());
}
@Override
protected Map<String, AttributeValue> asItem(TinyBean b) {
ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder();
builder.put("stringAttr", av(b.getStringAttr()));
return builder.build();
}
@Override
protected Map<String, AttributeValue> asItem(SmallBean b) {
ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder();
builder.put("stringAttr", av(b.getStringAttr()));
builder.put("binaryAttr", av(b.getBinaryAttr()));
List<AttributeValue> listAttr = b.getListAttr().stream().map(this::av).collect(Collectors.toList());
builder.put("listAttr", av(listAttr));
return builder.build();
}
@Override
protected Map<String, AttributeValue> asItem(HugeBean b) {
ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder();
builder.put("hashKey", av(b.getHashKey()));
builder.put("stringAttr", av(b.getStringAttr()));
builder.put("binaryAttr", av(b.getBinaryAttr()));
List<AttributeValue> listAttr = b.getListAttr().stream().map(this::av).collect(Collectors.toList());
builder.put("listAttr", av(listAttr));
Map<String, AttributeValue> mapAttr1 = b.getMapAttr1().entrySet().stream().collect(
Collectors.toMap(Map.Entry::getKey,
e -> av(e.getValue())));
builder.put("mapAttr1", av(mapAttr1));
Map<String, AttributeValue> mapAttr2 = b.getMapAttr2().entrySet().stream().collect(
Collectors.toMap(Map.Entry::getKey,
e -> av(e.getValue().stream().map(this::av).collect(Collectors.toList()))));
builder.put("mapAttr2", av(mapAttr2));
Map<String, AttributeValue> mapAttr3 = b.getMapAttr3().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
e -> {
List<Map<String, List<SdkBytes>>> value = e.getValue();
AttributeValue valueAv = av(value.stream().map(m -> av(m.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
ee -> av(ee.getValue().stream().map(this::av).collect(Collectors.toList()))))))
.collect(Collectors.toList()));
return valueAv;
}));
builder.put("mapAttr3", av(mapAttr3));
return builder.build();
}
@Override
protected AttributeValue av(String val) {
return new AttributeValue()
.withS(val);
}
@Override
protected AttributeValue av(List<AttributeValue> val) {
return new AttributeValue()
.withL(val);
}
@Override
protected AttributeValue av(Map<String, AttributeValue> val) {
return new AttributeValue()
.withM(val);
}
@Override
protected AttributeValue av(SdkBytes val) {
return new AttributeValue()
.withB(val.asByteBuffer());
}
@DynamoDBTable(tableName = "V1TinyBean")
public static class V1TinyBean extends ItemFactory.TinyBean {
public V1TinyBean() {
}
public V1TinyBean(String stringAttr) {
super.setStringAttr(stringAttr);
}
@DynamoDBHashKey
@Override
public String getStringAttr() {
return super.getStringAttr();
}
private static V1TinyBean fromTinyBean(TinyBean tb) {
V1TinyBean b = new V1TinyBean();
b.setStringAttr(tb.getStringAttr());
return b;
}
}
@DynamoDBTable(tableName = "V1SmallBean")
public static class V1SmallBean extends ItemFactory.SmallBean {
private ByteBuffer binaryAttr;
public V1SmallBean() {
}
public V1SmallBean(String stringAttr) {
super.setStringAttr(stringAttr);
}
@DynamoDBHashKey
@Override
public String getStringAttr() {
return super.getStringAttr();
}
@DynamoDBAttribute(attributeName = "binaryAttr")
public ByteBuffer getBinaryAttrV1() {
return binaryAttr;
}
@DynamoDBAttribute(attributeName = "binaryAttr")
public void setBinaryAttrV1(ByteBuffer binaryAttr) {
this.binaryAttr = binaryAttr;
}
@DynamoDBAttribute
@Override
public List<String> getListAttr() {
return super.getListAttr();
}
private static V1SmallBean fromSmallBean(SmallBean sb) {
V1SmallBean b = new V1SmallBean();
b.setStringAttr(sb.getStringAttr());
b.setBinaryAttrV1(sb.getBinaryAttr().asByteBuffer());
b.setListAttr(sb.getListAttr());
return b;
}
}
@DynamoDBTable(tableName = "V1HugeBean")
public static class V1HugeBean extends ItemFactory.HugeBean {
private ByteBuffer binaryAttr;
private Map<String, ByteBuffer> mapAttr1;
private Map<String, List<ByteBuffer>> mapAttr2;
private Map<String, List<Map<String, List<ByteBuffer>>>> mapAttr3;
public V1HugeBean() {
}
public V1HugeBean(String stringAttr) {
super.setStringAttr(stringAttr);
}
@DynamoDBHashKey
@Override
public String getStringAttr() {
return super.getStringAttr();
}
@DynamoDBAttribute
@Override
public String getHashKey() {
return super.getHashKey();
}
@DynamoDBAttribute(attributeName = "binaryAttr")
public ByteBuffer getBinaryAttrV1() {
return binaryAttr;
}
@DynamoDBAttribute(attributeName = "binaryAttr")
public void setBinaryAttrV1(ByteBuffer binaryAttr) {
this.binaryAttr = binaryAttr;
}
@DynamoDBAttribute
@Override
public List<String> getListAttr() {
return super.getListAttr();
}
@DynamoDBAttribute(attributeName = "mapAttr1")
public Map<String, ByteBuffer> getMapAttr1V1() {
return mapAttr1;
}
@DynamoDBAttribute(attributeName = "mapAttr1")
public void setMapAttr1V1(Map<String, ByteBuffer> mapAttr1) {
this.mapAttr1 = mapAttr1;
}
@DynamoDBAttribute(attributeName = "mapAttr2")
public Map<String, List<ByteBuffer>> getMapAttr2V1() {
return mapAttr2;
}
@DynamoDBAttribute(attributeName = "mapAttr2")
public void setMapAttr2V1(Map<String, List<ByteBuffer>> mapAttr2) {
this.mapAttr2 = mapAttr2;
}
@DynamoDBAttribute(attributeName = "mapAttr3")
public Map<String, List<Map<String, List<ByteBuffer>>>> getMapAttr3V1() {
return mapAttr3;
}
@DynamoDBAttribute(attributeName = "mapAttr3")
public void setMapAttr3V1(Map<String, List<Map<String, List<ByteBuffer>>>> mapAttr3) {
this.mapAttr3 = mapAttr3;
}
private static V1HugeBean fromHugeBean(HugeBean hb) {
V1HugeBean b = new V1HugeBean();
b.setHashKey(hb.getHashKey());
b.setStringAttr(hb.getStringAttr());
b.setBinaryAttrV1(hb.getBinaryAttr().asByteBuffer());
b.setListAttr(hb.getListAttr());
b.setMapAttr1V1(hb.getMapAttr1()
.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().asByteBuffer())));
b.setMapAttr2V1(hb.getMapAttr2()
.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().stream().map(SdkBytes::asByteBuffer).collect(Collectors.toList()))));
Map<String, List<Map<String, List<ByteBuffer>>>> mapAttr3V1 = hb.getMapAttr3()
.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream()
.map(m -> m.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, ee ->
ee.getValue().stream().map(SdkBytes::asByteBuffer).collect(Collectors.toList())
)))
.collect(Collectors.toList())));
b.setMapAttr3V1(mapAttr3V1);
return b;
}
}
@DynamoDBTable(tableName = "V1HugeBeanFlat")
public static class V1HugeBeanFlat extends HugeBeanFlat {
public V1HugeBeanFlat() {
}
public V1HugeBeanFlat(String stringAttr) {
this.setStringAttr1(stringAttr);
}
@DynamoDBAttribute(attributeName = "stringAttr1")
@DynamoDBHashKey
@Override
public String getStringAttr1() {
return super.getStringAttr1();
}
@DynamoDBAttribute(attributeName = "stringAttr2")
@Override
public String getStringAttr2() {
return super.getStringAttr2();
}
@DynamoDBAttribute(attributeName = "stringAttr3")
@Override
public String getStringAttr3() {
return super.getStringAttr3();
}
@DynamoDBAttribute(attributeName = "stringAttr4")
@Override
public String getStringAttr4() {
return super.getStringAttr4();
}
@DynamoDBAttribute(attributeName = "stringAttr5")
@Override
public String getStringAttr5() {
return super.getStringAttr5();
}
@DynamoDBAttribute(attributeName = "stringAttr6")
@Override
public String getStringAttr6() {
return super.getStringAttr6();
}
@DynamoDBAttribute(attributeName = "stringAttr7")
@Override
public String getStringAttr7() {
return super.getStringAttr7();
}
@DynamoDBAttribute(attributeName = "stringAttr8")
@Override
public String getStringAttr8() {
return super.getStringAttr8();
}
@DynamoDBAttribute(attributeName = "stringAttr9")
@Override
public String getStringAttr9() {
return super.getStringAttr9();
}
@DynamoDBAttribute(attributeName = "stringAttr10")
@Override
public String getStringAttr10() {
return super.getStringAttr10();
}
@DynamoDBAttribute(attributeName = "stringAttr11")
@Override
public String getStringAttr11() {
return super.getStringAttr11();
}
@DynamoDBAttribute(attributeName = "stringAttr12")
@Override
public String getStringAttr12() {
return super.getStringAttr12();
}
@DynamoDBAttribute(attributeName = "stringAttr13")
@Override
public String getStringAttr13() {
return super.getStringAttr13();
}
@DynamoDBAttribute(attributeName = "stringAttr14")
@Override
public String getStringAttr14() {
return super.getStringAttr14();
}
@DynamoDBAttribute(attributeName = "stringAttr15")
@Override
public String getStringAttr15() {
return super.getStringAttr15();
}
@DynamoDBAttribute(attributeName = "stringAttr16")
@Override
public String getStringAttr16() {
return super.getStringAttr16();
}
@DynamoDBAttribute(attributeName = "stringAttr17")
@Override
public String getStringAttr17() {
return super.getStringAttr17();
}
@DynamoDBAttribute(attributeName = "stringAttr18")
@Override
public String getStringAttr18() {
return super.getStringAttr18();
}
@DynamoDBAttribute(attributeName = "stringAttr19")
@Override
public String getStringAttr19() {
return super.getStringAttr19();
}
@DynamoDBAttribute(attributeName = "stringAttr20")
@Override
public String getStringAttr20() {
return super.getStringAttr20();
}
@DynamoDBAttribute(attributeName = "stringAttr21")
@Override
public String getStringAttr21() {
return super.getStringAttr21();
}
@DynamoDBAttribute(attributeName = "stringAttr22")
@Override
public String getStringAttr22() {
return super.getStringAttr22();
}
@DynamoDBAttribute(attributeName = "stringAttr23")
@Override
public String getStringAttr23() {
return super.getStringAttr23();
}
@DynamoDBAttribute(attributeName = "stringAttr24")
@Override
public String getStringAttr24() {
return super.getStringAttr24();
}
@DynamoDBAttribute(attributeName = "stringAttr25")
@Override
public String getStringAttr25() {
return super.getStringAttr25();
}
@DynamoDBAttribute(attributeName = "stringAttr26")
@Override
public String getStringAttr26() {
return super.getStringAttr26();
}
@DynamoDBAttribute(attributeName = "stringAttr27")
@Override
public String getStringAttr27() {
return super.getStringAttr27();
}
@DynamoDBAttribute(attributeName = "stringAttr28")
@Override
public String getStringAttr28() {
return super.getStringAttr28();
}
@DynamoDBAttribute(attributeName = "stringAttr29")
@Override
public String getStringAttr29() {
return super.getStringAttr29();
}
@DynamoDBAttribute(attributeName = "stringAttr30")
@Override
public String getStringAttr30() {
return super.getStringAttr30();
}
@DynamoDBAttribute(attributeName = "stringAttr31")
@Override
public String getStringAttr31() {
return super.getStringAttr31();
}
@DynamoDBAttribute(attributeName = "stringAttr32")
@Override
public String getStringAttr32() {
return super.getStringAttr32();
}
@DynamoDBAttribute(attributeName = "stringAttr33")
@Override
public String getStringAttr33() {
return super.getStringAttr33();
}
@DynamoDBAttribute(attributeName = "stringAttr34")
@Override
public String getStringAttr34() {
return super.getStringAttr34();
}
@DynamoDBAttribute(attributeName = "stringAttr35")
@Override
public String getStringAttr35() {
return super.getStringAttr35();
}
@DynamoDBAttribute(attributeName = "stringAttr36")
@Override
public String getStringAttr36() {
return super.getStringAttr36();
}
@DynamoDBAttribute(attributeName = "stringAttr37")
@Override
public String getStringAttr37() {
return super.getStringAttr37();
}
@DynamoDBAttribute(attributeName = "stringAttr38")
@Override
public String getStringAttr38() {
return super.getStringAttr38();
}
@DynamoDBAttribute(attributeName = "stringAttr39")
@Override
public String getStringAttr39() {
return super.getStringAttr39();
}
@DynamoDBAttribute(attributeName = "stringAttr40")
@Override
public String getStringAttr40() {
return super.getStringAttr40();
}
@DynamoDBAttribute(attributeName = "stringAttr41")
@Override
public String getStringAttr41() {
return super.getStringAttr41();
}
@DynamoDBAttribute(attributeName = "stringAttr42")
@Override
public String getStringAttr42() {
return super.getStringAttr42();
}
@DynamoDBAttribute(attributeName = "stringAttr43")
@Override
public String getStringAttr43() {
return super.getStringAttr43();
}
@DynamoDBAttribute(attributeName = "stringAttr44")
@Override
public String getStringAttr44() {
return super.getStringAttr44();
}
@DynamoDBAttribute(attributeName = "stringAttr45")
@Override
public String getStringAttr45() {
return super.getStringAttr45();
}
@DynamoDBAttribute(attributeName = "stringAttr46")
@Override
public String getStringAttr46() {
return super.getStringAttr46();
}
@DynamoDBAttribute(attributeName = "stringAttr47")
@Override
public String getStringAttr47() {
return super.getStringAttr47();
}
@DynamoDBAttribute(attributeName = "stringAttr48")
@Override
public String getStringAttr48() {
return super.getStringAttr48();
}
@DynamoDBAttribute(attributeName = "stringAttr49")
@Override
public String getStringAttr49() {
return super.getStringAttr49();
}
@DynamoDBAttribute(attributeName = "stringAttr50")
@Override
public String getStringAttr50() {
return super.getStringAttr50();
}
@DynamoDBAttribute(attributeName = "stringAttr51")
@Override
public String getStringAttr51() {
return super.getStringAttr51();
}
@DynamoDBAttribute(attributeName = "stringAttr52")
@Override
public String getStringAttr52() {
return super.getStringAttr52();
}
@DynamoDBAttribute(attributeName = "stringAttr53")
@Override
public String getStringAttr53() {
return super.getStringAttr53();
}
@Override
@DynamoDBAttribute(attributeName = "stringAttr54")
public String getStringAttr54() {
return super.getStringAttr54();
}
@DynamoDBAttribute(attributeName = "stringAttr55")
@Override
public String getStringAttr55() {
return super.getStringAttr55();
}
@DynamoDBAttribute(attributeName = "stringAttr56")
@Override
public String getStringAttr56() {
return super.getStringAttr56();
}
@DynamoDBAttribute(attributeName = "stringAttr57")
@Override
public String getStringAttr57() {
return super.getStringAttr57();
}
@DynamoDBAttribute(attributeName = "stringAttr58")
@Override
public String getStringAttr58() {
return super.getStringAttr58();
}
@DynamoDBAttribute(attributeName = "stringAttr59")
@Override
public String getStringAttr59() {
return super.getStringAttr59();
}
@DynamoDBAttribute(attributeName = "stringAttr60")
@Override
public String getStringAttr60() {
return super.getStringAttr60();
}
@DynamoDBAttribute(attributeName = "stringAttr61")
@Override
public String getStringAttr61() {
return super.getStringAttr61();
}
@DynamoDBAttribute(attributeName = "stringAttr62")
@Override
public String getStringAttr62() {
return super.getStringAttr62();
}
@DynamoDBAttribute(attributeName = "stringAttr63")
@Override
public String getStringAttr63() {
return super.getStringAttr63();
}
public static V1HugeBeanFlat fromHugeBeanFlat(HugeBeanFlat b) {
V1HugeBeanFlat bean = new V1HugeBeanFlat();
for (int i = 1; i <= 63; ++i) {
try {
Method setter = V1HugeBeanFlat.class.getMethod("setStringAttr" + i, String.class);
Method getter = HugeBeanFlat.class.getMethod("getStringAttr" + i);
setter.setAccessible(true);
setter.invoke(bean, getter.invoke(b));
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
return bean;
}
}
}
| 2,526 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientGetV1MapperComparisonBenchmark.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.model.GetItemResult;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Fork(2)
@State(Scope.Benchmark)
public class EnhancedClientGetV1MapperComparisonBenchmark {
private static final V2ItemFactory V2_ITEM_FACTORY = new V2ItemFactory();
private static final V1ItemFactory V1_ITEM_FACTORY = new V1ItemFactory();
@Benchmark
public Object v2Get(TestState s) {
return s.v2Table.getItem(s.key);
}
@Benchmark
public Object v1Get(TestState s) {
return s.v1DdbMapper.load(s.testItem.v1Key);
}
private static DynamoDbClient getV2Client(Blackhole bh, GetItemResponse getItemResponse) {
return new V2TestDynamoDbGetItemClient(bh, getItemResponse);
}
private static AmazonDynamoDB getV1Client(Blackhole bh, GetItemResult getItemResult) {
return new V1TestDynamoDbGetItemClient(bh, getItemResult);
}
@State(Scope.Benchmark)
public static class TestState {
@Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"})
public TestItem testItem;
private final Key key = Key.builder().partitionValue("key").build();
private DynamoDbTable<?> v2Table;
private DynamoDBMapper v1DdbMapper;
@Setup
public void setup(Blackhole bh) {
DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getV2Client(bh, testItem.v2Response))
.build();
v2Table = v2DdbEnh.table(testItem.name(), testItem.schema);
v1DdbMapper = new DynamoDBMapper(getV1Client(bh, testItem.v1Response));
}
public enum TestItem {
TINY(
V2ItemFactory.TINY_BEAN_TABLE_SCHEMA,
GetItemResponse.builder().item(V2_ITEM_FACTORY.tiny()).build(),
new V1ItemFactory.V1TinyBean("hashKey"),
new GetItemResult().withItem(V1_ITEM_FACTORY.tiny())
),
SMALL(
V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA,
GetItemResponse.builder().item(V2_ITEM_FACTORY.small()).build(),
new V1ItemFactory.V1SmallBean("hashKey"),
new GetItemResult().withItem(V1_ITEM_FACTORY.small())
),
HUGE(
V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA,
GetItemResponse.builder().item(V2_ITEM_FACTORY.huge()).build(),
new V1ItemFactory.V1HugeBean("hashKey"),
new GetItemResult().withItem(V1_ITEM_FACTORY.huge())
),
HUGE_FLAT(
V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA,
GetItemResponse.builder().item(V2_ITEM_FACTORY.hugeFlat()).build(),
new V1ItemFactory.V1HugeBeanFlat("hashKey"),
new GetItemResult().withItem(V1_ITEM_FACTORY.hugeFlat())
),
;
// V2
private TableSchema<?> schema;
private GetItemResponse v2Response;
// V1
private Object v1Key;
private GetItemResult v1Response;
TestItem(TableSchema<?> schema,
GetItemResponse v2Response,
Object v1Key,
GetItemResult v1Response) {
this.schema = schema;
this.v2Response = v2Response;
this.v1Key = v1Key;
this.v1Response = v1Response;
}
}
}
}
| 2,527 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientQueryV1MapperComparisonBenchmark.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression;
import com.amazonaws.services.dynamodbv2.model.QueryResult;
import java.util.Arrays;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Fork(2)
@State(Scope.Benchmark)
public class EnhancedClientQueryV1MapperComparisonBenchmark {
private static final V2ItemFactory V2_ITEM_FACTORY = new V2ItemFactory();
private static final V1ItemFactory V1_ITEM_FACTORY = new V1ItemFactory();
@Benchmark
public Object v2Query(TestState s) {
return s.v2Table.query(QueryConditional.keyEqualTo(s.key)).iterator().next();
}
@Benchmark
public Object v1Query(TestState s) {
return s.v1DdbMapper.query(s.testItem.getV1BeanClass(), s.testItem.v1QueryExpression).iterator().next();
}
private static DynamoDbClient getV2Client(Blackhole bh, QueryResponse queryResponse) {
return new V2TestDynamoDbQueryClient(bh, queryResponse);
}
private static AmazonDynamoDB getV1Client(Blackhole bh, QueryResult queryResult) {
return new V1TestDynamoDbQueryClient(bh, queryResult);
}
@State(Scope.Benchmark)
public static class TestState {
@Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"})
public TestItem testItem;
private DynamoDbTable<?> v2Table;
private DynamoDBMapper v1DdbMapper;
private final Key key = Key.builder().partitionValue("key").build();
@Setup
public void setup(Blackhole bh) {
DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getV2Client(bh, testItem.v2Response))
.build();
v2Table = v2DdbEnh.table(testItem.name(), testItem.schema);
v1DdbMapper = new DynamoDBMapper(getV1Client(bh, testItem.v1Response));
}
public enum TestItem {
TINY(
V2ItemFactory.TINY_BEAN_TABLE_SCHEMA,
QueryResponse.builder()
.items(Arrays.asList(V2_ITEM_FACTORY.tiny(),
V2_ITEM_FACTORY.tiny(),
V2_ITEM_FACTORY.tiny()))
.build(),
V1ItemFactory.V1TinyBean.class,
new DynamoDBQueryExpression().withHashKeyValues(new V1ItemFactory.V1TinyBean("hashKey")),
new QueryResult().withItems(
Arrays.asList(V1_ITEM_FACTORY.tiny(), V1_ITEM_FACTORY.tiny(), V1_ITEM_FACTORY.tiny()))
),
SMALL(
V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA,
QueryResponse.builder()
.items(Arrays.asList(V2_ITEM_FACTORY.small(),
V2_ITEM_FACTORY.small(),
V2_ITEM_FACTORY.small()))
.build(),
V1ItemFactory.V1SmallBean.class,
new DynamoDBQueryExpression().withHashKeyValues(new V1ItemFactory.V1SmallBean("hashKey")),
new QueryResult().withItems(
Arrays.asList(V1_ITEM_FACTORY.small(), V1_ITEM_FACTORY.small(), V1_ITEM_FACTORY.small()))
),
HUGE(
V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA,
QueryResponse.builder()
.items(Arrays.asList(V2_ITEM_FACTORY.huge(),
V2_ITEM_FACTORY.huge(),
V2_ITEM_FACTORY.huge()))
.build(),
V1ItemFactory.V1HugeBean.class,
new DynamoDBQueryExpression().withHashKeyValues(new V1ItemFactory.V1HugeBean("hashKey")),
new QueryResult().withItems(
Arrays.asList(V1_ITEM_FACTORY.huge(), V1_ITEM_FACTORY.huge(), V1_ITEM_FACTORY.huge()))
),
HUGE_FLAT(
V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA,
QueryResponse.builder()
.items(Arrays.asList(V2_ITEM_FACTORY.hugeFlat(),
V2_ITEM_FACTORY.hugeFlat(),
V2_ITEM_FACTORY.hugeFlat()))
.build(),
V1ItemFactory.V1HugeBeanFlat.class,
new DynamoDBQueryExpression().withHashKeyValues(new V1ItemFactory.V1HugeBeanFlat("hashKey")),
new QueryResult().withItems(
Arrays.asList(V1_ITEM_FACTORY.hugeFlat(), V1_ITEM_FACTORY.hugeFlat(), V1_ITEM_FACTORY.hugeFlat()))
),
;
// V2
private TableSchema<?> schema;
private QueryResponse v2Response;
// V1
private Class<?> v1BeanClass;
private DynamoDBQueryExpression v1QueryExpression;
private QueryResult v1Response;
TestItem(TableSchema<?> schema,
QueryResponse v2Response,
Class<?> v1BeanClass,
DynamoDBQueryExpression v1QueryExpression,
QueryResult v1Response) {
this.schema = schema;
this.v2Response = v2Response;
this.v1BeanClass = v1BeanClass;
this.v1QueryExpression = v1QueryExpression;
this.v1Response = v1Response;
}
public Class<?> getV1BeanClass() {
return v1BeanClass;
}
}
}
}
| 2,528 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbPutItemClient.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.benchmark.enhanced.dynamodb;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
public final class V2TestDynamoDbPutItemClient extends V2TestDynamoDbBaseClient {
private static final PutItemResponse PUT_ITEM_RESPONSE = PutItemResponse.builder().build();
public V2TestDynamoDbPutItemClient(Blackhole bh) {
super(bh);
}
@Override
public PutItemResponse putItem(PutItemRequest putItemRequest) {
bh.consume(putItemRequest);
return PUT_ITEM_RESPONSE;
}
}
| 2,529 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientScanV1MapperComparisonBenchmark.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
import com.amazonaws.services.dynamodbv2.model.ScanResult;
import java.util.Arrays;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Fork(2)
@State(Scope.Benchmark)
public class EnhancedClientScanV1MapperComparisonBenchmark {
private static final V2ItemFactory V2_ITEM_FACTORY = new V2ItemFactory();
private static final V1ItemFactory V1_ITEM_FACTORY = new V1ItemFactory();
private static final DynamoDBScanExpression V1_SCAN_EXPRESSION = new DynamoDBScanExpression();
@Benchmark
public Object v2Scan(TestState s) {
return s.v2Table.scan().iterator().next();
}
@Benchmark
public Object v1Scan(TestState s) {
return s.v1DdbMapper.scan(s.testItem.getV1BeanClass(), V1_SCAN_EXPRESSION).iterator().next();
}
private static DynamoDbClient getV2Client(Blackhole bh, ScanResponse scanResponse) {
return new V2TestDynamoDbScanClient(bh, scanResponse);
}
private static AmazonDynamoDB getV1Client(Blackhole bh, ScanResult scanResult) {
return new V1TestDynamoDbScanClient(bh, scanResult);
}
@State(Scope.Benchmark)
public static class TestState {
@Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"})
public TestItem testItem;
private DynamoDbTable<?> v2Table;
private DynamoDBMapper v1DdbMapper;
@Setup
public void setup(Blackhole bh) {
DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getV2Client(bh, testItem.v2Response))
.build();
v2Table = v2DdbEnh.table(testItem.name(), testItem.schema);
v1DdbMapper = new DynamoDBMapper(getV1Client(bh, testItem.v1Response));
}
public enum TestItem {
TINY(
V2ItemFactory.TINY_BEAN_TABLE_SCHEMA,
ScanResponse.builder()
.items(Arrays.asList(V2_ITEM_FACTORY.tiny(),
V2_ITEM_FACTORY.tiny(),
V2_ITEM_FACTORY.tiny()))
.build(),
V1ItemFactory.V1TinyBean.class,
new ScanResult().withItems(
Arrays.asList(V1_ITEM_FACTORY.tiny(), V1_ITEM_FACTORY.tiny(), V1_ITEM_FACTORY.tiny()))
),
SMALL(
V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA,
ScanResponse.builder()
.items(Arrays.asList(V2_ITEM_FACTORY.small(),
V2_ITEM_FACTORY.small(),
V2_ITEM_FACTORY.small()))
.build(),
V1ItemFactory.V1SmallBean.class,
new ScanResult().withItems(
Arrays.asList(V1_ITEM_FACTORY.small(), V1_ITEM_FACTORY.small(), V1_ITEM_FACTORY.small()))
),
HUGE(
V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA,
ScanResponse.builder()
.items(Arrays.asList(V2_ITEM_FACTORY.huge(),
V2_ITEM_FACTORY.huge(),
V2_ITEM_FACTORY.huge()))
.build(),
V1ItemFactory.V1HugeBean.class,
new ScanResult().withItems(
Arrays.asList(V1_ITEM_FACTORY.huge(), V1_ITEM_FACTORY.huge(), V1_ITEM_FACTORY.huge()))
),
HUGE_FLAT(
V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA,
ScanResponse.builder()
.items(Arrays.asList(V2_ITEM_FACTORY.hugeFlat(),
V2_ITEM_FACTORY.hugeFlat(),
V2_ITEM_FACTORY.hugeFlat()))
.build(),
V1ItemFactory.V1HugeBeanFlat.class,
new ScanResult().withItems(
Arrays.asList(V1_ITEM_FACTORY.hugeFlat(), V1_ITEM_FACTORY.hugeFlat(), V1_ITEM_FACTORY.hugeFlat()))
),
;
// V2
private TableSchema<?> schema;
private ScanResponse v2Response;
// V1
private Class<?> v1BeanClass;
private ScanResult v1Response;
TestItem(TableSchema<?> schema,
ScanResponse v2Response,
Class<?> v1BeanClass,
ScanResult v1Response) {
this.schema = schema;
this.v2Response = v2Response;
this.v1BeanClass = v1BeanClass;
this.v1Response = v1Response;
}
public Class<?> getV1BeanClass() {
return v1BeanClass;
}
}
}
}
| 2,530 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientGetOverheadBenchmark.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.benchmark.enhanced.dynamodb;
import static software.amazon.awssdk.core.client.config.SdkClientOption.ENDPOINT;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.util.Map;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.benchmark.utils.MockHttpClient;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.protocols.json.AwsJsonProtocol;
import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.transform.PutItemRequestMarshaller;
import software.amazon.awssdk.utils.IoUtils;
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Fork(2)
@State(Scope.Benchmark)
public class EnhancedClientGetOverheadBenchmark {
private static final AwsJsonProtocolFactory JSON_PROTOCOL_FACTORY = AwsJsonProtocolFactory
.builder()
.clientConfiguration(SdkClientConfiguration.builder()
.option(ENDPOINT, URI.create("https://dynamodb.amazonaws.com"))
.build())
.defaultServiceExceptionSupplier(DynamoDbException::builder)
.protocol(AwsJsonProtocol.AWS_JSON)
.protocolVersion("1.0")
.build();
private static final PutItemRequestMarshaller PUT_ITEM_REQUEST_MARSHALLER =
new PutItemRequestMarshaller(JSON_PROTOCOL_FACTORY);
private static final V2ItemFactory ITEM_FACTORY = new V2ItemFactory();
private final Key testKey = Key.builder().partitionValue("key").build();
@Benchmark
public Object lowLevelGet(TestState s) {
return s.dynamoDb.getItem(GetItemRequest.builder().build());
}
@Benchmark
public Object enhanceGet(TestState s) {
return s.table.getItem(testKey);
}
@State(Scope.Benchmark)
public static class TestState {
private DynamoDbClient dynamoDb;
@Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"})
private TestItem testItem;
private DynamoDbTable table;
@Setup
public void setup(Blackhole bh) {
dynamoDb = DynamoDbClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")))
.httpClient(new MockHttpClient(testItem.responseContent, "{}"))
.overrideConfiguration(o -> o.addExecutionInterceptor(new ExecutionInterceptor() {
@Override
public void afterUnmarshalling(Context.AfterUnmarshalling context,
ExecutionAttributes executionAttributes) {
bh.consume(context);
bh.consume(executionAttributes);
}
}))
.build();
DynamoDbEnhancedClient ddbEnh = DynamoDbEnhancedClient.builder()
.dynamoDbClient(dynamoDb)
.build();
table = ddbEnh.table(testItem.name(), testItem.tableSchema);
}
}
public enum TestItem {
TINY(marshall(ITEM_FACTORY.tiny()), V2ItemFactory.TINY_BEAN_TABLE_SCHEMA),
SMALL(marshall(ITEM_FACTORY.small()), V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA),
HUGE(marshall(ITEM_FACTORY.huge()), V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA),
HUGE_FLAT(marshall(ITEM_FACTORY.hugeFlat()), V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA)
;
private String responseContent;
private TableSchema tableSchema;
TestItem(String responseContent, TableSchema tableSchema) {
this.responseContent = responseContent;
this.tableSchema = tableSchema;
}
}
private static String marshall(Map<String, AttributeValue> item) {
return PUT_ITEM_REQUEST_MARSHALLER.marshall(PutItemRequest.builder().item(item).build())
.contentStreamProvider().map(cs -> {
try {
return IoUtils.toUtf8String(cs.newStream());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}).orElse(null);
}
}
| 2,531 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientDeleteV1MapperComparisonBenchmark.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Fork(2)
@State(Scope.Benchmark)
public class EnhancedClientDeleteV1MapperComparisonBenchmark {
@Benchmark
public void v2Delete(TestState s) {
s.v2Table.deleteItem(s.key);
}
@Benchmark
public void v1Delete(TestState s) {
s.v1DdbMapper.delete(s.testItem.v1Key);
}
private static DynamoDbClient getV2Client(Blackhole bh) {
return new V2TestDynamoDbDeleteItemClient(bh);
}
private static AmazonDynamoDB getV1Client(Blackhole bh) {
return new V1TestDynamoDbDeleteItemClient(bh);
}
@State(Scope.Benchmark)
public static class TestState {
@Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"})
public TestItem testItem;
private final Key key = Key.builder().partitionValue("key").build();
private DynamoDbTable v2Table;
private DynamoDBMapper v1DdbMapper;
@Setup
public void setup(Blackhole bh) {
DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getV2Client(bh))
.build();
v2Table = v2DdbEnh.table(testItem.name(), testItem.schema);
v1DdbMapper = new DynamoDBMapper(getV1Client(bh));
}
public enum TestItem {
TINY(
V2ItemFactory.TINY_BEAN_TABLE_SCHEMA,
new V1ItemFactory.V1TinyBean("hashKey")
),
SMALL(
V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA,
new V1ItemFactory.V1SmallBean("hashKey")
),
HUGE(
V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA,
new V1ItemFactory.V1HugeBean("hashKey")
),
HUGE_FLAT(
V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA,
new V1ItemFactory.V1HugeBeanFlat("hashKey")
),
;
// V2
private TableSchema schema;
// V1
private Object v1Key;
TestItem(TableSchema<?> schema,
Object v1Key) {
this.schema = schema;
this.v1Key = v1Key;
}
}
}
}
| 2,532 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientPutOverheadBenchmark.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.benchmark.enhanced.dynamodb;
import java.util.Map;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.benchmark.utils.MockHttpClient;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Fork(2)
@State(Scope.Benchmark)
public class EnhancedClientPutOverheadBenchmark {
@Benchmark
public void lowLevelPut(TestState s) {
s.ddb.putItem(r -> r.item(s.testItem.av));
}
@Benchmark
public void enhancedPut(TestState s) {
s.enhTable.putItem(s.testItem.bean);
}
@State(Scope.Benchmark)
public static class TestState {
@Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"})
private TestItem testItem;
private DynamoDbClient ddb;
private DynamoDbTable enhTable;
@Setup
public void setup(Blackhole bh) {
ddb = DynamoDbClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")))
.httpClient(new MockHttpClient("{}", "{}"))
.overrideConfiguration(c -> c.addExecutionInterceptor(new ExecutionInterceptor() {
@Override
public void afterUnmarshalling(Context.AfterUnmarshalling context,
ExecutionAttributes executionAttributes) {
bh.consume(context);
bh.consume(executionAttributes);
}
}))
.build();
DynamoDbEnhancedClient ddbEnh = DynamoDbEnhancedClient.builder()
.dynamoDbClient(ddb)
.build();
enhTable = ddbEnh.table(testItem.name(), testItem.tableSchema);
}
}
public enum TestItem {
TINY,
SMALL,
HUGE,
HUGE_FLAT
;
private static final V2ItemFactory FACTORY = new V2ItemFactory();
private Map<String, AttributeValue> av;
private TableSchema tableSchema;
private Object bean;
static {
TINY.av = FACTORY.tiny();
TINY.tableSchema = V2ItemFactory.TINY_BEAN_TABLE_SCHEMA;
TINY.bean = FACTORY.tinyBean();
SMALL.av = FACTORY.small();
SMALL.tableSchema = V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA;
SMALL.bean = FACTORY.smallBean();
HUGE.av = FACTORY.huge();
HUGE.tableSchema = V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA;
HUGE.bean = FACTORY.hugeBean();
HUGE_FLAT.av = FACTORY.hugeFlat();
HUGE_FLAT.tableSchema = V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA;
HUGE_FLAT.bean = FACTORY.hugeBeanFlat();
}
}
}
| 2,533 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbQueryClient.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.model.QueryRequest;
import com.amazonaws.services.dynamodbv2.model.QueryResult;
import org.openjdk.jmh.infra.Blackhole;
public class V1TestDynamoDbQueryClient extends V1TestDynamoDbBaseClient {
private final QueryResult queryResult;
public V1TestDynamoDbQueryClient(Blackhole bh, QueryResult queryResult) {
super(bh);
this.queryResult = queryResult;
}
@Override
public QueryResult query(QueryRequest request) {
bh.consume(request);
return queryResult;
}
}
| 2,534 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbBaseClient.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.benchmark.enhanced.dynamodb;
import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
abstract class V2TestDynamoDbBaseClient implements DynamoDbClient {
protected final Blackhole bh;
protected V2TestDynamoDbBaseClient(Blackhole bh) {
this.bh = bh;
}
@Override
public String serviceName() {
return "DynamoDB";
}
@Override
public void close() {
}
}
| 2,535 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbScanClient.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.benchmark.enhanced.dynamodb;
import com.amazonaws.services.dynamodbv2.model.ScanRequest;
import com.amazonaws.services.dynamodbv2.model.ScanResult;
import org.openjdk.jmh.infra.Blackhole;
public class V1TestDynamoDbScanClient extends V1TestDynamoDbBaseClient {
private final ScanResult scanResult;
public V1TestDynamoDbScanClient(Blackhole bh, ScanResult scanResult) {
super(bh);
this.scanResult = scanResult;
}
@Override
public ScanResult scan(ScanRequest request) {
bh.consume(request);
return scanResult;
}
}
| 2,536 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/dynamodb/V2ItemFactory.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.benchmark.marshaller.dynamodb;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
public final class V2ItemFactory extends AbstractItemFactory<AttributeValue> {
@Override
protected AttributeValue av(String val) {
return AttributeValue.builder().s(val).build();
}
@Override
protected AttributeValue av(ByteBuffer val) {
return AttributeValue.builder().b(SdkBytes.fromByteBuffer(val)).build();
}
@Override
protected AttributeValue av(List<AttributeValue> val) {
return AttributeValue.builder().l(val).build();
}
@Override
protected AttributeValue av(Map<String, AttributeValue> val) {
return AttributeValue.builder().m(val).build();
}
}
| 2,537 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/dynamodb/V1DynamoDbAttributeValue.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.benchmark.marshaller.dynamodb;
import com.amazonaws.AmazonWebServiceResponse;
import com.amazonaws.Request;
import com.amazonaws.http.HttpResponse;
import com.amazonaws.http.HttpResponseHandler;
import com.amazonaws.protocol.json.JsonClientMetadata;
import com.amazonaws.protocol.json.JsonOperationMetadata;
import com.amazonaws.protocol.json.SdkJsonProtocolFactory;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.GetItemResult;
import com.amazonaws.services.dynamodbv2.model.PutItemRequest;
import com.amazonaws.services.dynamodbv2.model.transform.GetItemResultJsonUnmarshaller;
import com.amazonaws.services.dynamodbv2.model.transform.PutItemRequestProtocolMarshaller;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Map;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
@State(Scope.Benchmark)
public class V1DynamoDbAttributeValue {
private static final SdkJsonProtocolFactory PROTOCOL_FACTORY = protocolFactory();
private static final PutItemRequestProtocolMarshaller PUT_ITEM_REQUEST_MARSHALLER
= new PutItemRequestProtocolMarshaller(PROTOCOL_FACTORY);
@Benchmark
public Object putItem(PutItemState s) {
return PUT_ITEM_REQUEST_MARSHALLER.marshall(s.getReq());
}
@Benchmark
public Object getItem(GetItemState s) {
HttpResponse resp = new HttpResponse(null, null);
resp.setContent(new ByteArrayInputStream(s.testItem.utf8()));
try {
return getItemJsonResponseHandler().handle(resp);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@State(Scope.Benchmark)
public static class PutItemState {
@Param({"TINY", "SMALL", "HUGE"})
private TestItem testItem;
private PutItemRequest req;
@Setup
public void setup() {
req = new PutItemRequest().withItem(testItem.getValue());
}
public PutItemRequest getReq() {
return req;
}
}
@State(Scope.Benchmark)
public static class GetItemState {
@Param(
{"TINY", "SMALL", "HUGE"}
)
private TestItemUnmarshalling testItem;
}
public enum TestItem {
TINY,
SMALL,
HUGE;
private static final AbstractItemFactory<AttributeValue> FACTORY = new V1ItemFactory();
private Map<String, AttributeValue> av;
static {
TINY.av = FACTORY.tiny();
SMALL.av = FACTORY.small();
HUGE.av = FACTORY.huge();
}
public Map<String, AttributeValue> getValue() {
return av;
}
}
public enum TestItemUnmarshalling {
TINY,
SMALL,
HUGE;
private byte[] utf8;
static {
TINY.utf8 = toUtf8ByteArray(TestItem.TINY.av);
SMALL.utf8 = toUtf8ByteArray(TestItem.SMALL.av);
HUGE.utf8 = toUtf8ByteArray(TestItem.HUGE.av);
}
public byte[] utf8() {
return utf8;
}
}
private static byte[] toUtf8ByteArray(Map<String, AttributeValue> item) {
Request<?> resp = PUT_ITEM_REQUEST_MARSHALLER.marshall(new PutItemRequest().withItem(item));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[8192];
int read;
try {
while ((read = resp.getContent().read(buff)) != -1) {
baos.write(buff, 0, read);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return baos.toByteArray();
}
private static HttpResponseHandler<AmazonWebServiceResponse<GetItemResult>> getItemJsonResponseHandler() {
return PROTOCOL_FACTORY.createResponseHandler(new JsonOperationMetadata()
.withPayloadJson(true)
.withHasStreamingSuccessResponse(false),
new GetItemResultJsonUnmarshaller());
}
private static SdkJsonProtocolFactory protocolFactory() {
return new com.amazonaws.protocol.json.SdkJsonProtocolFactory(
new JsonClientMetadata()
.withProtocolVersion("1.0")
.withSupportsCbor(false)
.withSupportsIon(false)
);
}
}
| 2,538 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/dynamodb/V1ItemFactory.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.benchmark.marshaller.dynamodb;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
public final class V1ItemFactory extends AbstractItemFactory<AttributeValue> {
@Override
protected AttributeValue av(String val) {
return new AttributeValue()
.withS(val);
}
@Override
protected AttributeValue av(ByteBuffer val) {
return new AttributeValue()
.withB(val);
}
@Override
protected AttributeValue av(List<AttributeValue> val) {
return new AttributeValue()
.withL(val);
}
@Override
protected AttributeValue av(Map<String, AttributeValue> val) {
return new AttributeValue()
.withM(val);
}
}
| 2,539 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/dynamodb/AbstractItemFactory.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.benchmark.marshaller.dynamodb;
import com.amazonaws.util.ImmutableMapParameter;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
abstract class AbstractItemFactory<T> {
private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
private static final Random RNG = new Random();
final Map<String, T> tiny() {
return ImmutableMapParameter.<String, T>builder()
.put("stringAttr", av(randomS()))
.build();
}
final Map<String, T> small() {
return ImmutableMapParameter.<String, T>builder()
.put("stringAttr", av(randomS()))
.put("binaryAttr", av(randomB()))
.put("listAttr", av(Arrays.asList(
av(randomS()),
av(randomB()),
av(randomS())
)))
.build();
}
final Map<String, T> huge() {
return ImmutableMapParameter.<String, T>builder()
.put("hashKey", av(randomS()))
.put("stringAttr", av(randomS()))
.put("binaryAttr", av(randomB()))
.put("listAttr", av(
Arrays.asList(
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomB()),
av(Collections.singletonList(av(randomS()))),
av(ImmutableMapParameter.of(
"attrOne", av(randomS())
)),
av(Arrays.asList(
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(randomB()),
(av(randomS())),
av(ImmutableMapParameter.of(
"attrOne",
av(randomS())
))
))
)
))
.put("mapAttr", av(
ImmutableMapParameter.<String, T>builder()
.put("attrOne", av(randomS()))
.put("attrTwo", av(randomB()))
.put("attrThree", av(
Arrays.asList(
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS()),
av(ImmutableMapParameter.<String, T>builder()
.put("attrOne", av(randomS()))
.put("attrTwo", av(randomB()))
.put("attrThree",
av(Arrays.asList(
av(randomS()),
av(randomS()),
av(randomS()),
av(randomS())
))
)
.build())
))
)
.build()))
.build();
}
protected abstract T av(String val);
protected abstract T av(ByteBuffer val);
protected abstract T av(List<T> val);
protected abstract T av(Map<String, T> val);
private String randomS(int len) {
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; ++i) {
sb.append(ALPHA.charAt(RNG.nextInt(ALPHA.length())));
}
return sb.toString();
}
private String randomS() {
return randomS(16);
}
private ByteBuffer randomB(int len) {
byte[] b = new byte[len];
RNG.nextBytes(b);
return ByteBuffer.wrap(b);
}
private ByteBuffer randomB() {
return randomB(16);
}
}
| 2,540 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/dynamodb/V2DynamoDbAttributeValue.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.benchmark.marshaller.dynamodb;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.Map;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.json.AwsJsonProtocol;
import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory;
import software.amazon.awssdk.protocols.json.JsonOperationMetadata;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.BackupInUseException;
import software.amazon.awssdk.services.dynamodb.model.BackupNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.ContinuousBackupsUnavailableException;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.GlobalTableAlreadyExistsException;
import software.amazon.awssdk.services.dynamodb.model.GlobalTableNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.IndexNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.InternalServerErrorException;
import software.amazon.awssdk.services.dynamodb.model.InvalidRestoreTimeException;
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
import software.amazon.awssdk.services.dynamodb.model.LimitExceededException;
import software.amazon.awssdk.services.dynamodb.model.PointInTimeRecoveryUnavailableException;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.ReplicaAlreadyExistsException;
import software.amazon.awssdk.services.dynamodb.model.ReplicaNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.ResourceInUseException;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.TableAlreadyExistsException;
import software.amazon.awssdk.services.dynamodb.model.TableInUseException;
import software.amazon.awssdk.services.dynamodb.model.TableNotFoundException;
import software.amazon.awssdk.services.dynamodb.transform.PutItemRequestMarshaller;
public class V2DynamoDbAttributeValue {
private static final AwsJsonProtocolFactory JSON_PROTOCOL_FACTORY = AwsJsonProtocolFactory
.builder()
.defaultServiceExceptionSupplier(DynamoDbException::builder)
.protocol(AwsJsonProtocol.AWS_JSON)
.protocolVersion("1.0")
.registerModeledException(
ExceptionMetadata.builder().errorCode("ResourceInUseException")
.exceptionBuilderSupplier(ResourceInUseException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("TableAlreadyExistsException")
.exceptionBuilderSupplier(TableAlreadyExistsException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("GlobalTableAlreadyExistsException")
.exceptionBuilderSupplier(GlobalTableAlreadyExistsException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("InvalidRestoreTimeException")
.exceptionBuilderSupplier(InvalidRestoreTimeException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("ReplicaAlreadyExistsException")
.exceptionBuilderSupplier(ReplicaAlreadyExistsException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("ConditionalCheckFailedException")
.exceptionBuilderSupplier(ConditionalCheckFailedException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("BackupNotFoundException")
.exceptionBuilderSupplier(BackupNotFoundException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("IndexNotFoundException")
.exceptionBuilderSupplier(IndexNotFoundException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("LimitExceededException")
.exceptionBuilderSupplier(LimitExceededException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("GlobalTableNotFoundException")
.exceptionBuilderSupplier(GlobalTableNotFoundException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("ItemCollectionSizeLimitExceededException")
.exceptionBuilderSupplier(ItemCollectionSizeLimitExceededException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("ReplicaNotFoundException")
.exceptionBuilderSupplier(ReplicaNotFoundException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("TableNotFoundException")
.exceptionBuilderSupplier(TableNotFoundException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("BackupInUseException")
.exceptionBuilderSupplier(BackupInUseException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("ResourceNotFoundException")
.exceptionBuilderSupplier(ResourceNotFoundException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("ContinuousBackupsUnavailableException")
.exceptionBuilderSupplier(ContinuousBackupsUnavailableException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("TableInUseException")
.exceptionBuilderSupplier(TableInUseException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("ProvisionedThroughputExceededException")
.exceptionBuilderSupplier(ProvisionedThroughputExceededException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("PointInTimeRecoveryUnavailableException")
.exceptionBuilderSupplier(PointInTimeRecoveryUnavailableException::builder).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("InternalServerError")
.exceptionBuilderSupplier(InternalServerErrorException::builder).build())
.build();
private static final PutItemRequestMarshaller PUT_ITEM_REQUEST_MARSHALLER
= new PutItemRequestMarshaller(getJsonProtocolFactory());
private static HttpResponseHandler<GetItemResponse> getItemResponseJsonResponseHandler() {
return JSON_PROTOCOL_FACTORY.createResponseHandler(JsonOperationMetadata.builder()
.isPayloadJson(true)
.hasStreamingSuccessResponse(false)
.build(),
GetItemResponse::builder);
}
@Benchmark
public Object putItem(PutItemState s) {
return putItemRequestMarshaller().marshall(s.getReq());
}
@Benchmark
public Object getItem(GetItemState s) throws Exception {
SdkHttpFullResponse resp = fullResponse(s.testItem);
return getItemResponseJsonResponseHandler().handle(resp, new ExecutionAttributes());
}
@State(Scope.Benchmark)
public static class PutItemState {
@Param({"TINY", "SMALL", "HUGE"})
private TestItem testItem;
private PutItemRequest req;
@Setup
public void setup() {
req = PutItemRequest.builder().item(testItem.getValue()).build();
}
public PutItemRequest getReq() {
return req;
}
}
@State(Scope.Benchmark)
public static class GetItemState {
@Param({"TINY", "SMALL", "HUGE"})
private TestItemUnmarshalling testItem;
}
public enum TestItem {
TINY,
SMALL,
HUGE;
private static final AbstractItemFactory<AttributeValue> FACTORY = new V2ItemFactory();
private Map<String, AttributeValue> av;
static {
TINY.av = FACTORY.tiny();
SMALL.av = FACTORY.small();
HUGE.av = FACTORY.huge();
}
public Map<String, AttributeValue> getValue() {
return av;
}
}
public enum TestItemUnmarshalling {
TINY,
SMALL,
HUGE;
private byte[] utf8;
static {
TINY.utf8 = toUtf8ByteArray(TestItem.TINY.av);
SMALL.utf8 = toUtf8ByteArray(TestItem.SMALL.av);
HUGE.utf8 = toUtf8ByteArray(TestItem.HUGE.av);
}
public byte[] utf8() {
return utf8;
}
}
private SdkHttpFullResponse fullResponse(TestItemUnmarshalling item) {
AbortableInputStream abortableInputStream = AbortableInputStream.create(new ByteArrayInputStream(item.utf8()));
return SdkHttpFullResponse.builder()
.statusCode(200)
.content(abortableInputStream)
.build();
}
private static byte[] toUtf8ByteArray(Map<String, AttributeValue> item) {
SdkHttpFullRequest marshalled = putItemRequestMarshaller().marshall(PutItemRequest.builder().item(item).build());
InputStream content = marshalled.contentStreamProvider().get().newStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[8192];
int read;
try {
while ((read = content.read(buff)) != -1) {
baos.write(buff, 0, read);
}
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
return baos.toByteArray();
}
private static PutItemRequestMarshaller putItemRequestMarshaller() {
return PUT_ITEM_REQUEST_MARSHALLER;
}
private static AwsJsonProtocolFactory getJsonProtocolFactory() {
return JSON_PROTOCOL_FACTORY;
}
}
| 2,541 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/ec2/V2ItemFactory.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.benchmark.marshaller.ec2;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import software.amazon.awssdk.services.ec2.model.BlockDeviceMapping;
import software.amazon.awssdk.services.ec2.model.ElasticGpuSpecification;
import software.amazon.awssdk.services.ec2.model.InstanceNetworkInterfaceSpecification;
import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
import software.amazon.awssdk.services.ec2.model.VolumeType;
final class V2ItemFactory {
private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
private static final Random RNG = new Random();
RunInstancesRequest tiny() {
return RunInstancesRequest.builder()
.additionalInfo(randomS(50))
.disableApiTermination(true)
.maxCount(5)
.build();
}
RunInstancesRequest small() {
return RunInstancesRequest.builder()
.additionalInfo(randomS(50))
.disableApiTermination(true)
.maxCount(5)
.blockDeviceMappings(blockDeviceMappings(3))
.cpuOptions(c -> c.coreCount(5).threadsPerCore(5))
.elasticGpuSpecification(elasticGpuSpecification())
.networkInterfaces(networkInterfaces(3))
.build();
}
RunInstancesRequest huge() {
return RunInstancesRequest.builder()
.additionalInfo(randomS(50))
.disableApiTermination(true)
.maxCount(5)
.blockDeviceMappings(blockDeviceMappings(100))
.cpuOptions(c -> c.coreCount(5).threadsPerCore(5))
.elasticGpuSpecification(elasticGpuSpecification())
.networkInterfaces(networkInterfaces(100))
.build();
}
private static ElasticGpuSpecification elasticGpuSpecification() {
return ElasticGpuSpecification.builder()
.type(randomS(50))
.build();
}
private static InstanceNetworkInterfaceSpecification networkInterface() {
return InstanceNetworkInterfaceSpecification.builder()
.associatePublicIpAddress(true)
.deleteOnTermination(true)
.deviceIndex(50)
.groups(randomS(50), randomS(50), randomS(50))
.description(randomS(50))
.build();
}
private static List<InstanceNetworkInterfaceSpecification> networkInterfaces(int num) {
return IntStream.of(num)
.mapToObj(i -> networkInterface())
.collect(Collectors.toList());
}
private static BlockDeviceMapping blockDeviceMapping() {
return BlockDeviceMapping.builder()
.deviceName(randomS(100))
.virtualName(randomS(50))
.noDevice(randomS(50))
.ebs(e -> e.deleteOnTermination(true)
.encrypted(false)
.iops(50)
.kmsKeyId(randomS(50))
.snapshotId(randomS(50))
.volumeSize(50)
.volumeType(VolumeType.GP2))
.build();
}
private static List<BlockDeviceMapping> blockDeviceMappings(int num) {
return IntStream.of(num)
.mapToObj(i -> blockDeviceMapping())
.collect(Collectors.toList());
}
private static String randomS(int len) {
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; ++i) {
sb.append(ALPHA.charAt(RNG.nextInt(ALPHA.length())));
}
return sb.toString();
}
}
| 2,542 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/ec2/V2Ec2MarshallerBenchmark.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.benchmark.marshaller.ec2;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import software.amazon.awssdk.protocols.query.AwsEc2ProtocolFactory;
import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
import software.amazon.awssdk.services.ec2.transform.RunInstancesRequestMarshaller;
public class V2Ec2MarshallerBenchmark {
private static final AwsEc2ProtocolFactory PROTOCOL_FACTORY = AwsEc2ProtocolFactory.builder().build();
private static final RunInstancesRequestMarshaller RUN_INSTANCES_REQUEST_MARSHALLER
= new RunInstancesRequestMarshaller(PROTOCOL_FACTORY);
@Benchmark
public Object marshall(MarshallerState s) {
return runInstancesRequestMarshaller().marshall(s.getReq());
}
@State(Scope.Benchmark)
public static class MarshallerState {
@Param({"TINY", "SMALL", "HUGE"})
private TestItem testItem;
private RunInstancesRequest req;
@Setup
public void setup() {
req = testItem.getValue();
}
public RunInstancesRequest getReq() {
return req;
}
}
public enum TestItem {
TINY,
SMALL,
HUGE;
private static final V2ItemFactory FACTORY = new V2ItemFactory();
private RunInstancesRequest request;
static {
TINY.request = FACTORY.tiny();
SMALL.request = FACTORY.small();
HUGE.request = FACTORY.huge();
}
public RunInstancesRequest getValue() {
return request;
}
}
private static RunInstancesRequestMarshaller runInstancesRequestMarshaller() {
return RUN_INSTANCES_REQUEST_MARSHALLER;
}
}
| 2,543 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/ec2/V1ItemFactory.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.benchmark.marshaller.ec2;
import com.amazonaws.services.ec2.model.BlockDeviceMapping;
import com.amazonaws.services.ec2.model.CpuOptionsRequest;
import com.amazonaws.services.ec2.model.EbsBlockDevice;
import com.amazonaws.services.ec2.model.ElasticGpuSpecification;
import com.amazonaws.services.ec2.model.InstanceNetworkInterfaceSpecification;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.VolumeType;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
final class V1ItemFactory {
private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
private static final Random RNG = new Random();
RunInstancesRequest tiny() {
return new RunInstancesRequest()
.withAdditionalInfo(randomS(50))
.withDisableApiTermination(true)
.withMaxCount(5);
}
RunInstancesRequest small() {
return new RunInstancesRequest()
.withAdditionalInfo(randomS(50))
.withDisableApiTermination(true)
.withMaxCount(5)
.withBlockDeviceMappings(blockDeviceMappings(3))
.withCpuOptions(new CpuOptionsRequest().withCoreCount(5).withThreadsPerCore(5))
.withElasticGpuSpecification(new ElasticGpuSpecification().withType(randomS(50)))
.withNetworkInterfaces(networkInterfaces(3));
}
RunInstancesRequest huge() {
return new RunInstancesRequest()
.withAdditionalInfo(randomS(50))
.withDisableApiTermination(true)
.withMaxCount(5)
.withBlockDeviceMappings(blockDeviceMappings(100))
.withCpuOptions(new CpuOptionsRequest().withCoreCount(5).withThreadsPerCore(5))
.withElasticGpuSpecification(new ElasticGpuSpecification().withType(randomS(50)))
.withNetworkInterfaces(networkInterfaces(100));
}
static InstanceNetworkInterfaceSpecification networkInterface() {
return new InstanceNetworkInterfaceSpecification()
.withAssociatePublicIpAddress(true)
.withDeleteOnTermination(true)
.withDeviceIndex(50)
.withGroups(randomS(50), randomS(50), randomS(50))
.withDescription(randomS(50));
}
static List<InstanceNetworkInterfaceSpecification> networkInterfaces(int num) {
return IntStream.of(num)
.mapToObj(i -> networkInterface())
.collect(Collectors.toList());
}
private static BlockDeviceMapping blockDeviceMapping() {
return new BlockDeviceMapping()
.withDeviceName(randomS(100))
.withVirtualName(randomS(50))
.withNoDevice(randomS(50))
.withEbs(new EbsBlockDevice().withDeleteOnTermination(true)
.withEncrypted(false)
.withIops(50)
.withKmsKeyId(randomS(50))
.withSnapshotId(randomS(50))
.withVolumeSize(50)
.withVolumeType(VolumeType.Gp2));
}
private static List<BlockDeviceMapping> blockDeviceMappings(int num) {
return IntStream.of(num)
.mapToObj(i -> blockDeviceMapping())
.collect(Collectors.toList());
}
private static String randomS(int len) {
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; ++i) {
sb.append(ALPHA.charAt(RNG.nextInt(ALPHA.length())));
}
return sb.toString();
}
}
| 2,544 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/ec2/V1Ec2MarshallerBenchmark.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.benchmark.marshaller.ec2;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.transform.RunInstancesRequestMarshaller;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
public class V1Ec2MarshallerBenchmark {
private static final RunInstancesRequestMarshaller RUN_INSTANCES_REQUEST_MARSHALLER
= new RunInstancesRequestMarshaller();
@Benchmark
public Object marshall(MarshallerState s) {
return runInstancesRequestMarshaller().marshall(s.getReq());
}
@State(Scope.Benchmark)
public static class MarshallerState {
@Param({"TINY", "SMALL", "HUGE"})
private TestItem testItem;
private RunInstancesRequest req;
@Setup
public void setup() {
req = testItem.getValue();
}
public RunInstancesRequest getReq() {
return req;
}
}
public enum TestItem {
TINY,
SMALL,
HUGE;
private static final V1ItemFactory FACTORY = new V1ItemFactory();
private RunInstancesRequest request;
static {
TINY.request = FACTORY.tiny();
SMALL.request = FACTORY.small();
HUGE.request = FACTORY.huge();
}
public RunInstancesRequest getValue() {
return request;
}
}
private static RunInstancesRequestMarshaller runInstancesRequestMarshaller() {
return RUN_INSTANCES_REQUEST_MARSHALLER;
}
}
| 2,545 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/stats/SdkBenchmarkParams.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.benchmark.stats;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.infra.BenchmarkParams;
import software.amazon.awssdk.core.util.VersionInfo;
/**
* Contains metadata for the benchmark
*/
public class SdkBenchmarkParams {
private String sdkVersion;
private String jdkVersion;
private String jvmName;
private String jvmVersion;
private Mode mode;
@JsonSerialize(using = ZonedDateSerializer.class)
@JsonDeserialize(using = ZonedDateDeserializer.class)
private ZonedDateTime date;
public SdkBenchmarkParams() {
}
public SdkBenchmarkParams(BenchmarkParams benchmarkParams) {
this.sdkVersion = VersionInfo.SDK_VERSION;
this.jdkVersion = benchmarkParams.getJdkVersion();
this.jvmName = benchmarkParams.getVmName();
this.jvmVersion = benchmarkParams.getVmVersion();
this.mode = benchmarkParams.getMode();
this.date = ZonedDateTime.now();
}
public String getSdkVersion() {
return sdkVersion;
}
public void setSdkVersion(String sdkVersion) {
this.sdkVersion = sdkVersion;
}
public String getJdkVersion() {
return jdkVersion;
}
public void setJdkVersion(String jdkVersion) {
this.jdkVersion = jdkVersion;
}
public String getJvmName() {
return jvmName;
}
public void setJvmName(String jvmName) {
this.jvmName = jvmName;
}
public String getJvmVersion() {
return jvmVersion;
}
public void setJvmVersion(String jvmVersion) {
this.jvmVersion = jvmVersion;
}
public ZonedDateTime getDate() {
return date;
}
public void setDate(ZonedDateTime date) {
this.date = date;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode mode) {
this.mode = mode;
}
private static class ZonedDateSerializer extends JsonSerializer<ZonedDateTime> {
@Override
public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(value.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}
}
private static class ZonedDateDeserializer extends JsonDeserializer<ZonedDateTime> {
@Override
public ZonedDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return ZonedDateTime.parse(p.getValueAsString());
}
}
}
| 2,546 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/stats/SdkBenchmarkResult.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.benchmark.stats;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* SDK wrapper of benchmark result, created for easy serialization/deserialization.
*/
public class SdkBenchmarkResult {
private String id;
private SdkBenchmarkParams params;
private SdkBenchmarkStatistics statistics;
@JsonCreator
public SdkBenchmarkResult(@JsonProperty("id") String benchmarkId,
@JsonProperty("params") SdkBenchmarkParams params,
@JsonProperty("statistics") SdkBenchmarkStatistics statistics) {
this.id = benchmarkId;
this.statistics = statistics;
this.params = params;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public SdkBenchmarkStatistics getStatistics() {
return statistics;
}
public void setStatistics(SdkBenchmarkStatistics statistics) {
this.statistics = statistics;
}
public SdkBenchmarkParams getParams() {
return params;
}
public void setParams(SdkBenchmarkParams params) {
this.params = params;
}
}
| 2,547 |
0 | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark | Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/stats/SdkBenchmarkStatistics.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.benchmark.stats;
import org.apache.commons.math3.stat.descriptive.StatisticalSummary;
import org.openjdk.jmh.util.Statistics;
/**
* SDK wrapper of benchmark statistics, created for easy serialization/deserialization.
*/
public class SdkBenchmarkStatistics implements StatisticalSummary {
private double mean;
private double variance;
private double standardDeviation;
private double max;
private double min;
private long n;
private double sum;
public SdkBenchmarkStatistics() {
}
public SdkBenchmarkStatistics(Statistics statistics) {
this.mean = statistics.getMean();
this.variance = statistics.getVariance();
this.standardDeviation = statistics.getStandardDeviation();
this.max = statistics.getMax();
this.min = statistics.getMin();
this.n = statistics.getN();
this.sum = statistics.getSum();
}
@Override
public double getMean() {
return mean;
}
public void setMean(double mean) {
this.mean = mean;
}
@Override
public double getVariance() {
return variance;
}
public void setVariance(double variance) {
this.variance = variance;
}
@Override
public double getStandardDeviation() {
return standardDeviation;
}
public void setStandardDeviation(double standardDeviation) {
this.standardDeviation = standardDeviation;
}
@Override
public double getMax() {
return max;
}
public void setMax(double max) {
this.max = max;
}
@Override
public double getMin() {
return min;
}
public void setMin(double min) {
this.min = min;
}
@Override
public long getN() {
return n;
}
public void setN(long n) {
this.n = n;
}
@Override
public double getSum() {
return sum;
}
public void setSum(double sum) {
this.sum = sum;
}
}
| 2,548 |
0 | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/EndpointProviderTestCase.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.core.rules.testing;
import java.util.function.Supplier;
import software.amazon.awssdk.core.rules.testing.model.Expect;
import software.amazon.awssdk.endpoints.Endpoint;
public final class EndpointProviderTestCase {
private Supplier<Endpoint> testMethod;
private Expect expect;
public EndpointProviderTestCase(Supplier<Endpoint> testMethod, Expect expect) {
this.testMethod = testMethod;
this.expect = expect;
}
public Supplier<Endpoint> getTestMethod() {
return testMethod;
}
public void setTestMethod(Supplier<Endpoint> testMethod) {
this.testMethod = testMethod;
}
public Expect getExpect() {
return expect;
}
public void setExpect(Expect expect) {
this.expect = expect;
}
}
| 2,549 |
0 | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/AsyncTestCase.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.core.rules.testing;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import software.amazon.awssdk.core.rules.testing.model.Expect;
public final class AsyncTestCase {
private final String description;
private final Supplier<CompletableFuture<?>> operationRunnable;
private final Expect expectation;
private final String skipReason;
public AsyncTestCase(String description, Supplier<CompletableFuture<?>> operationRunnable, Expect expectation) {
this(description, operationRunnable, expectation, null);
}
public AsyncTestCase(String description, Supplier<CompletableFuture<?>> operationRunnable, Expect expectation,
String skipReason) {
this.description = description;
this.operationRunnable = operationRunnable;
this.expectation = expectation;
this.skipReason = skipReason;
}
public Supplier<CompletableFuture<?>> operationRunnable() {
return operationRunnable;
}
public Expect expectation() {
return expectation;
}
public String skipReason() {
return skipReason;
}
@Override
public String toString() {
return description;
}
}
| 2,550 |
0 | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/BaseRuleSetClientTest.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.core.rules.testing;
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.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.net.URI;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider;
import software.amazon.awssdk.auth.token.credentials.StaticTokenProvider;
import software.amazon.awssdk.core.rules.testing.model.Expect;
import software.amazon.awssdk.endpoints.Endpoint;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.SdkHttpClient;
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.CompletableFutureUtils;
public abstract class BaseRuleSetClientTest {
protected static final AwsCredentialsProvider CREDENTIALS_PROVIDER =
StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"));
protected static final SdkTokenProvider TOKEN_PROVIDER = StaticTokenProvider.create(new TestSdkToken());
private static SdkHttpClient syncHttpClient;
private static SdkAsyncHttpClient asyncHttpClient;
@BeforeAll
public static void setup() {
syncHttpClient = mock(SdkHttpClient.class);
asyncHttpClient = mock(SdkAsyncHttpClient.class);
}
@BeforeEach
public void methodSetup() {
reset(syncHttpClient, asyncHttpClient);
when(syncHttpClient.prepareRequest(any())).thenThrow(new RuntimeException("Oops"));
when(asyncHttpClient.execute(any())).thenAnswer(i -> {
AsyncExecuteRequest req = i.getArgument(0, AsyncExecuteRequest.class);
SdkAsyncHttpResponseHandler responseHandler = req.responseHandler();
responseHandler.onError(new RuntimeException("Oops"));
return CompletableFutureUtils.failedFuture(new RuntimeException("Something went wrong"));
});
}
protected static void runAndVerify(SyncTestCase testCase) {
String skipReason = testCase.skipReason();
Assumptions.assumeTrue(skipReason == null, skipReason);
Expect expectation = testCase.expectation();
Runnable r = testCase.operationRunnable();
if (expectation.error() != null) {
assertThatThrownBy(r::run).hasMessageContaining(expectation.error());
} else {
assertThatThrownBy(r::run).hasMessageContaining("Oops");
ArgumentCaptor<HttpExecuteRequest> requestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
verify(syncHttpClient).prepareRequest(requestCaptor.capture());
URI requestUri = requestCaptor.getValue().httpRequest().getUri();
Endpoint expectedEndpoint = expectation.endpoint();
assertThat(requestUri.getScheme()).isEqualTo(expectedEndpoint.url().getScheme());
assertThat(requestUri.getHost()).isEqualTo(expectedEndpoint.url().getHost());
assertThat(requestUri.getRawPath()).startsWith(expectedEndpoint.url().getRawPath());
}
}
protected static void runAndVerify(AsyncTestCase testCase) {
String skipReason = testCase.skipReason();
Assumptions.assumeTrue(skipReason == null, skipReason);
Expect expectation = testCase.expectation();
Supplier<CompletableFuture<?>> r = testCase.operationRunnable();
CompletableFuture<?> executeFuture = r.get();
if (expectation.error() != null) {
assertThatThrownBy(executeFuture::get).hasMessageContaining(expectation.error());
} else {
assertThatThrownBy(executeFuture::get).hasMessageContaining("Oops");
ArgumentCaptor<AsyncExecuteRequest> requestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class);
verify(asyncHttpClient).execute(requestCaptor.capture());
URI requestUri = requestCaptor.getValue().request().getUri();
Endpoint expectedEndpoint = expectation.endpoint();
assertThat(requestUri.getScheme()).isEqualTo(expectedEndpoint.url().getScheme());
assertThat(requestUri.getHost()).isEqualTo(expectedEndpoint.url().getHost());
}
}
protected static SdkHttpClient getSyncHttpClient() {
return syncHttpClient;
}
protected static SdkAsyncHttpClient getAsyncHttpClient() {
return asyncHttpClient;
}
private static class TestSdkToken implements SdkToken {
@Override
public String token() {
return "TOKEN";
}
@Override
public Optional<Instant> expirationTime() {
return Optional.empty();
}
}
}
| 2,551 |
0 | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/BaseEndpointProviderTest.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.core.rules.testing;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.function.Supplier;
import software.amazon.awssdk.awscore.endpoints.AwsEndpointAttribute;
import software.amazon.awssdk.core.rules.testing.model.Expect;
import software.amazon.awssdk.endpoints.Endpoint;
public class BaseEndpointProviderTest {
protected final void verify(EndpointProviderTestCase tc) {
Expect expect = tc.getExpect();
Supplier<Endpoint> testMethod = tc.getTestMethod();
if (expect.error() != null) {
assertThatThrownBy(testMethod::get).hasMessageContaining(expect.error());
} else {
Endpoint actualEndpoint = testMethod.get();
Endpoint expectedEndpoint = expect.endpoint();
assertThat(actualEndpoint.url()).isEqualTo(expectedEndpoint.url());
assertThat(actualEndpoint.headers()).isEqualTo(expectedEndpoint.headers());
AwsEndpointAttribute.values().forEach(attr -> {
if (expectedEndpoint.attribute(attr) != null) {
assertThat(actualEndpoint.attribute(attr)).isEqualTo(expectedEndpoint.attribute(attr));
} else {
assertThat(actualEndpoint.attribute(attr)).isNull();
}
});
}
}
}
| 2,552 |
0 | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/SyncTestCase.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.core.rules.testing;
import software.amazon.awssdk.core.rules.testing.model.Expect;
public final class SyncTestCase {
private final String description;
private final Runnable operationRunnable;
private final Expect expectation;
private final String skipReason;
public SyncTestCase(String description, Runnable operationRunnable, Expect expectation) {
this(description, operationRunnable, expectation, null);
}
public SyncTestCase(String description, Runnable operationRunnable, Expect expectation, String skipReason) {
this.description = description;
this.operationRunnable = operationRunnable;
this.expectation = expectation;
this.skipReason = skipReason;
}
public Runnable operationRunnable() {
return operationRunnable;
}
public Expect expectation() {
return expectation;
}
public String skipReason() {
return skipReason;
}
@Override
public String toString() {
return description;
}
}
| 2,553 |
0 | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/util/EmptyPublisher.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.core.rules.testing.util;
import io.reactivex.rxjava3.core.Flowable;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
public class EmptyPublisher<T> implements Publisher<T> {
@Override
public void subscribe(Subscriber<? super T> subscriber) {
Publisher<T> empty = Flowable.empty();
empty.subscribe(subscriber);
}
}
| 2,554 |
0 | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/model/ParamInfo.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.core.rules.testing.model;
public class ParamInfo {
private String builtIn;
private ParamInfo(Builder b) {
this.builtIn = b.builtIn;
}
public String builtIn() {
return builtIn;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String builtIn;
public Builder builtIn(String builtIn) {
this.builtIn = builtIn;
return this;
}
public ParamInfo build() {
return new ParamInfo(this);
}
}
}
| 2,555 |
0 | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/model/Expect.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.core.rules.testing.model;
import software.amazon.awssdk.endpoints.Endpoint;
public class Expect {
private Endpoint endpoint;
private String error;
private Expect(Builder b) {
this.endpoint = b.endpoint;
this.error = b.error;
}
public Endpoint endpoint() {
return endpoint;
}
public String error() {
return error;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Endpoint endpoint;
private String error;
public Builder endpoint(Endpoint endpoint) {
this.endpoint = endpoint;
return this;
}
public Builder error(String error) {
this.error = error;
return this;
}
public Expect build() {
return new Expect(this);
}
}
}
| 2,556 |
0 | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/model/EndpointTest.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.core.rules.testing.model;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
import java.util.Map;
public class EndpointTest {
private String documentation;
private Map<String, JsonNode> params;
private List<String> tags;
private Expect expect;
public String getDocumentation() {
return documentation;
}
public void setDocumentation(String documentation) {
this.documentation = documentation;
}
public Map<String, JsonNode> getParams() {
return params;
}
public void setParams(Map<String, JsonNode> params) {
this.params = params;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public Expect getExpect() {
return expect;
}
public void setExpect(Expect expect) {
this.expect = expect;
}
}
| 2,557 |
0 | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing | Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/model/EndpointTestSuite.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.core.rules.testing.model;
import java.util.List;
public final class EndpointTestSuite {
private String service;
private String version;
private List<EndpointTest> testCases;
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public List<EndpointTest> getTestCases() {
return testCases;
}
public void setTestCases(List<EndpointTest> testCases) {
this.testCases = testCases;
}
}
| 2,558 |
0 | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/module-info.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.
*/
module software.amazon.awssdk.modulepath.tests {
requires software.amazon.awssdk.regions;
requires software.amazon.awssdk.http.urlconnection;
requires software.amazon.awssdk.http.apache;
requires software.amazon.awssdk.http.nio.netty;
requires software.amazon.awssdk.http;
requires software.amazon.awssdk.core;
requires software.amazon.awssdk.awscore;
requires software.amazon.awssdk.auth;
requires software.amazon.awssdk.services.s3;
requires software.amazon.awssdk.protocol.tests;
requires org.reactivestreams;
requires software.amazon.awssdk.utils;
requires software.amazon.awssdk.testutils.service;
requires org.slf4j;
requires slf4j.simple;
}
| 2,559 |
0 | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/IntegTestsRunner.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.modulepath.tests;
import java.util.ArrayList;
import java.util.List;
import software.amazon.awssdk.modulepath.tests.integtests.BaseApiCall;
import software.amazon.awssdk.modulepath.tests.integtests.S3ApiCall;
/**
* Tests runner to test module path on real service.
*/
public class IntegTestsRunner {
private IntegTestsRunner() {
}
public static void main(String... args) {
List<BaseApiCall> tests = new ArrayList<>();
tests.add(new S3ApiCall());
tests.forEach(test -> {
test.usingApacheClient();
test.usingUrlConnectionClient();
test.usingNettyClient();
});
}
}
| 2,560 |
0 | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/MockTestsRunner.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.modulepath.tests;
import java.util.ArrayList;
import java.util.List;
import software.amazon.awssdk.modulepath.tests.mocktests.BaseMockApiCall;
import software.amazon.awssdk.modulepath.tests.mocktests.JsonProtocolApiCall;
import software.amazon.awssdk.modulepath.tests.mocktests.XmlProtocolApiCall;
/**
* Executor to run mock tests on module path.
*/
public class MockTestsRunner {
private MockTestsRunner() {
}
public static void main(String... args) {
List<BaseMockApiCall> tests = new ArrayList<>();
tests.add(new XmlProtocolApiCall());
tests.add(new JsonProtocolApiCall());
tests.forEach(t -> {
t.successfulApiCall();
t.failedApiCall();
t.successfulAsyncApiCall();
t.failedAsyncApiCall();
});
}
}
| 2,561 |
0 | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/integtests/S3ApiCall.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.modulepath.tests.integtests;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
public class S3ApiCall extends BaseApiCall {
private S3Client s3Client = S3Client.builder()
.region(Region.US_WEST_2)
.httpClient(ApacheHttpClient.builder().build())
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.build();
private S3Client s3ClientWithHttpUrlConnection = S3Client.builder()
.region(Region.US_WEST_2)
.httpClient(UrlConnectionHttpClient.builder().build())
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build();
private S3AsyncClient s3ClientWithNettyClient = S3AsyncClient.builder()
.region(Region.US_WEST_2)
.httpClient(NettyNioAsyncHttpClient.builder().build())
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build();
public S3ApiCall() {
super("s3");
}
@Override
public Runnable apacheClientRunnable() {
return () -> s3Client.listBuckets();
}
@Override
public Runnable urlHttpConnectionClientRunnable() {
return () -> s3ClientWithHttpUrlConnection.listBuckets();
}
@Override
public Runnable nettyClientRunnable() {
return () -> s3ClientWithNettyClient.listBuckets().join();
}
}
| 2,562 |
0 | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/integtests/BaseApiCall.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.modulepath.tests.integtests;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.testutils.service.AwsTestBase;
/**
* Base Api Call class
*/
public abstract class BaseApiCall extends AwsTestBase {
private static final Logger logger = LoggerFactory.getLogger(BaseApiCall.class);
private final String serviceName;
public BaseApiCall(String serviceName) {
this.serviceName = serviceName;
}
public void usingApacheClient() {
logger.info("Starting testing {} client with Apache http client", serviceName);
apacheClientRunnable().run();
}
public void usingUrlConnectionClient() {
logger.info("Starting testing {} client with url connection http client", serviceName);
urlHttpConnectionClientRunnable().run();
}
public void usingNettyClient() {
logger.info("Starting testing {} client with netty client", serviceName);
nettyClientRunnable().run();
}
public abstract Runnable apacheClientRunnable();
public abstract Runnable urlHttpConnectionClientRunnable();
public abstract Runnable nettyClientRunnable();
}
| 2,563 |
0 | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/mocktests/JsonProtocolApiCall.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.modulepath.tests.mocktests;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
/**
* Protocol tests for json protocol
*/
public class JsonProtocolApiCall extends BaseMockApiCall {
private static final Logger logger = LoggerFactory.getLogger(JsonProtocolApiCall.class);
private ProtocolRestJsonClient client;
private ProtocolRestJsonAsyncClient asyncClient;
public JsonProtocolApiCall() {
super("json");
this.client = ProtocolRestJsonClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(
"akid", "skid")))
.region(Region.US_EAST_1)
.httpClient(mockHttpClient)
.build();
this.asyncClient = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(
StaticCredentialsProvider.create(AwsBasicCredentials.create(
"akid", "skid")))
.region(Region.US_EAST_1)
.httpClient(mockAyncHttpClient)
.build();
}
@Override
Runnable runnable() {
return () -> client.allTypes();
}
@Override
Runnable asyncRunnable() {
return () -> asyncClient.allTypes().join();
}
}
| 2,564 |
0 | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/mocktests/XmlProtocolApiCall.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.modulepath.tests.mocktests;
import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient;
import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient;
/**
* Protocol tests for xml protocol
*/
public class XmlProtocolApiCall extends BaseMockApiCall {
private ProtocolRestXmlClient client;
private ProtocolRestXmlAsyncClient asyncClient;
public XmlProtocolApiCall() {
super("xml");
client = ProtocolRestXmlClient.builder().httpClient(mockHttpClient).build();
asyncClient = ProtocolRestXmlAsyncClient.builder().httpClient(mockAyncHttpClient).build();
}
@Override
Runnable runnable() {
return () -> client.allTypes();
}
@Override
Runnable asyncRunnable() {
return () -> asyncClient.allTypes().join();
}
}
| 2,565 |
0 | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/mocktests/MockHttpClient.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.modulepath.tests.mocktests;
import java.util.ArrayList;
import java.util.List;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpRequest;
/**
* Mock implementation of {@link SdkHttpClient}.
*/
public final class MockHttpClient implements SdkHttpClient {
private final List<SdkHttpRequest> capturedRequests = new ArrayList<>();
private HttpExecuteResponse nextResponse;
@Override
public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) {
capturedRequests.add(request.httpRequest());
return new ExecutableHttpRequest() {
@Override
public HttpExecuteResponse call() {
return nextResponse;
}
@Override
public void abort() {
}
};
}
@Override
public void close() {
}
/**
* Resets this mock by clearing any captured requests and wiping any stubbed responses.
*/
public void reset() {
this.capturedRequests.clear();
this.nextResponse = null;
}
/**
* Sets up the next HTTP response that will be returned by the mock.
*
* @param nextResponse Next {@link HttpExecuteResponse} to return from
* {@link #prepareRequest(HttpExecuteRequest)}
*/
public void stubNextResponse(HttpExecuteResponse nextResponse) {
this.nextResponse = nextResponse;
}
/**
* @return The last executed request that went through this mock client.
* @throws IllegalStateException If no requests have been captured.
*/
public SdkHttpRequest getLastRequest() {
if (capturedRequests.isEmpty()) {
throw new IllegalStateException("No requests were captured by the mock");
}
return capturedRequests.get(capturedRequests.size() - 1);
}
}
| 2,566 |
0 | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/mocktests/BaseMockApiCall.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.modulepath.tests.mocktests;
import java.io.ByteArrayInputStream;
import java.util.concurrent.CompletionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpResponse;
/**
* Base classes to mock sync and async api calls.
*/
public abstract class BaseMockApiCall {
private static final Logger logger = LoggerFactory.getLogger(BaseMockApiCall.class);
protected final MockHttpClient mockHttpClient;
protected final MockAyncHttpClient mockAyncHttpClient;
private final String protocol;
public BaseMockApiCall(String protocol) {
this.protocol = protocol;
this.mockHttpClient = new MockHttpClient();
this.mockAyncHttpClient = new MockAyncHttpClient();
}
public void successfulApiCall() {
logger.info("stubing successful api call for {} protocol", protocol);
mockHttpClient.stubNextResponse(successResponse(protocol));
runnable().run();
mockHttpClient.reset();
}
public void failedApiCall() {
logger.info("stubing failed api call for {} protocol", protocol);
mockHttpClient.stubNextResponse(errorResponse(protocol));
try {
runnable().run();
} catch (AwsServiceException e) {
logger.info("Received expected service exception", e.getMessage());
}
mockHttpClient.reset();
}
public void successfulAsyncApiCall() {
logger.info("stubing successful async api call for {} protocol", protocol);
mockAyncHttpClient.stubNextResponse(successResponse(protocol));
asyncRunnable().run();
mockAyncHttpClient.reset();
}
public void failedAsyncApiCall() {
logger.info("stubing failed async api call for {} protocol", protocol);
mockAyncHttpClient.stubNextResponse(errorResponse(protocol));
try {
asyncRunnable().run();
} catch (CompletionException e) {
if (e.getCause() instanceof AwsServiceException) {
logger.info("expected service exception {}", e.getMessage());
} else {
throw new RuntimeException("Unexpected exception is thrown");
}
}
mockAyncHttpClient.reset();
}
abstract Runnable runnable();
abstract Runnable asyncRunnable();
private HttpExecuteResponse successResponse(String protocol) {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(200)
.build())
.responseBody(generateContent(protocol))
.build();
}
private HttpExecuteResponse errorResponse(String protocol) {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(500)
.build())
.responseBody(generateContent(protocol))
.build();
}
private AbortableInputStream generateContent(String protocol) {
String content;
switch (protocol) {
case "xml":
content = "<foo></foo>";
break;
default:
case "json":
content = "{}";
}
return AbortableInputStream.create(new ByteArrayInputStream(content.getBytes()));
}
}
| 2,567 |
0 | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests | Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/mocktests/MockAyncHttpClient.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.modulepath.tests.mocktests;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.HttpExecuteResponse;
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;
import software.amazon.awssdk.utils.IoUtils;
/**
* Mock implementation of {@link SdkAsyncHttpClient}.
*/
public final class MockAyncHttpClient implements SdkAsyncHttpClient {
private final List<SdkHttpRequest> capturedRequests = new ArrayList<>();
private HttpExecuteResponse nextResponse;
@Override
public CompletableFuture<Void> execute(AsyncExecuteRequest request) {
capturedRequests.add(request.request());
request.responseHandler().onHeaders(nextResponse.httpResponse());
request.responseHandler().onStream(new SdkHttpContentPublisher() {
byte[] content = nextResponse.responseBody().map(p -> invokeSafely(() -> IoUtils.toByteArray(p)))
.orElseGet(() -> new byte[0]);
@Override
public Optional<Long> contentLength() {
return Optional.of((long) content.length);
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
s.onSubscribe(new Subscription() {
private boolean running = true;
@Override
public void request(long n) {
if (n <= 0) {
running = false;
s.onError(new IllegalArgumentException("Demand must be positive"));
} else if (running) {
running = false;
s.onNext(ByteBuffer.wrap(content));
s.onComplete();
}
}
@Override
public void cancel() {
running = false;
}
});
}
});
return CompletableFuture.completedFuture(null);
}
@Override
public void close() {
}
/**
* Resets this mock by clearing any captured requests and wiping any stubbed responses.
*/
public void reset() {
this.capturedRequests.clear();
this.nextResponse = null;
}
public void stubNextResponse(HttpExecuteResponse nextResponse) {
this.nextResponse = nextResponse;
}
}
| 2,568 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/SraIdentityResolutionUsingPluginsTest.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.services;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
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 java.util.concurrent.CompletableFuture;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.SdkPlugin;
import software.amazon.awssdk.core.SdkServiceClientConfiguration;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.ResolveIdentityRequest;
import software.amazon.awssdk.services.protocolquery.ProtocolQueryClient;
import software.amazon.awssdk.services.protocolquery.ProtocolQueryServiceClientConfiguration;
import software.amazon.awssdk.utils.Validate;
@RunWith(MockitoJUnitRunner.class)
public class SraIdentityResolutionUsingPluginsTest {
@Mock
private AwsCredentialsProvider credentialsProvider;
@Test
public void testIdentityBasedPluginsResolutionIsUsedAndNotAnotherIdentityResolution() {
SdkHttpClient mockClient = mock(SdkHttpClient.class);
when(mockClient.prepareRequest(any())).thenThrow(new RuntimeException("boom"));
when(credentialsProvider.identityType()).thenReturn(AwsCredentialsIdentity.class);
when(credentialsProvider.resolveIdentity(any(ResolveIdentityRequest.class)))
.thenReturn(CompletableFuture.completedFuture(AwsBasicCredentials.create("akid1", "skid2")));
ProtocolQueryClient syncClient = ProtocolQueryClient
.builder()
.httpClient(mockClient)
.addPlugin(new TestPlugin(credentialsProvider))
// Below is necessary to create the test case where, addCredentialsToExecutionAttributes was getting called before
.overrideConfiguration(ClientOverrideConfiguration.builder().build())
.build();
assertThatThrownBy(() -> syncClient.allTypes(r -> {})).hasMessageContaining("boom");
verify(credentialsProvider, atLeastOnce()).identityType();
// This asserts that the identity used is the one from resolveIdentity() called by SRA AuthSchemeInterceptor and not
// from another call like from AwsCredentialsAuthorizationStrategy.addCredentialsToExecutionAttributes, asserted by
// combination of times(1) and verifyNoMoreInteractions.
verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class));
verifyNoMoreInteractions(credentialsProvider);
}
static class TestPlugin implements SdkPlugin {
private final AwsCredentialsProvider credentialsProvider;
TestPlugin(AwsCredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
}
@Override
public void configureClient(SdkServiceClientConfiguration.Builder config) {
ProtocolQueryServiceClientConfiguration.Builder builder =
Validate.isInstanceOf(ProtocolQueryServiceClientConfiguration.Builder.class,
config,
"Expecting an instance of " +
ProtocolQueryServiceClientConfiguration.class);
builder.credentialsProvider(credentialsProvider);
}
}
}
| 2,569 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/FipsEndpointTest.java | package software.amazon.awssdk.services;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
import software.amazon.awssdk.utils.StringInputStream;
import software.amazon.awssdk.utils.Validate;
@RunWith(Parameterized.class)
public class FipsEndpointTest {
@Parameterized.Parameter
public TestCase testCase;
@Test
public void resolvesCorrectEndpoint() {
String systemPropertyBeforeTest = System.getProperty(SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.property());
EnvironmentVariableHelper helper = new EnvironmentVariableHelper();
try {
ProtocolRestJsonClientBuilder builder =
ProtocolRestJsonClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(AnonymousCredentialsProvider.create());
if (testCase.clientSetting != null) {
builder.fipsEnabled(testCase.clientSetting);
}
if (testCase.systemPropSetting != null) {
System.setProperty(SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.property(), testCase.systemPropSetting);
}
if (testCase.envVarSetting != null) {
helper.set(SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.environmentVariable(), testCase.envVarSetting);
}
ProfileFile.Builder profileFile = ProfileFile.builder().type(ProfileFile.Type.CONFIGURATION);
if (testCase.profileSetting != null) {
profileFile.content(new StringInputStream("[default]\n" +
ProfileProperty.USE_FIPS_ENDPOINT + " = " + testCase.profileSetting));
} else {
profileFile.content(new StringInputStream(""));
}
EndpointCapturingInterceptor interceptor = new EndpointCapturingInterceptor();
builder.overrideConfiguration(c -> c.defaultProfileFile(profileFile.build())
.defaultProfileName("default")
.addExecutionInterceptor(interceptor));
if (testCase instanceof SuccessCase) {
ProtocolRestJsonClient client = builder.build();
try {
client.allTypes();
} catch (EndpointCapturingInterceptor.CaptureCompletedException e) {
// Expected
}
boolean expectedFipsEnabled = ((SuccessCase) testCase).expectedValue;
String expectedEndpoint = expectedFipsEnabled
? "https://customresponsemetadata-fips.us-west-2.amazonaws.com/2016-03-11/allTypes"
: "https://customresponsemetadata.us-west-2.amazonaws.com/2016-03-11/allTypes";
assertThat(interceptor.endpoints()).singleElement().isEqualTo(expectedEndpoint);
} else {
FailureCase failure = Validate.isInstanceOf(FailureCase.class, testCase, "Unexpected test case type.");
assertThatThrownBy(builder::build).hasMessageContaining(failure.exceptionMessage);
}
} finally {
if (systemPropertyBeforeTest != null) {
System.setProperty(SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.property(), systemPropertyBeforeTest);
} else {
System.clearProperty(SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.property());
}
helper.reset();
}
}
@Parameterized.Parameters(name = "{0}")
public static Iterable<TestCase> testCases() {
return Arrays.asList(new SuccessCase(true, "false", "false", "false", true, "Client highest priority (true)"),
new SuccessCase(false, "true", "true", "true", false, "Client highest priority (false)"),
new SuccessCase(null, "true", "false", "false", true, "System property second priority (true)"),
new SuccessCase(null, "false", "true", "true", false, "System property second priority (false)"),
new SuccessCase(null, null, "true", "false", true, "Env var third priority (true)"),
new SuccessCase(null, null, "false", "true", false, "Env var third priority (false)"),
new SuccessCase(null, null, null, "true", true, "Profile last priority (true)"),
new SuccessCase(null, null, null, "false", false, "Profile last priority (false)"),
new SuccessCase(null, null, null, null, false, "Default is false."),
new SuccessCase(null, "tRuE", null, null, true, "System property is not case sensitive."),
new SuccessCase(null, null, "tRuE", null, true, "Env var is not case sensitive."),
new SuccessCase(null, null, null, "tRuE", true, "Profile property is not case sensitive."),
new FailureCase(null, "FOO", null, null, "FOO", "Invalid system property values fail."),
new FailureCase(null, null, "FOO", null, "FOO", "Invalid env var values fail."),
new FailureCase(null, null, null, "FOO", "FOO", "Invalid profile values fail."));
}
public static class TestCase {
private final Boolean clientSetting;
private final String envVarSetting;
private final String systemPropSetting;
private final String profileSetting;
private final String caseName;
public TestCase(Boolean clientSetting, String systemPropSetting, String envVarSetting, String profileSetting,
String caseName) {
this.clientSetting = clientSetting;
this.envVarSetting = envVarSetting;
this.systemPropSetting = systemPropSetting;
this.profileSetting = profileSetting;
this.caseName = caseName;
}
@Override
public String toString() {
return caseName;
}
}
public static class SuccessCase extends TestCase {
private final boolean expectedValue;
public SuccessCase(Boolean clientSetting,
String systemPropSetting,
String envVarSetting,
String profileSetting,
boolean expectedValue,
String caseName) {
super(clientSetting, systemPropSetting, envVarSetting, profileSetting, caseName);
this.expectedValue = expectedValue;
}
}
private static class FailureCase extends TestCase {
private final String exceptionMessage;
public FailureCase(Boolean clientSetting,
String systemPropSetting,
String envVarSetting,
String profileSetting,
String exceptionMessage,
String caseName) {
super(clientSetting, systemPropSetting, envVarSetting, profileSetting, caseName);
this.exceptionMessage = exceptionMessage;
}
}
}
| 2,570 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/HostPrefixTest.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.services;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.net.URI;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
import software.amazon.awssdk.utils.StringInputStream;
import software.amazon.awssdk.utils.builder.SdkBuilder;
public class HostPrefixTest {
private MockSyncHttpClient mockHttpClient;
private ProtocolRestJsonClient client;
private MockAsyncHttpClient mockAsyncClient;
private ProtocolRestJsonAsyncClient asyncClient;
@BeforeEach
public void setupClient() {
mockHttpClient = new MockSyncHttpClient();
mockAsyncClient = new MockAsyncHttpClient();
client = ProtocolRestJsonClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid",
"skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost"))
.httpClient(mockHttpClient)
.build();
asyncClient = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost"))
.httpClient(mockAsyncClient)
.build();
}
@Test
public void invalidHostPrefix_shouldThrowException() {
assertThatThrownBy(() -> client.operationWithHostPrefix(b -> b.stringMember("123#")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("The provided operationWithHostPrefixRequest is not valid: the 'StringMember' component must "
+ "match the pattern \"[A-Za-z0-9\\-]+\".");
assertThatThrownBy(() -> asyncClient.operationWithHostPrefix(b -> b.stringMember("123#")).join())
.hasCauseInstanceOf(IllegalArgumentException.class).hasMessageContaining("The provided operationWithHostPrefixRequest is not valid: the 'StringMember' component must match the pattern \"[A-Za-z0-9\\-]+\".");
}
@Test
public void nullHostPrefix_shouldThrowException() {
assertThatThrownBy(() -> client.operationWithHostPrefix(SdkBuilder::build))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("component is missing");
assertThatThrownBy(() -> asyncClient.operationWithHostPrefix(SdkBuilder::build).join())
.hasCauseInstanceOf(IllegalArgumentException.class).hasMessageContaining("component is missing");
}
@Test
public void syncValidHostPrefix_shouldPrefixEndpoint() {
mockHttpClient.stubNextResponse(HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder().statusCode(200)
.build())
.responseBody(AbortableInputStream.create(new StringInputStream("")))
.build());
client.operationWithHostPrefix(b -> b.stringMember("123"));
assertThat(mockHttpClient.getLastRequest().getUri().getHost()).isEqualTo("123-foo.localhost");
}
@Test
public void asyncValidHostPrefix_shouldPrefixEndpoint() {
mockAsyncClient.stubNextResponse(HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder().statusCode(200)
.build())
.responseBody(AbortableInputStream.create(new StringInputStream("")))
.build());
asyncClient.operationWithHostPrefix(b -> b.stringMember("123")).join();
assertThat(mockAsyncClient.getLastRequest().getUri().getHost()).isEqualTo("123-foo.localhost");
}
}
| 2,571 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/EndpointDiscoveryAndEndpointOverrideTest.java | package software.amazon.awssdk.services;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletionException;
import java.util.function.Consumer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder;
import software.amazon.awssdk.core.client.builder.SdkClientBuilder;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.endpointdiscoveryrequiredtest.EndpointDiscoveryRequiredTestAsyncClient;
import software.amazon.awssdk.services.endpointdiscoveryrequiredtest.EndpointDiscoveryRequiredTestClient;
import software.amazon.awssdk.services.endpointdiscoveryrequiredwithcustomizationtest.EndpointDiscoveryRequiredWithCustomizationTestAsyncClient;
import software.amazon.awssdk.services.endpointdiscoveryrequiredwithcustomizationtest.EndpointDiscoveryRequiredWithCustomizationTestClient;
import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestAsyncClient;
import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestClient;
/**
* Verify the behavior of endpoint discovery when combined with endpoint override configuration.
*/
@RunWith(Parameterized.class)
public class EndpointDiscoveryAndEndpointOverrideTest {
private static final String OPTIONAL_SERVICE_ENDPOINT = "https://awsendpointdiscoverytestservice.us-west-2.amazonaws.com";
private static final String REQUIRED_SERVICE_ENDPOINT = "https://awsendpointdiscoveryrequiredtestservice.us-west-2.amazonaws.com";
private static final String REQUIRED_CUSTOMIZED_SERVICE_ENDPOINT = "https://awsendpointdiscoveryrequiredwithcustomizationtestservice.us-west-2.amazonaws.com";
private static final String ENDPOINT_OVERRIDE = "https://endpointoverride";
private static final List<TestCase<?>> ALL_TEST_CASES = new ArrayList<>();
private final TestCase<?> testCase;
static {
// This first case (case 0/1) is different than other SDKs/the SEP. This should probably actually throw an exception.
ALL_TEST_CASES.addAll(endpointDiscoveryOptionalCases(true, true, ENDPOINT_OVERRIDE + "/DescribeEndpoints", ENDPOINT_OVERRIDE + "/TestDiscoveryOptional"));
ALL_TEST_CASES.addAll(endpointDiscoveryOptionalCases(true, false, OPTIONAL_SERVICE_ENDPOINT + "/DescribeEndpoints", OPTIONAL_SERVICE_ENDPOINT + "/TestDiscoveryOptional"));
ALL_TEST_CASES.addAll(endpointDiscoveryOptionalCases(false, true, ENDPOINT_OVERRIDE + "/TestDiscoveryOptional"));
ALL_TEST_CASES.addAll(endpointDiscoveryOptionalCases(false, false, OPTIONAL_SERVICE_ENDPOINT + "/TestDiscoveryOptional"));
ALL_TEST_CASES.addAll(endpointDiscoveryRequiredCases(true, true));
ALL_TEST_CASES.addAll(endpointDiscoveryRequiredCases(true, false, REQUIRED_SERVICE_ENDPOINT + "/DescribeEndpoints"));
ALL_TEST_CASES.addAll(endpointDiscoveryRequiredCases(false, true));
ALL_TEST_CASES.addAll(endpointDiscoveryRequiredCases(false, false));
// These cases are different from what one would expect. Even though endpoint discovery is required (based on the model),
// if the customer specifies an endpoint override AND the service is customized, we actually bypass endpoint discovery.
ALL_TEST_CASES.addAll(endpointDiscoveryRequiredAndCustomizedCases(true, true, ENDPOINT_OVERRIDE + "/TestDiscoveryRequired"));
ALL_TEST_CASES.addAll(endpointDiscoveryRequiredAndCustomizedCases(true, false, REQUIRED_CUSTOMIZED_SERVICE_ENDPOINT + "/DescribeEndpoints"));
ALL_TEST_CASES.addAll(endpointDiscoveryRequiredAndCustomizedCases(false, true, ENDPOINT_OVERRIDE + "/TestDiscoveryRequired"));
ALL_TEST_CASES.addAll(endpointDiscoveryRequiredAndCustomizedCases(false, false));
}
public EndpointDiscoveryAndEndpointOverrideTest(TestCase<?> testCase) {
this.testCase = testCase;
}
@Before
public void reset() {
EndpointCapturingInterceptor.reset();
}
@Parameterized.Parameters(name = "{index} - {0}")
public static List<TestCase<?>> testCases() {
return ALL_TEST_CASES;
}
@Test(timeout = 5_000)
public void invokeTestCase() {
try {
testCase.callClient();
Assert.fail();
} catch (Throwable e) {
// Unwrap async exceptions so that they can be tested the same as async ones.
if (e instanceof CompletionException) {
e = e.getCause();
}
if (testCase.expectedPaths.length > 0) {
// We're using fake endpoints, so we expect even "valid" requests to fail because of unknown host exceptions.
assertThat(e.getCause()).hasRootCauseInstanceOf(UnknownHostException.class);
} else {
// If the requests are not expected to go through, we expect to see illegal state exceptions because the
// client is configured incorrectly.
assertThat(e).isInstanceOf(IllegalStateException.class);
}
}
if (testCase.enforcePathOrder) {
assertThat(EndpointCapturingInterceptor.ENDPOINTS).containsExactly(testCase.expectedPaths);
} else {
// Async is involved when order doesn't matter, so wait a little while until the expected number of paths arrive.
while (EndpointCapturingInterceptor.ENDPOINTS.size() < testCase.expectedPaths.length) {
Thread.yield();
}
assertThat(EndpointCapturingInterceptor.ENDPOINTS).containsExactlyInAnyOrder(testCase.expectedPaths);
}
}
private static List<TestCase<?>> endpointDiscoveryOptionalCases(boolean endpointDiscoveryEnabled,
boolean endpointOverridden,
String... expectedEndpoints) {
TestCase<?> syncCase = new TestCase<>(createClient(EndpointDiscoveryTestClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled),
endpointOverridden),
c -> c.testDiscoveryOptional(r -> {}),
caseName(EndpointDiscoveryTestClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints),
false,
expectedEndpoints);
TestCase<?> asyncCase = new TestCase<>(createClient(EndpointDiscoveryTestAsyncClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled),
endpointOverridden),
c -> c.testDiscoveryOptional(r -> {}).join(),
caseName(EndpointDiscoveryTestAsyncClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints),
false,
expectedEndpoints);
return Arrays.asList(syncCase, asyncCase);
}
private static List<TestCase<?>> endpointDiscoveryRequiredCases(boolean endpointDiscoveryEnabled,
boolean endpointOverridden,
String... expectedEndpoints) {
TestCase<?> syncCase = new TestCase<>(createClient(EndpointDiscoveryRequiredTestClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled),
endpointOverridden),
c -> c.testDiscoveryRequired(r -> {}),
caseName(EndpointDiscoveryRequiredTestClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints),
true,
expectedEndpoints);
TestCase<?> asyncCase = new TestCase<>(createClient(EndpointDiscoveryRequiredTestAsyncClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled),
endpointOverridden),
c -> c.testDiscoveryRequired(r -> {}).join(),
caseName(EndpointDiscoveryRequiredTestAsyncClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints),
true,
expectedEndpoints);
return Arrays.asList(syncCase, asyncCase);
}
private static List<TestCase<?>> endpointDiscoveryRequiredAndCustomizedCases(boolean endpointDiscoveryEnabled,
boolean endpointOverridden,
String... expectedEndpoints) {
TestCase<?> syncCase = new TestCase<>(createClient(EndpointDiscoveryRequiredWithCustomizationTestClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled),
endpointOverridden),
c -> c.testDiscoveryRequired(r -> {}),
caseName(EndpointDiscoveryRequiredWithCustomizationTestClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints),
true,
expectedEndpoints);
TestCase<?> asyncCase = new TestCase<>(createClient(EndpointDiscoveryRequiredWithCustomizationTestAsyncClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled),
endpointOverridden),
c -> c.testDiscoveryRequired(r -> {}).join(),
caseName(EndpointDiscoveryRequiredWithCustomizationTestAsyncClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints),
true,
expectedEndpoints);
return Arrays.asList(syncCase, asyncCase);
}
private static <T> T createClient(AwsClientBuilder<?, T> clientBuilder,
boolean endpointOverridden) {
return clientBuilder.region(Region.US_WEST_2)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.applyMutation(c -> addEndpointOverride(c, endpointOverridden))
.overrideConfiguration(c -> c.retryPolicy(p -> p.numRetries(0))
.addExecutionInterceptor(new EndpointCapturingInterceptor()))
.build();
}
private static String caseName(Class<?> client,
boolean endpointDiscoveryEnabled,
boolean endpointOverridden,
String... expectedEndpoints) {
return "(Client=" + client.getSimpleName() +
", DiscoveryEnabled=" + endpointDiscoveryEnabled +
", EndpointOverridden=" + endpointOverridden +
") => (ExpectedEndpoints=" + Arrays.toString(expectedEndpoints) + ")";
}
private static void addEndpointOverride(SdkClientBuilder<?, ?> builder, boolean endpointOverridden) {
if (endpointOverridden) {
builder.endpointOverride(URI.create(ENDPOINT_OVERRIDE));
}
}
private static class TestCase<T> {
private final T client;
private final Consumer<T> methodCall;
private final String caseName;
private final boolean enforcePathOrder;
private final String[] expectedPaths;
private TestCase(T client, Consumer<T> methodCall, String caseName, boolean enforcePathOrder, String... expectedPaths) {
this.client = client;
this.methodCall = methodCall;
this.caseName = caseName;
this.enforcePathOrder = enforcePathOrder;
this.expectedPaths = expectedPaths;
}
private void callClient() {
methodCall.accept(client);
}
@Override
public String toString() {
return caseName;
}
}
private static class EndpointCapturingInterceptor implements ExecutionInterceptor {
private static final List<String> ENDPOINTS = Collections.synchronizedList(new ArrayList<>());
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
ENDPOINTS.add(context.httpRequest().getUri().toString());
}
private static void reset() {
ENDPOINTS.clear();
}
}
}
| 2,572 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/EndpointCapturingInterceptor.java | package software.amazon.awssdk.services;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
public class EndpointCapturingInterceptor implements ExecutionInterceptor {
private final List<String> endpoints = Collections.synchronizedList(new ArrayList<>());
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
endpoints.add(context.httpRequest().getUri().toString());
throw new CaptureCompletedException();
}
public List<String> endpoints() {
return endpoints;
}
private void reset() {
endpoints.clear();
}
public class CaptureCompletedException extends RuntimeException {
}
} | 2,573 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/ProfileFileConfigurationTest.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.services;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.awscore.AwsExecutionAttribute;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
import software.amazon.awssdk.utils.StringInputStream;
public class ProfileFileConfigurationTest {
@Test
public void profileIsHonoredForCredentialsAndRegion() {
EnvironmentVariableHelper.run(env -> {
env.remove(SdkSystemSetting.AWS_REGION);
env.remove(SdkSystemSetting.AWS_ACCESS_KEY_ID);
env.remove(SdkSystemSetting.AWS_SECRET_ACCESS_KEY);
String profileContent = "[profile foo]\n" +
"region = us-banana-46\n" +
"aws_access_key_id = profileIsHonoredForCredentials_akid\n" +
"aws_secret_access_key = profileIsHonoredForCredentials_skid";
String profileName = "foo";
Signer signer = mock(Signer.class);
ProtocolRestJsonClient client =
ProtocolRestJsonClient.builder()
.overrideConfiguration(overrideConfig(profileContent, profileName, signer))
.build();
Mockito.when(signer.sign(any(), any())).thenReturn(SdkHttpFullRequest.builder()
.protocol("https")
.host("test")
.method(SdkHttpMethod.GET)
.build());
try {
client.allTypes();
} catch (SdkClientException e) {
// expected
}
ArgumentCaptor<SdkHttpFullRequest> httpRequest = ArgumentCaptor.forClass(SdkHttpFullRequest.class);
ArgumentCaptor<ExecutionAttributes> attributes = ArgumentCaptor.forClass(ExecutionAttributes.class);
Mockito.verify(signer).sign(httpRequest.capture(), attributes.capture());
AwsCredentials credentials = attributes.getValue().getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS);
assertThat(credentials.accessKeyId()).isEqualTo("profileIsHonoredForCredentials_akid");
assertThat(credentials.secretAccessKey()).isEqualTo("profileIsHonoredForCredentials_skid");
Region region = attributes.getValue().getAttribute(AwsExecutionAttribute.AWS_REGION);
assertThat(region.id()).isEqualTo("us-banana-46");
assertThat(httpRequest.getValue().getUri().getHost()).contains("us-banana-46");
});
}
private ClientOverrideConfiguration overrideConfig(String profileContent, String profileName, Signer signer) {
return ClientOverrideConfiguration.builder()
.defaultProfileFile(profileFile(profileContent))
.defaultProfileName(profileName)
.retryPolicy(r -> r.numRetries(0))
.putAdvancedOption(SdkAdvancedClientOption.SIGNER, signer)
.build();
}
private ProfileFile profileFile(String content) {
return ProfileFile.builder()
.content(new StringInputStream(content))
.type(ProfileFile.Type.CONFIGURATION)
.build();
}
// TODO(sra-identity-and-auth): Should add test for the same using SRA way, to assert the identity in SignRequest and
// region SignerProperty are per profile.
// To do this, need ability to inject AuthScheme which uses mock HttpSigner. This is pending https://i.amazon.com/SMITHY-1450
}
| 2,574 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/TraceIdTest.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.services;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.awscore.interceptor.TraceIdExecutionInterceptor;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
import software.amazon.awssdk.utils.StringInputStream;
/**
* Verifies that the {@link TraceIdExecutionInterceptor} is actually wired up for AWS services.
*/
public class TraceIdTest {
@Test
public void traceIdInterceptorIsEnabled() {
EnvironmentVariableHelper.run(env -> {
env.set("AWS_LAMBDA_FUNCTION_NAME", "foo");
env.set("_X_AMZN_TRACE_ID", "bar");
try (MockSyncHttpClient mockHttpClient = new MockSyncHttpClient();
ProtocolRestJsonClient client = ProtocolRestJsonClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(AnonymousCredentialsProvider.create())
.httpClient(mockHttpClient)
.build()) {
mockHttpClient.stubNextResponse(HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(200)
.build())
.responseBody(AbortableInputStream.create(new StringInputStream("{}")))
.build());
client.allTypes();
assertThat(mockHttpClient.getLastRequest().firstMatchingHeader("X-Amzn-Trace-Id")).hasValue("bar");
}
});
}
}
| 2,575 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/BlockingAsyncRequestResponseBodyTest.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.services;
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.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.allRequests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.BlockingInputStreamAsyncRequestBody;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.async.BlockingOutputStreamAsyncRequestBody;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationRequest;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationResponse;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationRequest;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationResponse;
import software.amazon.awssdk.utils.StringInputStream;
import software.amazon.awssdk.utils.ThreadFactoryBuilder;
@Timeout(5)
public class BlockingAsyncRequestResponseBodyTest {
private final WireMockServer wireMock = new WireMockServer(0);
private ProtocolRestJsonAsyncClient client;
@BeforeEach
public void setup() {
wireMock.start();
client = ProtocolRestJsonAsyncClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(AnonymousCredentialsProvider.create())
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.build();
}
@Test
public void blockingWithExecutor_inputStreamWithMark_shouldRetry() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
int length = 1 << 20;
String content = RandomStringUtils.randomAscii(length);
StringInputStream stringInputStream = new StringInputStream(content);
BufferedInputStream bufferedInputStream = new BufferedInputStream(stringInputStream);
try {
wireMock.stubFor(post(anyUrl())
.inScenario("retry at connect reset")
.whenScenarioStateIs(Scenario.STARTED)
.willSetStateTo("first attempt")
.willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)));
wireMock.stubFor(post(anyUrl())
.inScenario("retry at connect reset")
.whenScenarioStateIs("first attempt")
.willSetStateTo("second attempt")
.willReturn(aResponse()
.withStatus(200)
.withBody("{}")));
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(),
AsyncRequestBody.fromInputStream(b -> b.inputStream(bufferedInputStream).contentLength(
(long) length).executor(executorService).maxReadLimit(length + 1))).join();
List<LoggedRequest> requests = wireMock.findAll(allRequests());
assertThat(requests.get(0))
.extracting(LoggedRequest::getBody)
.extracting(String::new)
.isEqualTo(content);
} finally {
executorService.shutdownNow();
}
}
@Test
public void blockingWithExecutor_sendsRightValues() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(),
AsyncRequestBody.fromInputStream(new StringInputStream("Hello"),
5L,
executorService))
.join();
List<LoggedRequest> requests = wireMock.findAll(allRequests());
assertThat(requests).singleElement()
.extracting(LoggedRequest::getBody)
.extracting(String::new)
.isEqualTo("Hello");
} finally {
executorService.shutdownNow();
}
}
@Test
public void blockingWithExecutor_canUnderUpload() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(),
AsyncRequestBody.fromInputStream(new StringInputStream("Hello"),
4L,
executorService))
.join();
List<LoggedRequest> requests = wireMock.findAll(allRequests());
assertThat(requests).singleElement()
.extracting(LoggedRequest::getBody)
.extracting(String::new)
.isEqualTo("Hell");
} finally {
executorService.shutdownNow();
}
}
@Test
public void blockingWithExecutor_canUnderUploadOneByteAtATime() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(),
AsyncRequestBody.fromInputStream(new TrickleInputStream(new StringInputStream("Hello")),
4L,
executorService))
.join();
List<LoggedRequest> requests = wireMock.findAll(allRequests());
assertThat(requests).singleElement()
.extracting(LoggedRequest::getBody)
.extracting(String::new)
.isEqualTo("Hell");
} finally {
executorService.shutdownNow();
}
}
@Test
public void blockingWithExecutor_propagatesReadFailures() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
CompletableFuture<StreamingInputOperationResponse> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(),
AsyncRequestBody.fromInputStream(new FailOnReadInputStream(),
5L,
executorService));
assertThatThrownBy(responseFuture::join).hasRootCauseInstanceOf(IOException.class);
} finally {
executorService.shutdownNow();
}
}
@Test
public void blockingWithExecutor_propagates400Failures() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(404).withBody("{}")));
CompletableFuture<?> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(),
AsyncRequestBody.fromInputStream(new StringInputStream("Hello"),
5L,
executorService));
assertThatThrownBy(responseFuture::join).hasCauseInstanceOf(SdkServiceException.class);
} finally {
executorService.shutdownNow();
}
}
@Test
public void blockingWithExecutor_propagates500Failures() {
ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().daemonThreads(true).build());
try {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(500).withBody("{}")));
CompletableFuture<?> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(),
AsyncRequestBody.fromInputStream(new StringInputStream("Hello"),
5L,
executorService));
assertThatThrownBy(responseFuture::join).hasCauseInstanceOf(SdkServiceException.class);
} finally {
executorService.shutdownNow();
}
}
@Test
public void blockingInputStreamWithoutExecutor_sendsRightValues() {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(5L);
CompletableFuture<?> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
body.writeInputStream(new StringInputStream("Hello"));
responseFuture.join();
List<LoggedRequest> requests = wireMock.findAll(allRequests());
assertThat(requests).singleElement()
.extracting(LoggedRequest::getBody)
.extracting(String::new)
.isEqualTo("Hello");
}
@Test
public void blockingInputStreamWithoutExecutor_canUnderUpload() {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(4L);
CompletableFuture<?> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
body.writeInputStream(new StringInputStream("Hello"));
responseFuture.join();
List<LoggedRequest> requests = wireMock.findAll(allRequests());
assertThat(requests).singleElement()
.extracting(LoggedRequest::getBody)
.extracting(String::new)
.isEqualTo("Hell");
}
@Test
public void blockingInputStreamWithoutExecutor_canUnderUploadOneByteAtATime() {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(4L);
CompletableFuture<?> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
body.writeInputStream(new TrickleInputStream(new StringInputStream("Hello")));
responseFuture.join();
List<LoggedRequest> requests = wireMock.findAll(allRequests());
assertThat(requests).singleElement()
.extracting(LoggedRequest::getBody)
.extracting(String::new)
.isEqualTo("Hell");
}
@Test
public void blockingInputStreamWithoutExecutor_propagatesReadFailures() {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(5L);
CompletableFuture<StreamingInputOperationResponse> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
assertThatThrownBy(() -> body.writeInputStream(new FailOnReadInputStream())).hasRootCauseInstanceOf(IOException.class);
assertThatThrownBy(responseFuture::get)
.hasCauseInstanceOf(SdkClientException.class)
.hasMessageContaining("AsyncRequestBody.forBlockingInputStream does not support retries");
}
@Test
public void blockingInputStreamWithoutExecutor_propagates400Failures() {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(404).withBody("{}")));
BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(5L);
CompletableFuture<?> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
body.writeInputStream(new StringInputStream("Hello"));
assertThatThrownBy(responseFuture::join).hasCauseInstanceOf(SdkServiceException.class);
}
@Test
public void blockingInputStreamWithoutExecutor_propagates500Failures() {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(500).withBody("{}")));
BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(5L);
CompletableFuture<StreamingInputOperationResponse> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
body.writeInputStream(new StringInputStream("Hello"));
assertThatThrownBy(responseFuture::get)
.hasCauseInstanceOf(SdkClientException.class)
.hasMessageContaining("AsyncRequestBody.forBlockingInputStream does not support retries");
}
@Test
public void blockingResponseTransformer_readsRightValue() {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("hello")));
CompletableFuture<ResponseInputStream<StreamingOutputOperationResponse>> responseFuture =
client.streamingOutputOperation(StreamingOutputOperationRequest.builder().build(),
AsyncResponseTransformer.toBlockingInputStream());
ResponseInputStream<StreamingOutputOperationResponse> responseStream = responseFuture.join();
assertThat(responseStream).asString(StandardCharsets.UTF_8).isEqualTo("hello");
assertThat(responseStream.response().sdkHttpResponse().statusCode()).isEqualTo(200);
}
@Test
public void blockingResponseTransformer_abortCloseDoesNotThrow() throws IOException {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("hello")));
CompletableFuture<ResponseInputStream<StreamingOutputOperationResponse>> responseFuture =
client.streamingOutputOperation(StreamingOutputOperationRequest.builder().build(),
AsyncResponseTransformer.toBlockingInputStream());
ResponseInputStream<StreamingOutputOperationResponse> responseStream = responseFuture.join();
responseStream.abort();
responseStream.close();
}
@Test
public void blockingResponseTransformer_closeDoesNotThrow() throws IOException {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("hello")));
CompletableFuture<ResponseInputStream<StreamingOutputOperationResponse>> responseFuture =
client.streamingOutputOperation(StreamingOutputOperationRequest.builder().build(),
AsyncResponseTransformer.toBlockingInputStream());
ResponseInputStream<StreamingOutputOperationResponse> responseStream = responseFuture.join();
responseStream.close();
}
@Test
public void blockingOutputStreamWithoutExecutor_sendsRightValues() throws IOException {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(5L);
CompletableFuture<?> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
try (OutputStream stream = body.outputStream()) {
stream.write("Hello".getBytes(StandardCharsets.UTF_8));
}
responseFuture.join();
List<LoggedRequest> requests = wireMock.findAll(allRequests());
assertThat(requests).singleElement()
.extracting(LoggedRequest::getBody)
.extracting(String::new)
.isEqualTo("Hello");
}
@Test
public void blockingOutputStreamWithoutExecutor_canUnderUpload() throws IOException {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(4L);
CompletableFuture<?> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
try (OutputStream stream = body.outputStream()) {
stream.write("Hello".getBytes(StandardCharsets.UTF_8));
}
responseFuture.join();
List<LoggedRequest> requests = wireMock.findAll(allRequests());
assertThat(requests).singleElement()
.extracting(LoggedRequest::getBody)
.extracting(String::new)
.isEqualTo("Hell");
}
@Test
public void blockingOutputStreamWithoutExecutor_canUnderUploadOneByteAtATime() throws IOException {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(4L);
CompletableFuture<?> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
try (OutputStream stream = body.outputStream()) {
stream.write('H');
stream.write('e');
stream.write('l');
stream.write('l');
stream.write('o');
}
responseFuture.join();
List<LoggedRequest> requests = wireMock.findAll(allRequests());
assertThat(requests).singleElement()
.extracting(LoggedRequest::getBody)
.extracting(String::new)
.isEqualTo("Hell");
}
@Test
public void blockingOutputStreamWithoutExecutor_propagatesCancellations() {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}")));
BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(5L);
CompletableFuture<StreamingInputOperationResponse> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
body.outputStream().cancel();
assertThatThrownBy(responseFuture::get).hasRootCauseInstanceOf(CancellationException.class);
}
@Test
public void blockingOutputStreamWithoutExecutor_propagates400Failures() throws IOException {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(404).withBody("{}")));
BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(5L);
CompletableFuture<?> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
try (OutputStream stream = body.outputStream()) {
stream.write("Hello".getBytes(StandardCharsets.UTF_8));
}
assertThatThrownBy(responseFuture::join).hasCauseInstanceOf(SdkServiceException.class);
}
@Test
public void blockingOutputStreamWithoutExecutor_propagates500Failures() throws IOException {
wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(500).withBody("{}")));
BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(5L);
CompletableFuture<StreamingInputOperationResponse> responseFuture =
client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body);
try (OutputStream stream = body.outputStream()) {
stream.write("Hello".getBytes(StandardCharsets.UTF_8));
}
assertThatThrownBy(responseFuture::get)
.hasCauseInstanceOf(SdkClientException.class)
.hasMessageContaining("AsyncRequestBody.forBlockingOutputStream does not support retries");
}
private static class FailOnReadInputStream extends InputStream {
@Override
public int read() throws IOException {
throw new IOException("Intentionally failed to read.");
}
}
private static class TrickleInputStream extends InputStream {
private final InputStream delegate;
private TrickleInputStream(InputStream delegate) {
this.delegate = delegate;
}
@Override
public int read() throws IOException {
return delegate.read();
}
@Override
public int read(byte[] b) throws IOException {
if (b.length == 0) {
return 0;
}
return delegate.read(b, 0, 1);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (len == 0) {
return 0;
}
return delegate.read(b, off, 1);
}
}
}
| 2,576 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/EndpointDiscoveryRequestOverrideConfigTest.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.services;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestAsyncClient;
import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestClient;
import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
import software.amazon.awssdk.utils.StringInputStream;
/**
* Verifies that request-level overrides work with endpoint discovery.
*/
public class EndpointDiscoveryRequestOverrideConfigTest {
private EndpointDiscoveryTestClient client;
private EndpointDiscoveryTestAsyncClient asyncClient;
private MockSyncHttpClient httpClient;
private MockAsyncHttpClient asyncHttpClient;
private static final AwsBasicCredentials CLIENT_CREDENTIALS = AwsBasicCredentials.create("ca", "cs");
private static final AwsBasicCredentials REQUEST_CREDENTIALS = AwsBasicCredentials.create("ra", "rs");
@BeforeEach
public void setupClient() {
httpClient = new MockSyncHttpClient();
asyncHttpClient = new MockAsyncHttpClient();
client = EndpointDiscoveryTestClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(CLIENT_CREDENTIALS))
.region(Region.US_EAST_1)
.endpointDiscoveryEnabled(true)
.httpClient(httpClient)
.build();
asyncClient = EndpointDiscoveryTestAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(CLIENT_CREDENTIALS))
.region(Region.US_EAST_1)
.endpointDiscoveryEnabled(true)
.httpClient(asyncHttpClient)
.build();
}
@AfterEach
public void cleanup() {
httpClient.reset();
asyncHttpClient.reset();
}
@Test
public void syncClientCredentialsUsedByDefault() {
httpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse());
client.testDiscoveryRequired(r -> {});
assertRequestsUsedCredentials(httpClient.getRequests(), CLIENT_CREDENTIALS);
}
@Test
public void asyncClientCredentialsUsedByDefault() throws Exception {
asyncHttpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse());
asyncClient.testDiscoveryRequired(r -> {}).get(10, TimeUnit.SECONDS);
assertRequestsUsedCredentials(asyncHttpClient.getRequests(), CLIENT_CREDENTIALS);
}
@Test
public void syncClientRequestCredentialsUsedIfOverridden() {
httpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse());
client.testDiscoveryRequired(r -> r.overrideConfiguration(c -> c.credentialsProvider(() -> REQUEST_CREDENTIALS)));
assertRequestsUsedCredentials(httpClient.getRequests(), REQUEST_CREDENTIALS);
}
@Test
public void asyncClientRequestCredentialsUsedIfOverridden() throws Exception {
asyncHttpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse());
asyncClient.testDiscoveryRequired(r -> r.overrideConfiguration(c -> c.credentialsProvider(() -> REQUEST_CREDENTIALS)))
.get(10, TimeUnit.SECONDS);
assertRequestsUsedCredentials(asyncHttpClient.getRequests(), REQUEST_CREDENTIALS);
}
@Test
public void syncClientRequestHeadersUsed() {
httpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse());
client.testDiscoveryRequired(r -> r.overrideConfiguration(c -> c.putHeader("Foo", "Bar")));
assertRequestsHadHeader(httpClient.getRequests(), "Foo", "Bar");
}
@Test
public void asyncClientRequestHeadersUsed() throws Exception {
asyncHttpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse());
asyncClient.testDiscoveryRequired(r -> r.overrideConfiguration(c -> c.putHeader("Foo", "Bar")))
.get(10, TimeUnit.SECONDS);
assertRequestsHadHeader(asyncHttpClient.getRequests(), "Foo", "Bar");
}
private void assertRequestsHadHeader(List<SdkHttpRequest> requests, String headerName, String headerValue) {
assertThat(requests).hasSize(2);
assertThat(requests).allSatisfy(request -> {
assertThat(request.firstMatchingHeader(headerName)).hasValue(headerValue);
});
}
private void assertRequestsUsedCredentials(List<SdkHttpRequest> requests, AwsBasicCredentials clientCredentials) {
assertThat(requests).hasSize(2);
assertRequestUsedCredentials(requests.get(0), clientCredentials);
assertRequestUsedCredentials(requests.get(1), clientCredentials);
}
private void assertRequestUsedCredentials(SdkHttpRequest request, AwsCredentials expectedCredentials) {
assertThat(request.firstMatchingHeader("Authorization")).isPresent().hasValueSatisfying(authorizationHeader -> {
assertThat(authorizationHeader).contains(" Credential=" + expectedCredentials.accessKeyId() + "/");
});
}
private HttpExecuteResponse successfulEndpointDiscoveryResponse() {
String responseData =
"{" +
" \"Endpoints\": [{" +
" \"Address\": \"something\"," +
" \"CachePeriodInMinutes\": 30" +
" }]" +
"}";
AbortableInputStream responseStream = AbortableInputStream.create(new StringInputStream(responseData), () -> {});
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(200)
.appendHeader("Content-Length",
Integer.toString(responseData.length()))
.build())
.responseBody(responseStream)
.build();
}
private HttpExecuteResponse successfulResponse() {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(200)
.build())
.build();
}
}
| 2,577 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/DualstackEndpointTest.java | package software.amazon.awssdk.services;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
import software.amazon.awssdk.utils.StringInputStream;
import software.amazon.awssdk.utils.Validate;
@RunWith(Parameterized.class)
public class DualstackEndpointTest {
@Parameterized.Parameter
public TestCase testCase;
@Test
public void resolvesCorrectEndpoint() {
String systemPropertyBeforeTest = System.getProperty(SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.property());
EnvironmentVariableHelper helper = new EnvironmentVariableHelper();
try {
ProtocolRestJsonClientBuilder builder =
ProtocolRestJsonClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(AnonymousCredentialsProvider.create());
if (testCase.clientSetting != null) {
builder.dualstackEnabled(testCase.clientSetting);
}
if (testCase.systemPropSetting != null) {
System.setProperty(SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.property(), testCase.systemPropSetting);
}
if (testCase.envVarSetting != null) {
helper.set(SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.environmentVariable(), testCase.envVarSetting);
}
ProfileFile.Builder profileFile = ProfileFile.builder().type(ProfileFile.Type.CONFIGURATION);
if (testCase.profileSetting != null) {
profileFile.content(new StringInputStream("[default]\n" +
ProfileProperty.USE_DUALSTACK_ENDPOINT + " = " + testCase.profileSetting));
} else {
profileFile.content(new StringInputStream(""));
}
EndpointCapturingInterceptor interceptor = new EndpointCapturingInterceptor();
builder.overrideConfiguration(c -> c.defaultProfileFile(profileFile.build())
.defaultProfileName("default")
.addExecutionInterceptor(interceptor));
if (testCase instanceof SuccessCase) {
ProtocolRestJsonClient client = builder.build();
try {
client.allTypes();
} catch (EndpointCapturingInterceptor.CaptureCompletedException e) {
// Expected
}
boolean expectedDualstackEnabled = ((SuccessCase) testCase).expectedValue;
String expectedEndpoint = expectedDualstackEnabled
? "https://customresponsemetadata.us-west-2.api.aws/2016-03-11/allTypes"
: "https://customresponsemetadata.us-west-2.amazonaws.com/2016-03-11/allTypes";
assertThat(interceptor.endpoints()).singleElement().isEqualTo(expectedEndpoint);
} else {
FailureCase failure = Validate.isInstanceOf(FailureCase.class, testCase, "Unexpected test case type.");
assertThatThrownBy(builder::build).hasMessageContaining(failure.exceptionMessage);
}
} finally {
if (systemPropertyBeforeTest != null) {
System.setProperty(SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.property(), systemPropertyBeforeTest);
} else {
System.clearProperty(SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.property());
}
helper.reset();
}
}
@Parameterized.Parameters(name = "{0}")
public static Iterable<TestCase> testCases() {
return Arrays.asList(new SuccessCase(true, "false", "false", "false", true, "Client highest priority (true)"),
new SuccessCase(false, "true", "true", "true", false, "Client highest priority (false)"),
new SuccessCase(null, "true", "false", "false", true, "System property second priority (true)"),
new SuccessCase(null, "false", "true", "true", false, "System property second priority (false)"),
new SuccessCase(null, null, "true", "false", true, "Env var third priority (true)"),
new SuccessCase(null, null, "false", "true", false, "Env var third priority (false)"),
new SuccessCase(null, null, null, "true", true, "Profile last priority (true)"),
new SuccessCase(null, null, null, "false", false, "Profile last priority (false)"),
new SuccessCase(null, null, null, null, false, "Default is false."),
new SuccessCase(null, "tRuE", null, null, true, "System property is not case sensitive."),
new SuccessCase(null, null, "tRuE", null, true, "Env var is not case sensitive."),
new SuccessCase(null, null, null, "tRuE", true, "Profile property is not case sensitive."),
new FailureCase(null, "FOO", null, null, "FOO", "Invalid system property values fail."),
new FailureCase(null, null, "FOO", null, "FOO", "Invalid env var values fail."),
new FailureCase(null, null, null, "FOO", "FOO", "Invalid profile values fail."));
}
public static class TestCase {
private final Boolean clientSetting;
private final String envVarSetting;
private final String systemPropSetting;
private final String profileSetting;
private final String caseName;
public TestCase(Boolean clientSetting, String systemPropSetting, String envVarSetting, String profileSetting,
String caseName) {
this.clientSetting = clientSetting;
this.envVarSetting = envVarSetting;
this.systemPropSetting = systemPropSetting;
this.profileSetting = profileSetting;
this.caseName = caseName;
}
@Override
public String toString() {
return caseName;
}
}
public static class SuccessCase extends TestCase {
private final boolean expectedValue;
public SuccessCase(Boolean clientSetting,
String systemPropSetting,
String envVarSetting,
String profileSetting,
boolean expectedValue,
String caseName) {
super(clientSetting, systemPropSetting, envVarSetting, profileSetting, caseName);
this.expectedValue = expectedValue;
}
}
private static class FailureCase extends TestCase {
private final String exceptionMessage;
public FailureCase(Boolean clientSetting,
String systemPropSetting,
String envVarSetting,
String profileSetting,
String exceptionMessage,
String caseName) {
super(clientSetting, systemPropSetting, envVarSetting, profileSetting, caseName);
this.exceptionMessage = exceptionMessage;
}
}
}
| 2,578 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/ModelSerializationTest.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.services;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.IOException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest;
import software.amazon.awssdk.services.protocolrestjson.model.BaseType;
import software.amazon.awssdk.services.protocolrestjson.model.RecursiveStructType;
import software.amazon.awssdk.services.protocolrestjson.model.SimpleStruct;
import software.amazon.awssdk.services.protocolrestjson.model.StructWithNestedBlobType;
import software.amazon.awssdk.services.protocolrestjson.model.StructWithTimestamp;
import software.amazon.awssdk.services.protocolrestjson.model.SubTypeOne;
/**
* Verify that modeled objects can be marshalled using Jackson.
*/
public class ModelSerializationTest {
@Test
public void jacksonSerializationWorksForEmptyRequestObjects() throws IOException {
validateJacksonSerialization(AllTypesRequest.builder().build());
}
@Test
public void jacksonSerialization_mapWithNullValue_shouldWork() throws IOException {
Map<String, SimpleStruct> mapOfStringToStruct = new HashMap<>();
mapOfStringToStruct.put("test1", null);
mapOfStringToStruct.put("test2", null);
validateJacksonSerialization(AllTypesRequest.builder().mapOfStringToStruct(mapOfStringToStruct).build());
}
@Test
public void jacksonSerializationWorksForPopulatedRequestModels() throws IOException {
SdkBytes blob = SdkBytes.fromUtf8String("foo");
SimpleStruct simpleStruct = SimpleStruct.builder().stringMember("foo").build();
StructWithTimestamp structWithTimestamp = StructWithTimestamp.builder().nestedTimestamp(Instant.EPOCH).build();
StructWithNestedBlobType structWithNestedBlob = StructWithNestedBlobType.builder().nestedBlob(blob).build();
RecursiveStructType recursiveStruct = RecursiveStructType.builder()
.recursiveStruct(RecursiveStructType.builder().build())
.build();
BaseType baseType = BaseType.builder().baseMember("foo").build();
SubTypeOne subtypeOne = SubTypeOne.builder().subTypeOneMember("foo").build();
validateJacksonSerialization(AllTypesRequest.builder()
.stringMember("foo")
.integerMember(5)
.booleanMember(true)
.floatMember(5F)
.doubleMember(5D)
.longMember(5L)
.simpleList("foo", "bar")
.listOfMaps(singletonList(singletonMap("foo", "bar")))
.listOfMapsOfStringToStruct(singletonList(singletonMap("bar", simpleStruct)))
.listOfListOfMapsOfStringToStruct(
singletonList(singletonList(singletonMap("bar", simpleStruct))))
.listOfStructs(simpleStruct)
.mapOfStringToIntegerList(singletonMap("foo", singletonList(5)))
.mapOfStringToStruct(singletonMap("foo", simpleStruct))
.timestampMember(Instant.EPOCH)
.structWithNestedTimestampMember(structWithTimestamp)
.blobArg(blob)
.structWithNestedBlob(structWithNestedBlob)
.blobMap(singletonMap("foo", blob))
.listOfBlobs(blob, blob)
.recursiveStruct(recursiveStruct)
.polymorphicTypeWithSubTypes(baseType)
.polymorphicTypeWithoutSubTypes(subtypeOne)
.enumMember("foo")
.listOfEnumsWithStrings("foo", "bar")
.mapOfEnumToEnumWithStrings(singletonMap("foo", "bar"))
.build());
}
private void validateJacksonSerialization(AllTypesRequest original) throws IOException {
SimpleModule instantModule = new SimpleModule();
instantModule.addSerializer(Instant.class, new InstantSerializer());
instantModule.addDeserializer(Instant.class, new InstantDeserializer());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(instantModule);
String serialized = mapper.writeValueAsString(original.toBuilder());
AllTypesRequest deserialized = mapper.readValue(serialized, AllTypesRequest.serializableBuilderClass()).build();
assertThat(deserialized).isEqualTo(original);
}
private class InstantSerializer extends JsonSerializer<Instant> {
@Override
public void serialize(Instant t, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeString(t.toString());
}
}
private class InstantDeserializer extends JsonDeserializer<Instant> {
@Override
public Instant deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
return Instant.parse(jsonParser.getText());
}
}
}
| 2,579 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/ExecutionAttributesTest.java | package software.amazon.awssdk.services;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest;
public class ExecutionAttributesTest {
private static final ConcurrentMap<String, ExecutionAttribute<Object>> ATTR_POOL = new ConcurrentHashMap<>();
private static ExecutionAttribute<Object> attr(String name) {
name = ExecutionAttributesTest.class.getName() + ":" + name;
return ATTR_POOL.computeIfAbsent(name, ExecutionAttribute::new);
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void syncClient_disableHostPrefixInjection_isPresent() {
ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class);
ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class);
doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture());
ProtocolRestJsonClient sync = ProtocolRestJsonClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar")))
.region(Region.US_WEST_2)
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)
.putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true))
.build();
thrown.expect(RuntimeException.class);
try {
sync.allTypes();
} finally {
ExecutionAttributes attributes = attributesCaptor.getValue();
assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.DISABLE_HOST_PREFIX_INJECTION)).isTrue();
sync.close();
}
}
@Test
public void asyncClient_disableHostPrefixInjection_isPresent() {
ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class);
ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class);
doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture());
ProtocolRestJsonAsyncClient async = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar")))
.region(Region.US_WEST_2)
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)
.putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true))
.build();
thrown.expect(CompletionException.class);
try {
async.allTypes().join();
} finally {
ExecutionAttributes attributes = attributesCaptor.getValue();
assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.DISABLE_HOST_PREFIX_INJECTION)).isTrue();
async.close();
}
}
@Test
public void asyncClient_clientOverrideExecutionAttribute() {
ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class);
ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class);
doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture());
ExecutionAttribute testAttribute = attr("TestAttribute");
String testValue = "TestValue";
ProtocolRestJsonAsyncClient async = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar")))
.region(Region.US_WEST_2)
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)
.putExecutionAttribute(testAttribute, testValue))
.build();
thrown.expect(CompletionException.class);
try {
async.allTypes().join();
} finally {
ExecutionAttributes attributes = attributesCaptor.getValue();
assertThat(attributes.getAttribute(testAttribute)).isEqualTo(testValue);
async.close();
}
}
@Test
public void asyncClient_requestOverrideExecutionAttribute() {
ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class);
ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class);
doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture());
ExecutionAttribute testAttribute = attr("TestAttribute");
String testValue = "TestValue";
ProtocolRestJsonAsyncClient async = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar")))
.region(Region.US_WEST_2)
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor))
.build();
AllTypesRequest request = AllTypesRequest.builder().overrideConfiguration(
c -> c.putExecutionAttribute(testAttribute, testValue))
.build();
thrown.expect(CompletionException.class);
try {
async.allTypes(request).join();
} finally {
ExecutionAttributes attributes = attributesCaptor.getValue();
assertThat(attributes.getAttribute(testAttribute)).isEqualTo(testValue);
async.close();
}
}
@Test
public void asyncClient_requestOverrideExecutionAttributesHavePrecedence() {
ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class);
ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class);
doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture());
ExecutionAttribute testAttribute = attr("TestAttribute");
String testValue = "TestValue";
ProtocolRestJsonAsyncClient async = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar")))
.region(Region.US_WEST_2)
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor).putExecutionAttribute(testAttribute, testValue))
.build();
String overwrittenValue = "TestValue2";
AllTypesRequest request = AllTypesRequest.builder().overrideConfiguration(
c -> c.putExecutionAttribute(testAttribute, overwrittenValue))
.build();
thrown.expect(CompletionException.class);
try {
async.allTypes(request).join();
} finally {
ExecutionAttributes attributes = attributesCaptor.getValue();
assertThat(attributes.getAttribute(testAttribute)).isEqualTo(overwrittenValue);
async.close();
}
}
@Test
public void syncClient_requestOverrideExecutionAttribute() {
ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class);
ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class);
doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture());
ExecutionAttribute testAttribute = attr("TestAttribute");
String testValue = "TestValue";
ProtocolRestJsonClient sync = ProtocolRestJsonClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar")))
.region(Region.US_WEST_2)
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor))
.build();
AllTypesRequest request = AllTypesRequest.builder().overrideConfiguration(
c -> c.putExecutionAttribute(testAttribute, testValue))
.build();
thrown.expect(RuntimeException.class);
try {
sync.allTypes(request);
} finally {
ExecutionAttributes attributes = attributesCaptor.getValue();
assertThat(attributes.getAttribute(testAttribute)).isEqualTo(testValue);
sync.close();
}
}
@Test
public void syncClient_requestOverrideExecutionAttributesHavePrecedence() {
ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class);
ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class);
doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture());
ExecutionAttribute testAttribute = attr("TestAttribute");
String testValue = "TestValue";
ProtocolRestJsonClient sync = ProtocolRestJsonClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar")))
.region(Region.US_WEST_2)
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor).putExecutionAttribute(testAttribute, testValue))
.build();
String overwrittenValue = "TestValue2";
AllTypesRequest request = AllTypesRequest.builder().overrideConfiguration(
c -> c.putExecutionAttribute(testAttribute, overwrittenValue))
.build();
thrown.expect(RuntimeException.class);
try {
sync.allTypes(request);
} finally {
ExecutionAttributes attributes = attributesCaptor.getValue();
assertThat(attributes.getAttribute(testAttribute)).isEqualTo(overwrittenValue);
sync.close();
}
}
@Test
public void testExecutionAttributesMerge() {
ExecutionAttributes lowerPrecedence = new ExecutionAttributes();
for (int i = 0; i < 3; i++) {
lowerPrecedence.putAttribute(getAttribute(i), 1);
}
ExecutionAttributes higherPrecendence = new ExecutionAttributes();
for (int i = 2; i < 4; i++) {
higherPrecendence.putAttribute(getAttribute(i), 2);
}
ExecutionAttributes expectedAttributes = new ExecutionAttributes();
for (int i = 0; i < 4; i++) {
expectedAttributes.putAttribute(getAttribute(i), i >= 2 ? 2 : 1);
}
ExecutionAttributes merged = higherPrecendence.merge(lowerPrecedence);
assertThat(merged.getAttributes()).isEqualTo(expectedAttributes.getAttributes());
}
@Test
public void testCopyBuilder() {
ExecutionAttributes testAttributes = new ExecutionAttributes();
for (int i = 0; i < 3; i++) {
testAttributes.putAttribute(getAttribute(i), 1);
}
ExecutionAttributes copy = testAttributes.copy();
assertThat(copy.getAttributes()).isEqualTo(testAttributes.getAttributes());
}
@Test
public void testAttributeEquals() {
ExecutionAttribute attribute1 = getAttribute(0);
ExecutionAttribute attribute2 = getAttribute(0);
assertThat(attribute1).isEqualTo(attribute1);
assertThat(attribute1).isEqualTo(attribute2);
assertThat(attribute1).isNotEqualTo(null);
}
private ExecutionAttribute getAttribute(int i) {
return attr("TestAttribute" + i);
}
} | 2,580 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/HttpChecksumValidationTest.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.services;
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.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
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.put;
import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor;
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 org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING;
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import java.util.concurrent.CompletionException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.ChecksumValidation;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.ChecksumAlgorithm;
import software.amazon.awssdk.services.protocolrestjson.model.ChecksumMode;
import software.amazon.awssdk.services.protocolrestjson.model.GetOperationWithChecksumResponse;
import software.amazon.awssdk.services.protocolrestjson.model.OperationWithChecksumNonStreamingResponse;
public class HttpChecksumValidationTest {
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private ProtocolRestJsonClient client;
private ProtocolRestJsonAsyncClient asyncClient;
@Before
public void setupClient() {
client = ProtocolRestJsonClient.builder()
.credentialsProvider(AnonymousCredentialsProvider.create())
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.overrideConfiguration(
// TODO(sra-identity-and-auth): we should remove these
// overrides once we set up codegen to set chunk-encoding to true
// for requests that are streaming and checksum-enabled
o -> o.addExecutionInterceptor(new CaptureChecksumValidationInterceptor())
.putExecutionAttribute(
ENABLE_CHUNKED_ENCODING, true
))
.build();
asyncClient = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.overrideConfiguration(o -> o.addExecutionInterceptor(new CaptureChecksumValidationInterceptor()))
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.build();
}
@After
public void clear() {
CaptureChecksumValidationInterceptor.reset();
}
@Test
public void syncClientValidateStreamingResponse() {
String expectedChecksum = "i9aeUg==";
stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32");
client.putOperationWithChecksum(r -> r
.checksumAlgorithm(ChecksumAlgorithm.CRC32),
RequestBody.fromString("Hello world"), ResponseTransformer.toBytes());
verify(putRequestedFor(urlEqualTo("/")).withHeader("x-amz-trailer", equalTo("x-amz-checksum-crc32")));
verify(putRequestedFor(urlEqualTo("/")).withRequestBody(containing("x-amz-checksum-crc32:" + expectedChecksum)));
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
client.getOperationWithChecksum(r -> r.checksumMode(ChecksumMode.ENABLED), ResponseTransformer.toBytes());
assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32);
}
@Test
public void syncClientValidateStreamingResponseZeroByte() {
String expectedChecksum = "AAAAAA==";
stubWithCRC32AndSha256Checksum("", expectedChecksum, "crc32");
client.putOperationWithChecksum(r -> r
.checksumAlgorithm(ChecksumAlgorithm.CRC32),
RequestBody.fromString(""), ResponseTransformer.toBytes());
verify(putRequestedFor(urlEqualTo("/")).withHeader("x-amz-trailer", equalTo("x-amz-checksum-crc32")));
verify(putRequestedFor(urlEqualTo("/")).withRequestBody(containing("x-amz-checksum-crc32:" + expectedChecksum)));
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
client.getOperationWithChecksum(r -> r.checksumMode(ChecksumMode.ENABLED), ResponseTransformer.toBytes());
assertThat(responseBytes.asUtf8String()).isEmpty();
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32);
}
@Test
public void syncClientValidateNonStreamingResponse() {
String expectedChecksum = "lzlLIA==";
stubWithCRC32AndSha256Checksum("{\"stringMember\":\"Hello world\"}", expectedChecksum, "crc32");
client.operationWithChecksumNonStreaming(
r -> r.stringMember("Hello world").checksumAlgorithm(ChecksumAlgorithm.CRC32)
// TODO(sra-identity-and-auth): we should remove these
// overrides once we set up codegen to set chunk-encoding to true
// for requests that are streaming and checksum-enabled
.overrideConfiguration(c -> c.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, false))
);
verify(postRequestedFor(urlEqualTo("/")).withHeader("x-amz-checksum-crc32", equalTo(expectedChecksum)));
OperationWithChecksumNonStreamingResponse operationWithChecksumNonStreamingResponse =
client.operationWithChecksumNonStreaming(o -> o.checksumMode(ChecksumMode.ENABLED));
assertThat(operationWithChecksumNonStreamingResponse.stringMember()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32);
}
@Test
public void syncClientValidateNonStreamingResponseZeroByte() {
String expectedChecksum = "o6a/Qw==";
stubWithCRC32AndSha256Checksum("{}", expectedChecksum, "crc32");
client.operationWithChecksumNonStreaming(
r -> r.checksumAlgorithm(ChecksumAlgorithm.CRC32)
// TODO(sra-identity-and-auth): we should remove these
// overrides once we set up codegen to set chunk-encoding to true
// for requests that are streaming and checksum-enabled
.overrideConfiguration(c -> c.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, false))
);
verify(postRequestedFor(urlEqualTo("/")).withHeader("x-amz-checksum-crc32", equalTo(expectedChecksum)));
OperationWithChecksumNonStreamingResponse operationWithChecksumNonStreamingResponse =
client.operationWithChecksumNonStreaming(o -> o.checksumMode(ChecksumMode.ENABLED));
assertThat(operationWithChecksumNonStreamingResponse.stringMember()).isNull();
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32);
}
@Test
public void syncClientValidateStreamingResponseForceSkip() {
String expectedChecksum = "i9aeUg==";
stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32");
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
client.getOperationWithChecksum(
r -> r.checksumMode(ChecksumMode.ENABLED).overrideConfiguration(
o -> o.putExecutionAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION,
ChecksumValidation.FORCE_SKIP)),
ResponseTransformer.toBytes());
assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.FORCE_SKIP);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull();
}
@Test
public void syncClientValidateStreamingResponseNoAlgorithmInResponse() {
stubWithNoChecksum();
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
client.getOperationWithChecksum(
r -> r.checksumMode(ChecksumMode.ENABLED),
ResponseTransformer.toBytes());
assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.CHECKSUM_ALGORITHM_NOT_FOUND);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull();
}
@Test
public void syncClientValidateStreamingResponseNoAlgorithmFoundInClient() {
String expectedChecksum = "someNewAlgorithmCalculatedValue";
stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc64");
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
client.getOperationWithChecksum(
r -> r.checksumMode(ChecksumMode.ENABLED),
ResponseTransformer.toBytes());
assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.CHECKSUM_ALGORITHM_NOT_FOUND);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull();
}
@Test
public void syncClientValidateStreamingResponseWithValidationFailed() {
String expectedChecksum = "i9aeUg=";
stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32");
assertThatExceptionOfType(SdkClientException.class)
.isThrownBy(() -> client.getOperationWithChecksum(
r -> r.checksumMode(ChecksumMode.ENABLED),
ResponseTransformer.toBytes()))
.withMessage("Unable to unmarshall response (Data read has a different checksum than expected. Was i9aeUg==, "
+ "but expected i9aeUg=). Response Code: 200, Response Text: OK");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32);
}
@Test
public void syncClientSkipsValidationWhenFeatureDisabled() {
String expectedChecksum = "i9aeUg==";
stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32");
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
client.getOperationWithChecksum(r -> r.stringMember("foo"), ResponseTransformer.toBytes());
assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isNull();
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull();
}
//Async
@Test
public void asyncClientValidateStreamingResponse() {
String expectedChecksum = "i9aeUg==";
stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32");
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
asyncClient.getOperationWithChecksum(r -> r.checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()).join();
assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32);
}
@Test
public void asyncClientValidateStreamingResponseZeroByte() {
String expectedChecksum = "AAAAAA==";
stubWithCRC32AndSha256Checksum("", expectedChecksum, "crc32");
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
asyncClient.getOperationWithChecksum(r -> r.checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()).join();
assertThat(responseBytes.asUtf8String()).isEmpty();
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32);
}
@Test
public void asyncClientValidateNonStreamingResponse() {
String expectedChecksum = "lzlLIA==";
stubWithCRC32AndSha256Checksum("{\"stringMember\":\"Hello world\"}", expectedChecksum, "crc32");
OperationWithChecksumNonStreamingResponse response =
asyncClient.operationWithChecksumNonStreaming(
o -> o.checksumMode(ChecksumMode.ENABLED)
// TODO(sra-identity-and-auth): we should remove these
// overrides once we set up codegen to set chunk-encoding to true
// for requests that are streaming and checksum-enabled
.overrideConfiguration(c -> c.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, false))).join();
assertThat(response.stringMember()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32);
}
@Test
public void asyncClientValidateNonStreamingResponseZeroByte() {
String expectedChecksum = "o6a/Qw==";
stubWithCRC32AndSha256Checksum("{}", expectedChecksum, "crc32");
OperationWithChecksumNonStreamingResponse operationWithChecksumNonStreamingResponse =
asyncClient.operationWithChecksumNonStreaming(
o -> o.checksumMode(ChecksumMode.ENABLED)
// TODO(sra-identity-and-auth): we should remove these
// overrides once we set up codegen to set chunk-encoding to true
// for requests that are streaming and checksum-enabled
.overrideConfiguration(c -> c.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, false))).join();
assertThat(operationWithChecksumNonStreamingResponse.stringMember()).isNull();
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32);
}
@Test
public void asyncClientValidateStreamingResponseForceSkip() {
String expectedChecksum = "i9aeUg==";
stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32");
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
asyncClient.getOperationWithChecksum(
r -> r.checksumMode(ChecksumMode.ENABLED).overrideConfiguration(
o -> o.putExecutionAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION,
ChecksumValidation.FORCE_SKIP)),
AsyncResponseTransformer.toBytes()).join();
assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.FORCE_SKIP);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull();
}
@Test
public void asyncClientValidateStreamingResponseNoAlgorithmInResponse() {
stubWithNoChecksum();
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
asyncClient.getOperationWithChecksum(
r -> r.checksumMode(ChecksumMode.ENABLED),
AsyncResponseTransformer.toBytes()).join();
assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.CHECKSUM_ALGORITHM_NOT_FOUND);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull();
}
@Test
public void asyncClientValidateStreamingResponseNoAlgorithmFoundInClient() {
String expectedChecksum = "someNewAlgorithmCalculatedValue";
stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc64");
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
asyncClient.getOperationWithChecksum(
r -> r.checksumMode(ChecksumMode.ENABLED),
AsyncResponseTransformer.toBytes()).join();
assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.CHECKSUM_ALGORITHM_NOT_FOUND);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull();
}
@Test
public void asyncClientValidateStreamingResponseWithValidationFailed() {
String expectedChecksum = "i9aeUg=";
stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32");
assertThatExceptionOfType(CompletionException.class)
.isThrownBy(() -> asyncClient.getOperationWithChecksum(
r -> r.checksumMode(ChecksumMode.ENABLED),
AsyncResponseTransformer.toBytes()).join())
.withMessage("software.amazon.awssdk.core.exception.SdkClientException: Data read has a different checksum"
+ " than expected. Was i9aeUg==, but expected i9aeUg=");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32);
}
@Test
public void asyncClientSkipsValidationWhenFeatureDisabled() {
String expectedChecksum = "i9aeUg==";
stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32");
ResponseBytes<GetOperationWithChecksumResponse> responseBytes =
asyncClient.getOperationWithChecksum(r -> r.stringMember("foo"), AsyncResponseTransformer.toBytes()).join();
assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world");
assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isNull();
assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull();
}
private void stubWithCRC32AndSha256Checksum(String body, String checksumValue, String algorithmName) {
ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(200)
.withHeader("x-amz-checksum-" + algorithmName, checksumValue)
.withHeader("content-length",
String.valueOf(body.length()))
.withBody(body);
stubFor(get(anyUrl()).willReturn(responseBuilder));
stubFor(put(anyUrl()).willReturn(responseBuilder));
stubFor(post(anyUrl()).willReturn(responseBuilder));
}
private void stubWithNoChecksum() {
ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(200)
.withHeader("content-length",
String.valueOf("Hello world".length()))
.withBody("Hello world");
stubFor(get(anyUrl()).willReturn(responseBuilder));
stubFor(put(anyUrl()).willReturn(responseBuilder));
stubFor(post(anyUrl()).willReturn(responseBuilder));
}
private static class CaptureChecksumValidationInterceptor implements ExecutionInterceptor {
private static Algorithm expectedAlgorithm;
private static ChecksumValidation checksumValidation;
public static void reset() {
expectedAlgorithm = null;
checksumValidation = null;
}
@Override
public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) {
expectedAlgorithm =
executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_CHECKSUM_VALIDATION_ALGORITHM).orElse(null);
checksumValidation =
executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION).orElse(null);
}
@Override
public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) {
expectedAlgorithm =
executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_CHECKSUM_VALIDATION_ALGORITHM).orElse(null);
checksumValidation =
executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION).orElse(null);
}
}
}
| 2,581 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/EndpointDiscoveryTest.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.services;
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.mock;
import static org.mockito.Mockito.when;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import io.reactivex.Flowable;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.assertj.core.api.AbstractThrowableAssert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.stubbing.Answer;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryFailedException;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.internal.SdkInternalTestAdvancedClientOption;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestAsyncClient;
import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestClient;
import software.amazon.awssdk.services.endpointdiscoverytest.model.EndpointDiscoveryTestException;
public class EndpointDiscoveryTest {
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private SdkHttpClient mockSyncClient;
private SdkAsyncHttpClient mockAsyncClient;
private EndpointDiscoveryTestClient client;
private EndpointDiscoveryTestAsyncClient asyncClient;
@Before
public void setupClient() {
mockSyncClient = mock(SdkHttpClient.class);
client = EndpointDiscoveryTestClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(
"akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.endpointDiscoveryEnabled(true)
.overrideConfiguration(c -> c.putAdvancedOption(
SdkInternalTestAdvancedClientOption.ENDPOINT_OVERRIDDEN_OVERRIDE, false))
.httpClient(mockSyncClient)
.build();
mockAsyncClient = mock(SdkAsyncHttpClient.class);
asyncClient = EndpointDiscoveryTestAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.endpointDiscoveryEnabled(true)
.overrideConfiguration(c -> c.putAdvancedOption(
SdkInternalTestAdvancedClientOption.ENDPOINT_OVERRIDDEN_OVERRIDE,
false))
.httpClient(mockAsyncClient)
.build();
}
@Test
public void syncRequiredOperation_EmptyEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() {
stubResponse(mockSyncClient, 200, "{}");
assertThatThrownBy(() -> client.testDiscoveryRequired(r -> {
}))
.isInstanceOf(EndpointDiscoveryFailedException.class);
}
@Test
public void asyncRequiredOperation_EmptyEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() {
stubResponse(mockAsyncClient, 200, "{}");
assertAsyncRequiredOperationCallThrowable()
.isInstanceOf(EndpointDiscoveryFailedException.class)
.hasCauseInstanceOf(IllegalArgumentException.class);
}
@Test
public void syncRequiredOperation_NonRetryableEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() {
stubResponse(mockSyncClient, 404, "localhost", 60);
assertThatThrownBy(() -> client.testDiscoveryRequired(r -> {
}))
.isInstanceOf(EndpointDiscoveryFailedException.class)
.hasCauseInstanceOf(EndpointDiscoveryTestException.class);
}
@Test
public void asyncRequiredOperation_NonRetryableEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() {
stubResponse(mockAsyncClient, 404, "localhost", 60);
assertAsyncRequiredOperationCallThrowable()
.isInstanceOf(EndpointDiscoveryFailedException.class);
}
@Test
public void syncRequiredOperation_RetryableEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() {
stubResponse(mockSyncClient, 500, "localhost", 60);
assertThatThrownBy(() -> client.testDiscoveryRequired(r -> {
}))
.isInstanceOf(EndpointDiscoveryFailedException.class)
.hasCauseInstanceOf(EndpointDiscoveryTestException.class);
}
@Test
public void asyncRequiredOperation_RetryableEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() {
stubResponse(mockAsyncClient, 500, "localhost", 60);
assertAsyncRequiredOperationCallThrowable()
.isInstanceOf(EndpointDiscoveryFailedException.class)
.hasCauseInstanceOf(EndpointDiscoveryTestException.class);
}
@Test
public void syncRequiredOperation_InvalidEndpointEndpointDiscoveryResponse_CausesSdkException() {
stubResponse(mockSyncClient, 500, "invalid", 15);
assertThatThrownBy(() -> client.testDiscoveryRequired(r -> {
}))
.isInstanceOf(SdkClientException.class);
}
@Test
public void asyncRequiredOperation_InvalidEndpointEndpointDiscoveryResponse_CausesSdkException() {
stubResponse(mockAsyncClient, 500, "invalid", 15);
assertAsyncRequiredOperationCallThrowable()
.isInstanceOf(SdkClientException.class);
}
private AbstractThrowableAssert<?, ? extends Throwable> assertAsyncRequiredOperationCallThrowable() {
try {
asyncClient.testDiscoveryRequired(r -> {
}).get();
throw new AssertionError();
} catch (InterruptedException e) {
return assertThat(e);
} catch (ExecutionException e) {
return assertThat(e.getCause());
}
}
private static class TestExecutableHttpRequest implements ExecutableHttpRequest {
private final HttpExecuteResponse response;
TestExecutableHttpRequest(HttpExecuteResponse response) {
this.response = response;
}
@Override
public void abort() {
}
@Override
public HttpExecuteResponse call() throws IOException {
return response;
}
}
private void stubResponse(SdkAsyncHttpClient mockClient, int statusCode, String address, long cachePeriod) {
String responseBody = "{" +
" \"Endpoints\": [{" +
" \"Address\": \"" + address + "\"," +
" \"CachePeriodInMinutes\": " + cachePeriod +
" }]" +
"}";
stubResponse(mockClient, statusCode, responseBody);
}
private void stubResponse(SdkAsyncHttpClient mockClient, int statusCode, String responseBody) {
when(mockClient.execute(any())).thenAnswer(
stubAsyncResponse(SdkHttpResponse.builder().statusCode(statusCode).build(),
ByteBuffer.wrap(responseBody.getBytes(StandardCharsets.UTF_8))));
}
private void stubResponse(SdkHttpClient mockClient, int statusCode, String address, long cachePeriod) {
String responseBody = "{" +
" \"Endpoints\": [{" +
" \"Address\": \"" + address + "\"," +
" \"CachePeriodInMinutes\": " + cachePeriod +
" }]" +
"}";
stubResponse(mockClient, statusCode, responseBody);
}
private void stubResponse(SdkHttpClient mockClient, int statusCode, String responseBody) {
when(mockClient.prepareRequest(any())).thenReturn(new TestExecutableHttpRequest(
HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(statusCode)
.build())
.responseBody(AbortableInputStream.create(
new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8))))
.build()
));
}
private Answer<CompletableFuture<Void>> stubAsyncResponse(SdkHttpResponse response, ByteBuffer content) {
return (i) -> {
AsyncExecuteRequest request = i.getArgument(0, AsyncExecuteRequest.class);
request.responseHandler().onHeaders(response);
request.responseHandler().onStream(Flowable.just(content));
CompletableFuture<Void> cf = new CompletableFuture<>();
cf.complete(null);
return cf;
};
}
}
| 2,582 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/InvalidRegionTest.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.services;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
public class InvalidRegionTest {
@Test
public void invalidClientRegionGivesHelpfulMessage() {
assertThatThrownBy(() -> ProtocolRestJsonClient.builder()
.region(Region.of("US_EAST_1"))
.credentialsProvider(AnonymousCredentialsProvider.create())
.build())
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("US_EAST_1")
.hasMessageContaining("region");
}
}
| 2,583 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/NoneAuthTypeRequestTest.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.services;
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.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.reactivex.Flowable;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.awscore.client.builder.AwsAsyncClientBuilder;
import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder;
import software.amazon.awssdk.awscore.client.builder.AwsSyncClientBuilder;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullResponse;
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.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.ResolveIdentityRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient;
import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient;
/**
* Verify that the "authtype" C2J trait for request type is honored for each requests.
*/
public class NoneAuthTypeRequestTest {
private AwsCredentialsProvider credentialsProvider;
private SdkHttpClient httpClient;
private SdkAsyncHttpClient httpAsyncClient;
private ProtocolRestJsonClient jsonClient;
private ProtocolRestJsonAsyncClient jsonAsyncClient;
private ProtocolRestXmlClient xmlClient;
private ProtocolRestXmlAsyncClient xmlAsyncClient;
@Before
public void setup() throws IOException {
credentialsProvider = spy(AwsCredentialsProvider.class);
when(credentialsProvider.identityType()).thenReturn(AwsCredentialsIdentity.class);
when(credentialsProvider.resolveIdentity(any(ResolveIdentityRequest.class))).thenAnswer(
invocationOnMock -> CompletableFuture.completedFuture(AwsBasicCredentials.create("123", "12344")));
httpClient = mock(SdkHttpClient.class);
httpAsyncClient = mock(SdkAsyncHttpClient.class);
jsonClient = initializeSync(ProtocolRestJsonClient.builder()).build();
jsonAsyncClient = initializeAsync(ProtocolRestJsonAsyncClient.builder()).build();
xmlClient = initializeSync(ProtocolRestXmlClient.builder()).build();
xmlAsyncClient = initializeAsync(ProtocolRestXmlAsyncClient.builder()).build();
SdkHttpFullResponse successfulHttpResponse = SdkHttpResponse.builder()
.statusCode(200)
.putHeader("Content-Length", "0")
.build();
ExecutableHttpRequest request = mock(ExecutableHttpRequest.class);
when(request.call()).thenReturn(HttpExecuteResponse.builder()
.response(successfulHttpResponse)
.build());
when(httpClient.prepareRequest(any())).thenReturn(request);
when(httpAsyncClient.execute(any())).thenAnswer(invocation -> {
AsyncExecuteRequest asyncExecuteRequest = invocation.getArgument(0, AsyncExecuteRequest.class);
asyncExecuteRequest.responseHandler().onHeaders(successfulHttpResponse);
asyncExecuteRequest.responseHandler().onStream(Flowable.empty());
return CompletableFuture.completedFuture(null);
});
}
@Test
public void sync_json_authorization_is_absent_for_noneAuthType() {
jsonClient.operationWithNoneAuthType(o -> o.booleanMember(true));
assertThat(getSyncRequest().firstMatchingHeader("Authorization")).isNotPresent();
verify(credentialsProvider, times(0)).resolveIdentity(any(ResolveIdentityRequest.class));
}
@Test
public void sync_json_authorization_is_present_for_defaultAuth() {
jsonClient.jsonValuesOperation();
assertThat(getSyncRequest().firstMatchingHeader("Authorization")).isPresent();
verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class));
}
@Test
public void async_json_authorization_is_absent_for_noneAuthType() {
jsonAsyncClient.operationWithNoneAuthType(o -> o.booleanMember(true));
assertThat(getAsyncRequest().firstMatchingHeader("Authorization")).isNotPresent();
verify(credentialsProvider, times(0)).resolveIdentity(any(ResolveIdentityRequest.class));
}
@Test
public void async_json_authorization_is_present_for_defaultAuth() {
jsonAsyncClient.jsonValuesOperation();
assertThat(getAsyncRequest().firstMatchingHeader("Authorization")).isPresent();
verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class));
}
@Test
public void sync_xml_authorization_is_absent_for_noneAuthType() {
xmlClient.operationWithNoneAuthType(o -> o.booleanMember(true));
assertThat(getSyncRequest().firstMatchingHeader("Authorization")).isNotPresent();
verify(credentialsProvider, times(0)).resolveIdentity(any(ResolveIdentityRequest.class));
}
@Test
public void sync_xml_authorization_is_present_for_defaultAuth() {
xmlClient.jsonValuesOperation(json -> json.jsonValueMember("one"));
assertThat(getSyncRequest().firstMatchingHeader("Authorization")).isPresent();
verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class));
}
@Test
public void async_xml_authorization_is_absent_for_noneAuthType() {
xmlAsyncClient.operationWithNoneAuthType(o -> o.booleanMember(true));
assertThat(getAsyncRequest().firstMatchingHeader("Authorization")).isNotPresent();
verify(credentialsProvider, times(0)).resolveIdentity(any(ResolveIdentityRequest.class));
}
@Test
public void async_xml_authorization_is_present_for_defaultAuth() {
xmlAsyncClient.jsonValuesOperation(json -> json.jsonValueMember("one"));
assertThat(getAsyncRequest().firstMatchingHeader("Authorization")).isPresent();
verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class));
}
private SdkHttpRequest getSyncRequest() {
ArgumentCaptor<HttpExecuteRequest> captor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
verify(httpClient).prepareRequest(captor.capture());
return captor.getValue().httpRequest();
}
private SdkHttpRequest getAsyncRequest() {
ArgumentCaptor<AsyncExecuteRequest> captor = ArgumentCaptor.forClass(AsyncExecuteRequest.class);
verify(httpAsyncClient).execute(captor.capture());
return captor.getValue().request();
}
private <T extends AwsSyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeSync(T syncClientBuilder) {
return initialize(syncClientBuilder.httpClient(httpClient).credentialsProvider(credentialsProvider));
}
private <T extends AwsAsyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeAsync(T asyncClientBuilder) {
return initialize(asyncClientBuilder.httpClient(httpAsyncClient).credentialsProvider(credentialsProvider));
}
private <T extends AwsClientBuilder<T, ?>> T initialize(T clientBuilder) {
return clientBuilder.region(Region.US_WEST_2);
}
} | 2,584 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/OverrideConfigurationTest.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.services;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.endpointproviders.EndpointInterceptorTests;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClient;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClientBuilder;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClientBuilder;
public class OverrideConfigurationTest {
private CapturingInterceptor interceptor;
@BeforeEach
public void setup() {
this.interceptor = new CapturingInterceptor();
}
@Test
public void sync_clientOverrideConfiguration_isAddedToRequest() {
RestJsonEndpointProvidersClient syncClient = syncClientBuilder()
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)
.putHeader("K1", "V1"))
.build();
assertThatThrownBy(() -> syncClient.allTypes(r -> {}))
.hasMessageContaining("stop");
assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1"));
}
@Test
public void sync_requestOverrideConfiguration_isAddedToRequest() {
RestJsonEndpointProvidersClient syncClient = syncClientBuilder().build();
assertThatThrownBy(() -> syncClient.allTypes(r -> r.overrideConfiguration(c -> c.putHeader("K1", "V1")
.putRawQueryParameter("K2", "V2"))))
.hasMessageContaining("stop");
assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1"));
assertThat(interceptor.context.httpRequest().rawQueryParameters()).containsEntry("K2", singletonList("V2"));
}
@Test
public void async_clientOverrideConfiguration_isAddedToRequest() {
RestJsonEndpointProvidersAsyncClient syncClient = asyncClientBuilder()
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)
.putHeader("K1", "V1"))
.build();
assertThatThrownBy(() -> syncClient.allTypes(r -> {}).join())
.hasMessageContaining("stop");
assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1"));
}
@Test
public void async_requestOverrideConfiguration_isAddedToRequest() {
RestJsonEndpointProvidersAsyncClient syncClient = asyncClientBuilder().build();
assertThatThrownBy(() -> syncClient.allTypes(r -> r.overrideConfiguration(c -> c.putHeader("K1", "V1")
.putRawQueryParameter("K2", "V2")))
.join())
.hasMessageContaining("stop");
assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1"));
assertThat(interceptor.context.httpRequest().rawQueryParameters()).containsEntry("K2", singletonList("V2"));
}
private RestJsonEndpointProvidersClientBuilder syncClientBuilder() {
return RestJsonEndpointProvidersClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")))
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor));
}
private RestJsonEndpointProvidersAsyncClientBuilder asyncClientBuilder() {
return RestJsonEndpointProvidersAsyncClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")))
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor));
}
public static class CapturingInterceptor implements ExecutionInterceptor {
private Context.BeforeTransmission context;
private ExecutionAttributes executionAttributes;
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
this.context = context;
this.executionAttributes = executionAttributes;
throw new RuntimeException("stop");
}
public ExecutionAttributes executionAttributes() {
return executionAttributes;
}
public class CaptureCompletedException extends RuntimeException {
CaptureCompletedException(String message) {
super(message);
}
}
}
}
| 2,585 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/SraIdentityResolutionTest.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.services;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.any;
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 java.util.concurrent.CompletableFuture;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.ResolveIdentityRequest;
import software.amazon.awssdk.services.protocolquery.ProtocolQueryClient;
@RunWith(MockitoJUnitRunner.class)
public class SraIdentityResolutionTest {
@Mock
private AwsCredentialsProvider credsProvider;
@Test
public void testIdentityPropertyBasedResolutionIsUsedAndNotAnotherIdentityResolution() {
SdkHttpClient mockClient = mock(SdkHttpClient.class);
when(mockClient.prepareRequest(any())).thenThrow(new RuntimeException("boom"));
when(credsProvider.identityType()).thenReturn(AwsCredentialsIdentity.class);
when(credsProvider.resolveIdentity(any(ResolveIdentityRequest.class)))
.thenReturn(CompletableFuture.completedFuture(AwsBasicCredentials.create("akid1", "skid2")));
ProtocolQueryClient syncClient = ProtocolQueryClient
.builder()
.httpClient(mockClient)
.credentialsProvider(credsProvider)
// Below is necessary to create the test case where, addCredentialsToExecutionAttributes was getting called before
.overrideConfiguration(ClientOverrideConfiguration.builder().build())
.build();
assertThatThrownBy(() -> syncClient.allTypes(r -> {})).hasMessageContaining("boom");
verify(credsProvider, times(2)).identityType();
// This asserts that the identity used is the one from resolveIdentity() called by SRA AuthSchemeInterceptor and not from
// from another call like from AwsCredentialsAuthorizationStrategy.addCredentialsToExecutionAttributes, asserted by
// combination of times(1) and verifyNoMoreInteractions.
verify(credsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class));
verifyNoMoreInteractions(credsProvider);
}
}
| 2,586 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/OverrideConfigurationPluginsTest.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.services;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.SdkPlugin;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClient;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClientBuilder;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClientBuilder;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersServiceClientConfiguration;
import software.amazon.awssdk.utils.Validate;
public class OverrideConfigurationPluginsTest {
private CapturingInterceptor interceptor;
@BeforeEach
void setup() {
this.interceptor = new CapturingInterceptor();
}
@Test
void sync_pluginsClientOverrideConfiguration_isAddedToRequest() {
RestJsonEndpointProvidersClient syncClient = syncClientBuilder()
.addPlugin(config -> config.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)
.putHeader("K1", "V1")))
.build();
assertThatThrownBy(() -> syncClient.allTypes(r -> {
}))
.hasMessageContaining("boom!");
assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1"));
}
@Test
void sync_pluginsRequestOverrideConfiguration_isAddedToRequest() {
RestJsonEndpointProvidersClient syncClient = syncClientBuilder().build();
SdkPlugin plugin = config -> config.overrideConfiguration(c -> c.putHeader("K1", "V1"));
assertThatThrownBy(() -> syncClient.allTypes(r -> r.overrideConfiguration(c -> c.addPlugin(plugin))))
.hasMessageContaining("boom!");
assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1"));
}
@Test
void async_pluginsClientOverrideConfiguration_isAddedToRequest() {
RestJsonEndpointProvidersAsyncClient syncClient = asyncClientBuilder()
.addPlugin(config -> config.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)
.putHeader("K1", "V1")))
.build();
assertThatThrownBy(() -> syncClient.allTypes(r -> {
}).join())
.hasMessageContaining("boom!");
assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1"));
}
@Test
void async_pluginsRequestOverrideConfiguration_isAddedToRequest() {
RestJsonEndpointProvidersAsyncClient syncClient = asyncClientBuilder().build();
SdkPlugin plugin = config -> config.overrideConfiguration(c -> c.putHeader("K1", "V1"));
assertThatThrownBy(() -> syncClient.allTypes(r -> r.overrideConfiguration(c -> c.addPlugin(plugin)))
.join())
.hasMessageContaining("boom!");
assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1"));
}
private RestJsonEndpointProvidersClientBuilder syncClientBuilder() {
return RestJsonEndpointProvidersClient
.builder()
.addPlugin(c -> {
RestJsonEndpointProvidersServiceClientConfiguration.Builder config =
Validate.isInstanceOf(RestJsonEndpointProvidersServiceClientConfiguration.Builder.class, c, "\uD83E\uDD14");
config.region(Region.US_WEST_2)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")))
.overrideConfiguration(oc -> oc.addExecutionInterceptor(interceptor));
});
}
private RestJsonEndpointProvidersAsyncClientBuilder asyncClientBuilder() {
return RestJsonEndpointProvidersAsyncClient
.builder()
.addPlugin(c -> {
RestJsonEndpointProvidersServiceClientConfiguration.Builder config =
Validate.isInstanceOf(RestJsonEndpointProvidersServiceClientConfiguration.Builder.class, c, "\uD83E\uDD14");
config.region(Region.US_WEST_2)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")))
.overrideConfiguration(oc -> oc.addExecutionInterceptor(interceptor));
});
}
public static class CapturingInterceptor implements ExecutionInterceptor {
private Context.BeforeTransmission context;
private ExecutionAttributes executionAttributes;
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
this.context = context;
this.executionAttributes = executionAttributes;
throw new RuntimeException("boom!");
}
public ExecutionAttributes executionAttributes() {
return executionAttributes;
}
public class CaptureCompletedException extends RuntimeException {
CaptureCompletedException(String message) {
super(message);
}
}
}
}
| 2,587 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/RequestCompressionTest.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.services;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.AfterEach;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.internal.compression.Compressor;
import software.amazon.awssdk.core.internal.compression.GzipCompressor;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.PutOperationWithRequestCompressionRequest;
import software.amazon.awssdk.services.protocolrestjson.model.PutOperationWithStreamingRequestCompressionRequest;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
public class RequestCompressionTest {
private static final String UNCOMPRESSED_BODY =
"RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest";
private String compressedBody;
private int compressedLen;
private MockSyncHttpClient mockHttpClient;
private ProtocolRestJsonClient syncClient;
private Compressor compressor;
private RequestBody requestBody;
@BeforeEach
public void setUp() {
mockHttpClient = new MockSyncHttpClient();
syncClient = ProtocolRestJsonClient.builder()
.credentialsProvider(AnonymousCredentialsProvider.create())
.region(Region.US_EAST_1)
.httpClient(mockHttpClient)
.build();
compressor = new GzipCompressor();
byte[] compressedBodyBytes = compressor.compress(UNCOMPRESSED_BODY.getBytes());
compressedLen = compressedBodyBytes.length;
compressedBody = new String(compressedBodyBytes);
TestContentProvider provider = new TestContentProvider(UNCOMPRESSED_BODY.getBytes());
requestBody = RequestBody.fromContentProvider(provider, "binary/octet-stream");
}
@AfterEach
public void reset() {
mockHttpClient.reset();
}
@Test
public void syncNonStreamingOperation_compressionEnabledThresholdOverridden_compressesCorrectly() {
mockHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500));
PutOperationWithRequestCompressionRequest request =
PutOperationWithRequestCompressionRequest.builder()
.body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY))
.overrideConfiguration(o -> o.compressionConfiguration(
c -> c.minimumCompressionThresholdInBytes(1)))
.build();
syncClient.putOperationWithRequestCompression(request);
SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockHttpClient.getLastRequest();
InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream();
String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray());
int loggedSize = Integer.valueOf(loggedRequest.firstMatchingHeader("Content-Length").get());
assertThat(loggedBody).isEqualTo(compressedBody);
assertThat(loggedSize).isEqualTo(compressedLen);
assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip");
}
@Test
public void syncNonStreamingOperation_payloadSizeLessThanCompressionThreshold_doesNotCompress() {
mockHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500));
PutOperationWithRequestCompressionRequest request =
PutOperationWithRequestCompressionRequest.builder()
.body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY))
.build();
syncClient.putOperationWithRequestCompression(request);
SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockHttpClient.getLastRequest();
InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream();
String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray());
assertThat(loggedBody).isEqualTo(UNCOMPRESSED_BODY);
assertThat(loggedRequest.firstMatchingHeader("Content-encoding")).isEmpty();
}
@Test
public void syncStreamingOperation_compressionEnabled_compressesCorrectly() {
mockHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500));
PutOperationWithStreamingRequestCompressionRequest request =
PutOperationWithStreamingRequestCompressionRequest.builder().build();
syncClient.putOperationWithStreamingRequestCompression(request, requestBody, ResponseTransformer.toBytes());
SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockHttpClient.getLastRequest();
InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream();
String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray());
assertThat(loggedBody).isEqualTo(compressedBody);
assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip");
assertThat(loggedRequest.matchingHeaders("Content-Length")).isEmpty();
assertThat(loggedRequest.firstMatchingHeader("Transfer-Encoding").get()).isEqualTo("chunked");
}
@Test
public void syncNonStreamingOperation_compressionEnabledThresholdOverriddenWithRetry_compressesCorrectly() {
mockHttpClient.stubNextResponse(mockErrorResponse(), Duration.ofMillis(500));
mockHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500));
PutOperationWithRequestCompressionRequest request =
PutOperationWithRequestCompressionRequest.builder()
.body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY))
.overrideConfiguration(o -> o.compressionConfiguration(
c -> c.minimumCompressionThresholdInBytes(1)))
.build();
syncClient.putOperationWithRequestCompression(request);
SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockHttpClient.getLastRequest();
InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream();
String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray());
int loggedSize = Integer.valueOf(loggedRequest.firstMatchingHeader("Content-Length").get());
assertThat(loggedBody).isEqualTo(compressedBody);
assertThat(loggedSize).isEqualTo(compressedLen);
assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip");
}
@Test
public void syncStreamingOperation_compressionEnabledWithRetry_compressesCorrectly() {
mockHttpClient.stubNextResponse(mockErrorResponse(), Duration.ofMillis(500));
mockHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500));
PutOperationWithStreamingRequestCompressionRequest request =
PutOperationWithStreamingRequestCompressionRequest.builder().build();
syncClient.putOperationWithStreamingRequestCompression(request, requestBody, ResponseTransformer.toBytes());
SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockHttpClient.getLastRequest();
InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream();
String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray());
assertThat(loggedBody).isEqualTo(compressedBody);
assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip");
assertThat(loggedRequest.matchingHeaders("Content-Length")).isEmpty();
assertThat(loggedRequest.firstMatchingHeader("Transfer-Encoding").get()).isEqualTo("chunked");
}
private HttpExecuteResponse mockResponse() {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder().statusCode(200).build())
.build();
}
private HttpExecuteResponse mockErrorResponse() {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder().statusCode(500).build())
.build();
}
private static final class TestContentProvider implements ContentStreamProvider {
private final byte[] content;
private final List<CloseTrackingInputStream> createdStreams = new ArrayList<>();
private CloseTrackingInputStream currentStream;
private TestContentProvider(byte[] content) {
this.content = content;
}
@Override
public InputStream newStream() {
if (currentStream != null) {
invokeSafely(currentStream::close);
}
currentStream = new CloseTrackingInputStream(new ByteArrayInputStream(content));
createdStreams.add(currentStream);
return currentStream;
}
List<CloseTrackingInputStream> getCreatedStreams() {
return createdStreams;
}
}
private static class CloseTrackingInputStream extends FilterInputStream {
private boolean isClosed = false;
CloseTrackingInputStream(InputStream in) {
super(in);
}
@Override
public void close() throws IOException {
super.close();
isClosed = true;
}
boolean isClosed() {
return isClosed;
}
}
}
| 2,588 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/UnionTypeTest.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.services;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.util.DefaultSdkAutoConstructList;
import software.amazon.awssdk.core.util.DefaultSdkAutoConstructMap;
import software.amazon.awssdk.services.protocolrestjson.model.AllTypesUnionStructure;
import software.amazon.awssdk.services.protocolrestjson.model.AllTypesUnionStructure.Type;
import software.amazon.awssdk.services.protocolrestjson.model.BaseType;
import software.amazon.awssdk.services.protocolrestjson.model.EnumType;
import software.amazon.awssdk.services.protocolrestjson.model.RecursiveStructType;
import software.amazon.awssdk.services.protocolrestjson.model.StructWithNestedBlobType;
import software.amazon.awssdk.services.protocolrestjson.model.StructWithTimestamp;
import software.amazon.awssdk.services.protocolrestjson.model.SubTypeOne;
public class UnionTypeTest {
public static List<TestCase<?>> testCases() {
List<TestCase<?>> tests = new ArrayList<>();
tests.add(new TestCase<>(Type.STRING_MEMBER,
"foo",
AllTypesUnionStructure::fromStringMember,
AllTypesUnionStructure::stringMember,
AllTypesUnionStructure.Builder::stringMember));
tests.add(new TestCase<>(Type.INTEGER_MEMBER,
5,
AllTypesUnionStructure::fromIntegerMember,
AllTypesUnionStructure::integerMember,
AllTypesUnionStructure.Builder::integerMember));
tests.add(new TestCase<>(Type.BOOLEAN_MEMBER,
true,
AllTypesUnionStructure::fromBooleanMember,
AllTypesUnionStructure::booleanMember,
AllTypesUnionStructure.Builder::booleanMember));
tests.add(new TestCase<>(Type.FLOAT_MEMBER,
0.1f,
AllTypesUnionStructure::fromFloatMember,
AllTypesUnionStructure::floatMember,
AllTypesUnionStructure.Builder::floatMember));
tests.add(new TestCase<>(Type.DOUBLE_MEMBER,
0.1d,
AllTypesUnionStructure::fromDoubleMember,
AllTypesUnionStructure::doubleMember,
AllTypesUnionStructure.Builder::doubleMember));
tests.add(new TestCase<>(Type.LONG_MEMBER,
5L,
AllTypesUnionStructure::fromLongMember,
AllTypesUnionStructure::longMember,
AllTypesUnionStructure.Builder::longMember));
tests.add(new TestCase<>(Type.SHORT_MEMBER,
(short) 5,
AllTypesUnionStructure::fromShortMember,
AllTypesUnionStructure::shortMember,
AllTypesUnionStructure.Builder::shortMember));
tests.add(new TestCase<>(Type.ENUM_MEMBER,
EnumType.ENUM_VALUE1,
AllTypesUnionStructure::fromEnumMember,
AllTypesUnionStructure::enumMember,
AllTypesUnionStructure.Builder::enumMember));
tests.add(new TestCase<>(Type.SIMPLE_LIST,
emptyList(),
AllTypesUnionStructure::fromSimpleList,
AllTypesUnionStructure::simpleList,
AllTypesUnionStructure.Builder::simpleList));
tests.add(new TestCase<>(Type.LIST_OF_ENUMS,
emptyList(),
AllTypesUnionStructure::fromListOfEnums,
AllTypesUnionStructure::listOfEnums,
AllTypesUnionStructure.Builder::listOfEnums));
tests.add(new TestCase<>(Type.LIST_OF_MAPS,
emptyList(),
AllTypesUnionStructure::fromListOfMaps,
AllTypesUnionStructure::listOfMaps,
AllTypesUnionStructure.Builder::listOfMaps));
tests.add(new TestCase<>(Type.LIST_OF_LIST_OF_MAPS_OF_STRING_TO_STRUCT,
emptyList(),
AllTypesUnionStructure::fromListOfListOfMapsOfStringToStruct,
AllTypesUnionStructure::listOfListOfMapsOfStringToStruct,
AllTypesUnionStructure.Builder::listOfListOfMapsOfStringToStruct));
tests.add(new TestCase<>(Type.LIST_OF_MAPS_OF_STRING_TO_STRUCT,
emptyList(),
AllTypesUnionStructure::fromListOfMapsOfStringToStruct,
AllTypesUnionStructure::listOfMapsOfStringToStruct,
AllTypesUnionStructure.Builder::listOfMapsOfStringToStruct));
tests.add(new TestCase<>(Type.LIST_OF_STRUCTS,
emptyList(),
AllTypesUnionStructure::fromListOfStructs,
AllTypesUnionStructure::listOfStructs,
AllTypesUnionStructure.Builder::listOfStructs));
tests.add(new TestCase<>(Type.MAP_OF_STRING_TO_INTEGER_LIST,
emptyMap(),
AllTypesUnionStructure::fromMapOfStringToIntegerList,
AllTypesUnionStructure::mapOfStringToIntegerList,
AllTypesUnionStructure.Builder::mapOfStringToIntegerList));
tests.add(new TestCase<>(Type.MAP_OF_STRING_TO_STRING,
emptyMap(),
AllTypesUnionStructure::fromMapOfStringToString,
AllTypesUnionStructure::mapOfStringToString,
AllTypesUnionStructure.Builder::mapOfStringToString));
tests.add(new TestCase<>(Type.MAP_OF_STRING_TO_STRUCT,
emptyMap(),
AllTypesUnionStructure::fromMapOfStringToStruct,
AllTypesUnionStructure::mapOfStringToStruct,
AllTypesUnionStructure.Builder::mapOfStringToStruct));
tests.add(new TestCase<>(Type.MAP_OF_ENUM_TO_ENUM,
emptyMap(),
AllTypesUnionStructure::fromMapOfEnumToEnum,
AllTypesUnionStructure::mapOfEnumToEnum,
AllTypesUnionStructure.Builder::mapOfEnumToEnum));
tests.add(new TestCase<>(Type.TIMESTAMP_MEMBER,
Instant.now(),
AllTypesUnionStructure::fromTimestampMember,
AllTypesUnionStructure::timestampMember,
AllTypesUnionStructure.Builder::timestampMember));
tests.add(new TestCase<>(Type.STRUCT_WITH_NESTED_TIMESTAMP_MEMBER,
StructWithTimestamp.builder().build(),
AllTypesUnionStructure::fromStructWithNestedTimestampMember,
AllTypesUnionStructure::structWithNestedTimestampMember,
AllTypesUnionStructure.Builder::structWithNestedTimestampMember));
tests.add(new TestCase<>(Type.BLOB_ARG,
SdkBytes.fromUtf8String(""),
AllTypesUnionStructure::fromBlobArg,
AllTypesUnionStructure::blobArg,
AllTypesUnionStructure.Builder::blobArg));
tests.add(new TestCase<>(Type.STRUCT_WITH_NESTED_BLOB,
StructWithNestedBlobType.builder().build(),
AllTypesUnionStructure::fromStructWithNestedBlob,
AllTypesUnionStructure::structWithNestedBlob,
AllTypesUnionStructure.Builder::structWithNestedBlob));
tests.add(new TestCase<>(Type.BLOB_MAP,
emptyMap(),
AllTypesUnionStructure::fromBlobMap,
AllTypesUnionStructure::blobMap,
AllTypesUnionStructure.Builder::blobMap));
tests.add(new TestCase<>(Type.LIST_OF_BLOBS,
emptyList(),
AllTypesUnionStructure::fromListOfBlobs,
AllTypesUnionStructure::listOfBlobs,
AllTypesUnionStructure.Builder::listOfBlobs));
tests.add(new TestCase<>(Type.RECURSIVE_STRUCT,
RecursiveStructType.builder().build(),
AllTypesUnionStructure::fromRecursiveStruct,
AllTypesUnionStructure::recursiveStruct,
AllTypesUnionStructure.Builder::recursiveStruct));
tests.add(new TestCase<>(Type.POLYMORPHIC_TYPE_WITH_SUB_TYPES,
BaseType.builder().build(),
AllTypesUnionStructure::fromPolymorphicTypeWithSubTypes,
AllTypesUnionStructure::polymorphicTypeWithSubTypes,
AllTypesUnionStructure.Builder::polymorphicTypeWithSubTypes));
tests.add(new TestCase<>(Type.POLYMORPHIC_TYPE_WITHOUT_SUB_TYPES,
SubTypeOne.builder().build(),
AllTypesUnionStructure::fromPolymorphicTypeWithoutSubTypes,
AllTypesUnionStructure::polymorphicTypeWithoutSubTypes,
AllTypesUnionStructure.Builder::polymorphicTypeWithoutSubTypes));
tests.add(new TestCase<>(Type.SET_PREFIXED_MEMBER,
"foo",
AllTypesUnionStructure::fromSetPrefixedMember,
AllTypesUnionStructure::setPrefixedMember,
AllTypesUnionStructure.Builder::setPrefixedMember));
tests.add(new TestCase<>(Type.UNION_MEMBER,
AllTypesUnionStructure.builder().build(),
AllTypesUnionStructure::fromUnionMember,
AllTypesUnionStructure::unionMember,
AllTypesUnionStructure.Builder::unionMember));
return tests;
}
@Test
public void allTypesTested() {
Set<Type> types = EnumSet.allOf(Type.class);
types.remove(Type.UNKNOWN_TO_SDK_VERSION);
Set<Type> testedTypes = testCases().stream().map(t -> t.type).collect(Collectors.toSet());
assertThat(testedTypes).isEqualTo(types); // If this fails, it means you need to add a test case above
}
@Test
public void noMembersIsUnknownType() {
assertThat(AllTypesUnionStructure.builder().build().type()).isEqualTo(Type.UNKNOWN_TO_SDK_VERSION);
}
@ParameterizedTest
@MethodSource("testCases")
public <T> void twoMembersIsNull(TestCase<T> testCase) {
AllTypesUnionStructure.Builder builder = AllTypesUnionStructure.builder();
testCase.setter.apply(builder, testCase.value);
if (testCase.type == Type.STRING_MEMBER) {
builder.integerMember(5);
} else {
builder.stringMember("foo");
}
assertThat(builder.build().type()).isNull();
}
@ParameterizedTest
@MethodSource("testCases")
public <T> void twoMinusOneMemberIsKnownType(TestCase<T> testCase) {
AllTypesUnionStructure.Builder builder = AllTypesUnionStructure.builder();
if (testCase.type == Type.STRING_MEMBER) {
builder.integerMember(5);
} else {
builder.stringMember("foo");
}
testCase.setter.apply(builder, testCase.value);
if (testCase.type == Type.STRING_MEMBER) {
builder.integerMember(null);
} else {
builder.stringMember(null);
}
assertThat(builder.build().type()).isEqualTo(testCase.type);
}
@ParameterizedTest
@MethodSource("testCases")
public <T> void staticConstructorsWork(TestCase<T> testCase) {
AllTypesUnionStructure structure = testCase.constructor.apply(testCase.value);
T valuePassedThrough = testCase.getter.apply(structure);
assertThat(valuePassedThrough).isEqualTo(testCase.value);
assertThat(structure.type()).isEqualTo(testCase.type);
}
@ParameterizedTest
@MethodSource("testCases")
public <T> void typeIsPreservedThroughToBuilder(TestCase<T> testCase) {
AllTypesUnionStructure structure = testCase.constructor.apply(testCase.value);
assertThat(structure.toBuilder().build().type()).isEqualTo(testCase.type);
}
@Test
public void autoConstructListsArentCountedForType() {
assertThat(AllTypesUnionStructure.builder()
.stringMember("foo")
.listOfMaps(DefaultSdkAutoConstructList.getInstance())
.build()
.type())
.isEqualTo(Type.STRING_MEMBER);
assertThat(AllTypesUnionStructure.builder()
.listOfMaps(DefaultSdkAutoConstructList.getInstance())
.stringMember("foo")
.build()
.type())
.isEqualTo(Type.STRING_MEMBER);
}
@Test
public void autoConstructMapsArentCountedForType() {
assertThat(AllTypesUnionStructure.builder()
.stringMember("foo")
.mapOfEnumToEnum(DefaultSdkAutoConstructMap.getInstance())
.build()
.type())
.isEqualTo(Type.STRING_MEMBER);
assertThat(AllTypesUnionStructure.builder()
.mapOfEnumToEnum(DefaultSdkAutoConstructMap.getInstance())
.stringMember("foo")
.build()
.type())
.isEqualTo(Type.STRING_MEMBER);
}
private static class TestCase<T> {
private final Type type;
private final T value;
private final Function<T, AllTypesUnionStructure> constructor;
private final Function<AllTypesUnionStructure, T> getter;
private final BiFunction<AllTypesUnionStructure.Builder, T, AllTypesUnionStructure.Builder> setter;
public TestCase(Type type,
T value,
Function<T, AllTypesUnionStructure> constructor,
Function<AllTypesUnionStructure, T> getter,
BiFunction<AllTypesUnionStructure.Builder, T, AllTypesUnionStructure.Builder> setter) {
this.type = type;
this.value = value;
this.constructor = constructor;
this.getter = getter;
this.setter = setter;
}
@Override
public String toString() {
return type + " test";
}
}
}
| 2,589 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/SraIdentityResolutionUsingRequestPluginsTest.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.services;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
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.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.util.concurrent.CompletableFuture;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.SdkPlugin;
import software.amazon.awssdk.core.SdkServiceClientConfiguration;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.ResolveIdentityRequest;
import software.amazon.awssdk.services.protocolquery.ProtocolQueryClient;
import software.amazon.awssdk.services.protocolquery.ProtocolQueryServiceClientConfiguration;
import software.amazon.awssdk.services.protocolquery.model.AllTypesRequest;
import software.amazon.awssdk.utils.Validate;
@RunWith(MockitoJUnitRunner.class)
public class SraIdentityResolutionUsingRequestPluginsTest {
@Mock
private AwsCredentialsProvider credentialsProvider;
@Test
public void testIdentityBasedPluginsResolutionIsUsedAndNotAnotherIdentityResolution() {
SdkHttpClient mockClient = mock(SdkHttpClient.class);
when(mockClient.prepareRequest(any())).thenThrow(new RuntimeException("boom"));
when(credentialsProvider.identityType()).thenReturn(AwsCredentialsIdentity.class);
when(credentialsProvider.resolveIdentity(any(ResolveIdentityRequest.class)))
.thenReturn(CompletableFuture.completedFuture(AwsBasicCredentials.create("akid1", "skid2")));
ProtocolQueryClient syncClient = ProtocolQueryClient
.builder()
.httpClient(mockClient)
.build();
AllTypesRequest request = AllTypesRequest.builder()
.overrideConfiguration(c -> c.addPlugin(new TestPlugin(credentialsProvider)))
.build();
assertThatThrownBy(() -> syncClient.allTypes(request))
.hasMessageContaining("boom");
verify(credentialsProvider, times(2)).identityType();
// This asserts that the identity used is the one from resolveIdentity() called by SRA AuthSchemeInterceptor and not
// from another call like from AwsCredentialsAuthorizationStrategy.addCredentialsToExecutionAttributes, asserted by
// combination of times(1) and verifyNoMoreInteractions.
verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class));
verifyNoMoreInteractions(credentialsProvider);
}
static class TestPlugin implements SdkPlugin {
private final AwsCredentialsProvider credentialsProvider;
TestPlugin(AwsCredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
}
@Override
public void configureClient(SdkServiceClientConfiguration.Builder config) {
ProtocolQueryServiceClientConfiguration.Builder builder =
Validate.isInstanceOf(ProtocolQueryServiceClientConfiguration.Builder.class,
config,
"Expecting an instance of " +
ProtocolQueryServiceClientConfiguration.class);
builder.credentialsProvider(credentialsProvider);
}
}
}
| 2,590 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/EndpointVariantResolutionTest.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.services;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder;
public class EndpointVariantResolutionTest {
@Test
public void dualstackEndpointResolution() {
EndpointCapturingInterceptor interceptor = new EndpointCapturingInterceptor();
try {
clientBuilder(interceptor).dualstackEnabled(true).build().allTypes();
} catch (EndpointCapturingInterceptor.CaptureCompletedException e) {
// Expected
}
assertThat(interceptor.endpoints())
.singleElement()
.isEqualTo("https://customresponsemetadata.us-west-2.api.aws/2016-03-11/allTypes");
}
@Test
public void fipsEndpointResolution() {
EndpointCapturingInterceptor interceptor = new EndpointCapturingInterceptor();
try {
clientBuilder(interceptor).fipsEnabled(true).build().allTypes();
} catch (EndpointCapturingInterceptor.CaptureCompletedException e) {
// Expected
}
assertThat(interceptor.endpoints())
.singleElement()
.isEqualTo("https://customresponsemetadata-fips.us-west-2.amazonaws.com/2016-03-11/allTypes");
}
@Test
public void dualstackFipsEndpointResolution() {
EndpointCapturingInterceptor interceptor = new EndpointCapturingInterceptor();
try {
clientBuilder(interceptor).dualstackEnabled(true).fipsEnabled(true).build().allTypes();
} catch (EndpointCapturingInterceptor.CaptureCompletedException e) {
// Expected
}
assertThat(interceptor.endpoints())
.singleElement()
.isEqualTo("https://customresponsemetadata-fips.us-west-2.api.aws/2016-03-11/allTypes");
}
private ProtocolRestJsonClientBuilder clientBuilder(EndpointCapturingInterceptor interceptor) {
return ProtocolRestJsonClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(AnonymousCredentialsProvider.create())
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor));
}
}
| 2,591 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/AsyncSignerOverrideTest.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.services;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationRequest;
/**
* Test to ensure that operations that use the {@link software.amazon.awssdk.auth.signer.AsyncAws4Signer} don't apply
* the override when the signer is overridden by the customer.
*/
@RunWith(MockitoJUnitRunner.class)
public class AsyncSignerOverrideTest {
@Mock
public Signer mockSigner;
@Test
public void test_signerOverriddenForStreamingInput_takesPrecedence() {
ProtocolRestJsonAsyncClient asyncClient = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_WEST_2)
.overrideConfiguration(o -> o.putAdvancedOption(SIGNER, mockSigner))
.build();
try {
asyncClient.streamingInputOperation(StreamingInputOperationRequest.builder().build(),
AsyncRequestBody.fromString("test")).join();
} catch (Exception expected) {
}
verify(mockSigner).sign(any(SdkHttpFullRequest.class), any(ExecutionAttributes.class));
}
// TODO(sra-identity-and-auth): Add test for SRA way of overriding signer to assert that overridden signer is used.
// At that point, rename this class to SignerOverrideTest, not specific to AsyncSignerOverride (which was for operation
// level codegen changes).
}
| 2,592 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/HttpChecksumInHeaderTest.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.services;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import io.reactivex.Flowable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.awscore.client.builder.AwsAsyncClientBuilder;
import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder;
import software.amazon.awssdk.awscore.client.builder.AwsSyncClientBuilder;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullResponse;
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.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.ChecksumAlgorithm;
import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient;
import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient;
/**
* Verify that the "HttpChecksum" C2J trait results in a valid checksum of the payload being included in the HTTP
* request.
*/
public class HttpChecksumInHeaderTest {
public static Set<String> VALID_CHECKSUM_HEADERS =
Arrays.stream(Algorithm.values()).map(x -> "x-amz-checksum-" + x).collect(Collectors.toSet());
private SdkHttpClient httpClient;
private SdkAsyncHttpClient httpAsyncClient;
private ProtocolRestJsonClient jsonClient;
private ProtocolRestJsonAsyncClient jsonAsyncClient;
private ProtocolRestXmlClient xmlClient;
private ProtocolRestXmlAsyncClient xmlAsyncClient;
@Before
public void setup() throws IOException {
httpClient = Mockito.mock(SdkHttpClient.class);
httpAsyncClient = Mockito.mock(SdkAsyncHttpClient.class);
jsonClient = initializeSync(ProtocolRestJsonClient.builder()).build();
jsonAsyncClient = initializeAsync(ProtocolRestJsonAsyncClient.builder()).build();
xmlClient = initializeSync(ProtocolRestXmlClient.builder()).build();
xmlAsyncClient = initializeAsync(ProtocolRestXmlAsyncClient.builder()).build();
SdkHttpFullResponse successfulHttpResponse = SdkHttpResponse.builder()
.statusCode(200)
.putHeader("Content-Length", "0")
.build();
ExecutableHttpRequest request = Mockito.mock(ExecutableHttpRequest.class);
Mockito.when(request.call()).thenReturn(HttpExecuteResponse.builder()
.response(successfulHttpResponse)
.build());
Mockito.when(httpClient.prepareRequest(any())).thenReturn(request);
Mockito.when(httpAsyncClient.execute(any())).thenAnswer(invocation -> {
AsyncExecuteRequest asyncExecuteRequest = invocation.getArgument(0, AsyncExecuteRequest.class);
asyncExecuteRequest.responseHandler().onHeaders(successfulHttpResponse);
asyncExecuteRequest.responseHandler().onStream(Flowable.empty());
return CompletableFuture.completedFuture(null);
});
}
@Test
public void sync_json_nonStreaming_unsignedPayload_with_Sha1_in_header() {
// jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world"));
jsonClient.operationWithChecksumNonStreaming(
r -> r.stringMember("Hello world").checksumAlgorithm(ChecksumAlgorithm.SHA1).build());
assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent();
//Note that content will be of form "{"stringMember":"Hello world"}"
assertThat(getSyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("M68rRwFal7o7B3KEMt3m0w39TaA=");
}
@Test
public void aync_json_nonStreaming_unsignedPayload_with_Sha1_in_header() {
// jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world"));
jsonAsyncClient.operationWithChecksumNonStreaming(
r -> r.checksumAlgorithm(ChecksumAlgorithm.SHA1).stringMember("Hello world").build());
assertThat(getAsyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent();
//Note that content will be of form "{"stringMember":"Hello world"}"
assertThat(getAsyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("M68rRwFal7o7B3KEMt3m0w39TaA=");
}
@Test
public void sync_xml_nonStreaming_unsignedPayload_with_Sha1_in_header() {
// jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world"));
xmlClient.operationWithChecksumNonStreaming(r -> r.stringMember("Hello world")
.checksumAlgorithm(software.amazon.awssdk.services.protocolrestxml.model.ChecksumAlgorithm.SHA1).build());
assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent();
//Note that content will be of form "<?xml version="1.0" encoding="UTF-8"?><stringMember>Hello world</stringMember>"
// TODO(sra-identity-and-auth): Uncomment once sra is set to true
// assertThat(getSyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("FB/utBbwFLbIIt5ul3Ojuy5dKgU=");
}
@Test
public void sync_xml_nonStreaming_unsignedEmptyPayload_with_Sha1_in_header() {
// jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world"));
xmlClient.operationWithChecksumNonStreaming(r -> r.checksumAlgorithm(software.amazon.awssdk.services.protocolrestxml.model.ChecksumAlgorithm.SHA1).build());
assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent();
//Note that content will be of form "<?xml version="1.0" encoding="UTF-8"?><stringMember>Hello world</stringMember>"
// TODO(sra-identity-and-auth): Uncomment once sra is set to true
// assertThat(getSyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("2jmj7l5rSw0yVb/vlWAYkK/YBwk=");
}
@Test
public void aync_xml_nonStreaming_unsignedPayload_with_Sha1_in_header() {
// jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world"));
xmlAsyncClient.operationWithChecksumNonStreaming(r -> r.stringMember("Hello world")
.checksumAlgorithm(software.amazon.awssdk.services.protocolrestxml.model.ChecksumAlgorithm.SHA1).build()).join();
assertThat(getAsyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent();
//Note that content will be of form <?xml version="1.0" encoding="UTF-8"?><stringMember>Hello world</stringMember>"
assertThat(getAsyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("FB/utBbwFLbIIt5ul3Ojuy5dKgU=");
}
@Test
public void aync_xml_nonStreaming_unsignedEmptyPayload_with_Sha1_in_header() {
// jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world"));
xmlAsyncClient.operationWithChecksumNonStreaming(r -> r.checksumAlgorithm(software.amazon.awssdk.services.protocolrestxml.model.ChecksumAlgorithm.SHA1).build()).join();
assertThat(getAsyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent();
//Note that content will be of form <?xml version="1.0" encoding="UTF-8"?><stringMember>Hello world</stringMember>"
// TODO(sra-identity-and-auth): Uncomment once sra is set to true
// assertThat(getAsyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("2jmj7l5rSw0yVb/vlWAYkK/YBwk=");
}
private SdkHttpRequest getSyncRequest() {
ArgumentCaptor<HttpExecuteRequest> captor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
Mockito.verify(httpClient).prepareRequest(captor.capture());
return captor.getValue().httpRequest();
}
private SdkHttpRequest getAsyncRequest() {
ArgumentCaptor<AsyncExecuteRequest> captor = ArgumentCaptor.forClass(AsyncExecuteRequest.class);
Mockito.verify(httpAsyncClient).execute(captor.capture());
return captor.getValue().request();
}
private <T extends AwsSyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeSync(T syncClientBuilder) {
return initialize(syncClientBuilder.httpClient(httpClient));
}
private <T extends AwsAsyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeAsync(T asyncClientBuilder) {
return initialize(asyncClientBuilder.httpClient(httpAsyncClient));
}
private <T extends AwsClientBuilder<T, ?>> T initialize(T clientBuilder) {
return clientBuilder.credentialsProvider(AnonymousCredentialsProvider.create())
.region(Region.US_WEST_2);
}
}
| 2,593 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/SyncHttpChecksumInTrailerTest.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.services;
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.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.findAll;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor;
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 org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING;
import static software.amazon.awssdk.http.Header.CONTENT_LENGTH;
import static software.amazon.awssdk.http.Header.CONTENT_TYPE;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.core.HttpChecksumConstant;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.ChecksumAlgorithm;
public class SyncHttpChecksumInTrailerTest {
private static final String CRLF = "\r\n";
private static final String SCENARIO = "scenario";
private static final String PATH = "/";
private static final String JSON_BODY = "{\"StringMember\":\"foo\"}";
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private ProtocolRestJsonClient client;
@Before
public void setupClient() {
client = ProtocolRestJsonClient.builder()
.credentialsProvider(AnonymousCredentialsProvider.create())
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
// TODO(sra-identity-and-auth): we should remove these
// overrides once we set up codegen to set chunk-encoding to true
// for requests that are streaming and checksum-enabled
.overrideConfiguration(c -> c.putExecutionAttribute(
ENABLE_CHUNKED_ENCODING, true
))
.build();
}
@Test
public void sync_streaming_NoSigner_appends_trailer_checksum() {
stubResponseWithHeaders();
client.putOperationWithChecksum(r -> r.checksumAlgorithm(ChecksumAlgorithm.CRC32), RequestBody.fromString("Hello world")
, ResponseTransformer.toBytes());
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo("52")));
verify(putRequestedFor(anyUrl()).withHeader(HttpChecksumConstant.HEADER_FOR_TRAILER_REFERENCE, equalTo("x-amz-checksum-crc32")));
verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", equalTo("STREAMING-UNSIGNED-PAYLOAD-TRAILER")));
verify(putRequestedFor(anyUrl()).withHeader("x-amz-decoded-content-length", equalTo("11")));
verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked")));
//b is hex value of 11.
verify(putRequestedFor(anyUrl()).withRequestBody(
containing(
"b" + CRLF + "Hello world" + CRLF
+ "0" + CRLF
+ "x-amz-checksum-crc32:i9aeUg==" + CRLF + CRLF)));
}
@Test
public void sync_streaming_NoSigner_appends_trailer_checksum_withContentEncodingSetByUser() {
stubResponseWithHeaders();
client.putOperationWithChecksum(r ->
r.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.contentEncoding("deflate"),
RequestBody.fromString("Hello world"),
ResponseTransformer.toBytes());
verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked")));
verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("deflate")));
//b is hex value of 11.
verify(putRequestedFor(anyUrl()).withRequestBody(
containing(
"b" + CRLF + "Hello world" + CRLF
+ "0" + CRLF
+ "x-amz-checksum-crc32:i9aeUg==" + CRLF + CRLF)));
}
@Test
public void sync_streaming_specifiedLengthIsLess_NoSigner_appends_trailer_checksum() {
stubResponseWithHeaders();
ContentStreamProvider provider = () -> new ByteArrayInputStream("Hello world".getBytes(StandardCharsets.UTF_8));
// length of 5 truncates to "Hello"
RequestBody requestBody = RequestBody.fromContentProvider(provider, 5, "text/plain");
client.putOperationWithChecksum(r -> r.checksumAlgorithm(ChecksumAlgorithm.CRC32),
requestBody,
ResponseTransformer.toBytes());
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo("46")));
verify(putRequestedFor(anyUrl()).withHeader(HttpChecksumConstant.HEADER_FOR_TRAILER_REFERENCE, equalTo("x-amz-checksum-crc32")));
verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", equalTo("STREAMING-UNSIGNED-PAYLOAD-TRAILER")));
verify(putRequestedFor(anyUrl()).withHeader("x-amz-decoded-content-length", equalTo("5")));
verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked")));
verify(putRequestedFor(anyUrl()).withRequestBody(
containing(
"5" + CRLF + "Hello" + CRLF
+ "0" + CRLF
// 99GJgg== is the base64 encoded CRC32 of "Hello"
+ "x-amz-checksum-crc32:99GJgg==" + CRLF + CRLF)));
}
@Test
public void syncStreaming_withRetry_NoSigner_shouldContainChecksum_fromInterceptors() {
stubForFailureThenSuccess(500, "500");
final String expectedRequestBody =
"3" + CRLF + "abc" + CRLF
+ "0" + CRLF
+ "x-amz-checksum-sha256:ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=" + CRLF + CRLF;
client.putOperationWithChecksum(r -> r.checksumAlgorithm(ChecksumAlgorithm.SHA256), RequestBody.fromString("abc"),
ResponseTransformer.toBytes());
List<LoggedRequest> requests = getRecordedRequests();
assertThat(requests.size()).isEqualTo(2);
assertThat(requests.get(0).getBody()).contains(expectedRequestBody.getBytes());
assertThat(requests.get(1).getBody()).contains(expectedRequestBody.getBytes());
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo("text/plain; charset=UTF-8")));
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo("81")));
verify(putRequestedFor(anyUrl()).withHeader(HttpChecksumConstant.HEADER_FOR_TRAILER_REFERENCE, equalTo("x-amz-checksum-sha256")));
verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", equalTo("STREAMING-UNSIGNED-PAYLOAD-TRAILER")));
verify(putRequestedFor(anyUrl()).withHeader("x-amz-decoded-content-length", equalTo("3")));
verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked")));
verify(putRequestedFor(anyUrl()).withRequestBody(
containing(
expectedRequestBody)));
}
private void stubResponseWithHeaders() {
stubFor(put(anyUrl())
.willReturn(aResponse().withStatus(200)
.withHeader("x-foo-id", "foo")
.withHeader("x-bar-id", "bar")
.withHeader("x-foobar-id", "foobar")
.withBody("{}")));
}
private void stubForFailureThenSuccess(int statusCode, String errorCode) {
WireMock.reset();
stubFor(put(urlEqualTo(PATH))
.inScenario(SCENARIO)
.whenScenarioStateIs(Scenario.STARTED)
.willSetStateTo("1")
.willReturn(aResponse()
.withStatus(statusCode)
.withHeader("x-amzn-ErrorType", errorCode)
.withBody("{}")));
stubFor(put(urlEqualTo(PATH))
.inScenario(SCENARIO)
.whenScenarioStateIs("1")
.willSetStateTo("2")
.willReturn(aResponse()
.withStatus(200)
.withBody(JSON_BODY)));
}
private List<LoggedRequest> getRecordedRequests() {
return findAll(putRequestedFor(urlEqualTo(PATH)));
}
}
| 2,594 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/AsyncRequestBodyFlexibleChecksumInTrailerTest.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.services;
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.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.findAll;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor;
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 org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING;
import static software.amazon.awssdk.http.Header.CONTENT_LENGTH;
import static software.amazon.awssdk.http.Header.CONTENT_TYPE;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.HttpChecksumConstant;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.internal.async.FileAsyncRequestBody;
import software.amazon.awssdk.core.internal.util.Mimetype;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.model.ChecksumAlgorithm;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.utils.BinaryUtils;
public class AsyncRequestBodyFlexibleChecksumInTrailerTest {
public static final int KB = 1024;
private static final String CRLF = "\r\n";
private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper();
private static final String SCENARIO = "scenario";
private static final String PATH = "/";
private static final String JSON_BODY = "{\"StringMember\":\"foo\"}";
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private ProtocolRestJsonAsyncClient asyncClient;
private ProtocolRestJsonAsyncClient asyncClientWithSigner;
public static String createDataOfSize(int dataSize, char contentCharacter) {
return IntStream.range(0, dataSize).mapToObj(i -> String.valueOf(contentCharacter)).collect(Collectors.joining());
}
@Before
public void setupClient() {
asyncClientWithSigner = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.overrideConfiguration(
// TODO(sra-identity-and-auth): we should remove these
// overrides once we set up codegen to set chunk-encoding to true
// for requests that are streaming and checksum-enabled
o -> o.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, true)
.putExecutionAttribute(ENABLE_PAYLOAD_SIGNING, false))
.build();
asyncClient = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(AnonymousCredentialsProvider.create())
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.overrideConfiguration(
// TODO(sra-identity-and-auth): we should remove these
// overrides once we set up codegen to set chunk-encoding to true
// for requests that are streaming and checksum-enabled
o -> o.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, true)
.putExecutionAttribute(ENABLE_PAYLOAD_SIGNING, false))
.build();
}
@After
public void cleanUp() {
ENVIRONMENT_VARIABLE_HELPER.reset();
}
@Test
public void asyncStreaming_NoSigner_shouldContainChecksum_fromInterceptors() {
stubResponseWithHeaders();
asyncClient.putOperationWithChecksum(b -> b.checksumAlgorithm(ChecksumAlgorithm.CRC32), AsyncRequestBody.fromString(
"abc"),
AsyncResponseTransformer.toBytes()).join();
//payload would in json form as "{"StringMember":"foo"}x-amz-checksum-crc32:tcUDMQ==[\r][\n]"
verifyHeadersForPutRequest("44", "3", "x-amz-checksum-crc32");
verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked")));
verify(putRequestedFor(anyUrl()).withRequestBody(
containing(
"3" + CRLF + "abc" + CRLF
+ "0" + CRLF
+ "x-amz-checksum-crc32:NSRBwg==" + CRLF + CRLF)));
}
@Test
public void asyncStreaming_NoSigner_shouldContainChecksum_fromInterceptors_withContentEncoding() {
stubResponseWithHeaders();
asyncClient.putOperationWithChecksum(b -> b.checksumAlgorithm(ChecksumAlgorithm.CRC32).contentEncoding("deflate"),
AsyncRequestBody.fromString(
"abc"),
AsyncResponseTransformer.toBytes()).join();
//payload would in json form as "{"StringMember":"foo"}x-amz-checksum-crc32:tcUDMQ==[\r][\n]"
verifyHeadersForPutRequest("44", "3", "x-amz-checksum-crc32");
verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked")));
verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("deflate")));
verify(putRequestedFor(anyUrl()).withRequestBody(
containing(
"3" + CRLF + "abc" + CRLF
+ "0" + CRLF
+ "x-amz-checksum-crc32:NSRBwg==" + CRLF + CRLF)));
}
@Test
public void asyncStreaming_withRetry_NoSigner_shouldContainChecksum_fromInterceptors() {
stubForFailureThenSuccess(500, "500");
final String expectedRequestBody =
"3" + CRLF + "abc" + CRLF
+ "0" + CRLF
+ "x-amz-checksum-sha256:ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=" + CRLF + CRLF;
asyncClient.putOperationWithChecksum(b -> b.checksumAlgorithm(ChecksumAlgorithm.SHA256), AsyncRequestBody.fromString(
"abc"),
AsyncResponseTransformer.toBytes()).join();
List<LoggedRequest> requests = getRecordedRequests();
assertThat(requests.size()).isEqualTo(2);
assertThat(requests.get(0).getBody()).contains(expectedRequestBody.getBytes());
assertThat(requests.get(1).getBody()).contains(expectedRequestBody.getBytes());
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(Mimetype.MIMETYPE_TEXT_PLAIN + "; charset=UTF-8")));
verifyHeadersForPutRequest("81", "3", "x-amz-checksum-sha256");
verify(putRequestedFor(anyUrl()).withRequestBody(
containing(
expectedRequestBody)));
}
@Test
public void asyncStreaming_FromAsyncRequestBody_VariableChunkSize_NoSigner_addsChecksums_fromInterceptors() throws IOException {
stubForFailureThenSuccess(500, "500");
File randomFileOfFixedLength = new RandomTempFile(37 * KB);
String contentString = new String(Files.readAllBytes(randomFileOfFixedLength.toPath()));
String expectedChecksum = calculatedChecksum(contentString, Algorithm.CRC32);
asyncClient.putOperationWithChecksum(b -> b.checksumAlgorithm(ChecksumAlgorithm.CRC32),
FileAsyncRequestBody.builder().path(randomFileOfFixedLength.toPath())
.chunkSizeInBytes(16 * KB)
.build(),
AsyncResponseTransformer.toBytes()).join();
verifyHeadersForPutRequest("37948", "37888", "x-amz-checksum-crc32");
verify(putRequestedFor(anyUrl()).withRequestBody(
containing(
"4000" + CRLF + contentString.substring(0, 16 * KB) + CRLF
+ "4000" + CRLF + contentString.substring(16 * KB, 32 * KB) + CRLF
+ "1400" + CRLF + contentString.substring(32 * KB) + CRLF
+ "0" + CRLF
+ "x-amz-checksum-crc32:" + expectedChecksum + CRLF + CRLF)));
}
@Test
public void asyncStreaming_withRetry_FromAsyncRequestBody_VariableChunkSize_NoSigner_addsChecksums_fromInterceptors() throws IOException {
File randomFileOfFixedLength = new RandomTempFile(37 * KB);
String contentString = new String(Files.readAllBytes(randomFileOfFixedLength.toPath()));
String expectedChecksum = calculatedChecksum(contentString, Algorithm.CRC32);
stubResponseWithHeaders();
asyncClient.putOperationWithChecksum(b -> b.checksumAlgorithm(ChecksumAlgorithm.CRC32),
FileAsyncRequestBody.builder().path(randomFileOfFixedLength.toPath())
.chunkSizeInBytes(16 * KB)
.build(),
AsyncResponseTransformer.toBytes()).join();
verifyHeadersForPutRequest("37948", "37888", "x-amz-checksum-crc32");
verify(putRequestedFor(anyUrl()).withRequestBody(
containing(
"4000" + CRLF + contentString.substring(0, 16 * KB) + CRLF
+ "4000" + CRLF + contentString.substring(16 * KB, 32 * KB) + CRLF
+ "1400" + CRLF + contentString.substring(32 * KB) + CRLF
+ "0" + CRLF
+ "x-amz-checksum-crc32:" + expectedChecksum + CRLF + CRLF)));
}
private String calculatedChecksum(String contentString, Algorithm algorithm) {
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm);
for (byte character : contentString.getBytes(StandardCharsets.UTF_8)) {
sdkChecksum.update(character);
}
return BinaryUtils.toBase64(sdkChecksum.getChecksumBytes());
}
private void stubResponseWithHeaders() {
stubFor(put(anyUrl())
.willReturn(aResponse().withStatus(200)
.withHeader("x-foo-id", "foo")
.withHeader("x-bar-id", "bar")
.withHeader("x-foobar-id", "foobar")
.withBody("{}")));
}
private void stubForFailureThenSuccess(int statusCode, String errorCode) {
WireMock.reset();
stubFor(put(urlEqualTo(PATH))
.inScenario(SCENARIO)
.whenScenarioStateIs(Scenario.STARTED)
.willSetStateTo("1")
.willReturn(aResponse()
.withStatus(statusCode)
.withHeader("x-amzn-ErrorType", errorCode)
.withBody("{}")));
stubFor(put(urlEqualTo(PATH))
.inScenario(SCENARIO)
.whenScenarioStateIs("1")
.willSetStateTo("2")
.willReturn(aResponse()
.withStatus(200)
.withBody(JSON_BODY)));
}
private List<LoggedRequest> getRecordedRequests() {
return findAll(putRequestedFor(urlEqualTo(PATH)));
}
private void verifyHeadersForPutRequest(String contentLength, String decodedContentLength, String checksumHeader) {
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo(contentLength)));
verify(putRequestedFor(anyUrl()).withHeader(HttpChecksumConstant.HEADER_FOR_TRAILER_REFERENCE, equalTo(
checksumHeader)));
verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", equalTo("STREAMING-UNSIGNED-PAYLOAD-TRAILER")));
verify(putRequestedFor(anyUrl()).withHeader("x-amz-decoded-content-length", equalTo(decodedContentLength)));
verify(putRequestedFor(anyUrl()).withHeader("content-encoding", equalTo("aws-chunked")));
verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked")));
}
}
| 2,595 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/HttpChecksumRequiredTest.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.services;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import io.reactivex.Flowable;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.awscore.client.builder.AwsAsyncClientBuilder;
import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder;
import software.amazon.awssdk.awscore.client.builder.AwsSyncClientBuilder;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullResponse;
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.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.ChecksumAlgorithm;
import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient;
import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient;
/**
* Verify that the "httpChecksumRequired" C2J trait results in a valid MD5 checksum of the payload being included in the HTTP
* request.
*/
public class HttpChecksumRequiredTest {
private SdkHttpClient httpClient;
private SdkAsyncHttpClient httpAsyncClient;
private ProtocolRestJsonClient jsonClient;
private ProtocolRestJsonAsyncClient jsonAsyncClient;
private ProtocolRestXmlClient xmlClient;
private ProtocolRestXmlAsyncClient xmlAsyncClient;
@Before
public void setup() throws IOException {
httpClient = Mockito.mock(SdkHttpClient.class);
httpAsyncClient = Mockito.mock(SdkAsyncHttpClient.class);
jsonClient = initializeSync(ProtocolRestJsonClient.builder()).build();
jsonAsyncClient = initializeAsync(ProtocolRestJsonAsyncClient.builder()).build();
xmlClient = initializeSync(ProtocolRestXmlClient.builder()).build();
xmlAsyncClient = initializeAsync(ProtocolRestXmlAsyncClient.builder()).build();
SdkHttpFullResponse successfulHttpResponse = SdkHttpResponse.builder()
.statusCode(200)
.putHeader("Content-Length", "0")
.build();
ExecutableHttpRequest request = Mockito.mock(ExecutableHttpRequest.class);
Mockito.when(request.call()).thenReturn(HttpExecuteResponse.builder()
.response(successfulHttpResponse)
.build());
Mockito.when(httpClient.prepareRequest(any())).thenReturn(request);
Mockito.when(httpAsyncClient.execute(any())).thenAnswer(invocation -> {
AsyncExecuteRequest asyncExecuteRequest = invocation.getArgument(0, AsyncExecuteRequest.class);
asyncExecuteRequest.responseHandler().onHeaders(successfulHttpResponse);
asyncExecuteRequest.responseHandler().onStream(Flowable.empty());
return CompletableFuture.completedFuture(null);
});
}
private <T extends AwsSyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeSync(T syncClientBuilder) {
return initialize(syncClientBuilder.httpClient(httpClient));
}
private <T extends AwsAsyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeAsync(T asyncClientBuilder) {
return initialize(asyncClientBuilder.httpClient(httpAsyncClient));
}
private <T extends AwsClientBuilder<T, ?>> T initialize(T clientBuilder) {
return clientBuilder.credentialsProvider(AnonymousCredentialsProvider.create())
.region(Region.US_WEST_2);
}
@Test
public void syncJsonSupportsChecksumRequiredTrait() {
jsonClient.operationWithRequiredChecksum(r -> r.stringMember("foo"));
assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).hasValue("g8VCvPTPCMoU01rBlBVt9w==");
}
@Test
public void syncStreamingInputJsonSupportsChecksumRequiredTrait() {
jsonClient.streamingInputOperationWithRequiredChecksum(r -> {}, RequestBody.fromString("foo"));
assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).hasValue("rL0Y20zC+Fzt72VPzMSk2A==");
}
@Test
public void syncStreamingInputXmlSupportsChecksumRequiredTrait() {
xmlClient.streamingInputOperationWithRequiredChecksum(r -> {}, RequestBody.fromString("foo"));
assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).hasValue("rL0Y20zC+Fzt72VPzMSk2A==");
}
@Test
public void syncXmlSupportsChecksumRequiredTrait() {
xmlClient.operationWithRequiredChecksum(r -> r.stringMember("foo"));
assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).hasValue("vqm481l+Lv0zEvdu+duE6Q==");
}
@Test
public void asyncJsonSupportsChecksumRequiredTrait() {
jsonAsyncClient.operationWithRequiredChecksum(r -> r.stringMember("foo")).join();
assertThat(getAsyncRequest().firstMatchingHeader("Content-MD5")).hasValue("g8VCvPTPCMoU01rBlBVt9w==");
}
@Test
public void asyncXmlSupportsChecksumRequiredTrait() {
xmlAsyncClient.operationWithRequiredChecksum(r -> r.stringMember("foo")).join();
assertThat(getAsyncRequest().firstMatchingHeader("Content-MD5")).hasValue("vqm481l+Lv0zEvdu+duE6Q==");
}
@Test(expected = CompletionException.class)
public void asyncStreamingInputJsonFailsWithChecksumRequiredTrait() {
jsonAsyncClient.streamingInputOperationWithRequiredChecksum(r -> {}, AsyncRequestBody.fromString("foo")).join();
}
@Test(expected = CompletionException.class)
public void asyncStreamingInputXmlFailsWithChecksumRequiredTrait() {
xmlAsyncClient.streamingInputOperationWithRequiredChecksum(r -> {}, AsyncRequestBody.fromString("foo")).join();
}
@Test
public void syncJsonSupportsOperationWithRequestChecksumRequired() {
jsonClient.operationWithRequestChecksumRequired(r -> r.stringMember("foo"));
assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).hasValue("g8VCvPTPCMoU01rBlBVt9w==");
}
@Test
public void syncJsonSupportsOperationWithCustomRequestChecksum() {
jsonClient.operationWithCustomRequestChecksum(r -> r.stringMember("foo").checksumAlgorithm(ChecksumAlgorithm.CRC32));
assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent();
assertThat(getSyncRequest().firstMatchingHeader("x-amz-checksum-crc32")).hasValue("rzlTOg==");
}
private SdkHttpRequest getSyncRequest() {
ArgumentCaptor<HttpExecuteRequest> captor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
Mockito.verify(httpClient).prepareRequest(captor.capture());
return captor.getValue().httpRequest();
}
private SdkHttpRequest getAsyncRequest() {
ArgumentCaptor<AsyncExecuteRequest> captor = ArgumentCaptor.forClass(AsyncExecuteRequest.class);
Mockito.verify(httpAsyncClient).execute(captor.capture());
return captor.getValue().request();
}
}
| 2,596 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/AsyncRequestCompressionTest.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.services;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.Flowable;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Optional;
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.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.internal.compression.Compressor;
import software.amazon.awssdk.core.internal.compression.GzipCompressor;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.model.PutOperationWithRequestCompressionRequest;
import software.amazon.awssdk.services.protocolrestjson.model.PutOperationWithStreamingRequestCompressionRequest;
import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient;
public class AsyncRequestCompressionTest {
private static final String UNCOMPRESSED_BODY =
"RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest";
private String compressedBody;
private int compressedLen;
private MockAsyncHttpClient mockAsyncHttpClient;
private ProtocolRestJsonAsyncClient asyncClient;
private Compressor compressor;
@BeforeEach
public void setUp() {
mockAsyncHttpClient = new MockAsyncHttpClient();
asyncClient = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(AnonymousCredentialsProvider.create())
.region(Region.US_EAST_1)
.httpClient(mockAsyncHttpClient)
.build();
compressor = new GzipCompressor();
byte[] compressedBodyBytes = compressor.compress(UNCOMPRESSED_BODY.getBytes());
compressedBody = new String(compressedBodyBytes);
compressedLen = compressedBodyBytes.length;
}
@AfterEach
public void reset() {
mockAsyncHttpClient.reset();
}
@Test
public void asyncNonStreamingOperation_compressionEnabledThresholdOverridden_compressesCorrectly() {
mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500));
PutOperationWithRequestCompressionRequest request =
PutOperationWithRequestCompressionRequest.builder()
.body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY))
.overrideConfiguration(o -> o.compressionConfiguration(
c -> c.minimumCompressionThresholdInBytes(1)))
.build();
asyncClient.putOperationWithRequestCompression(request);
SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockAsyncHttpClient.getLastRequest();
InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream();
String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray());
int loggedSize = Integer.valueOf(loggedRequest.firstMatchingHeader("Content-Length").get());
assertThat(loggedBody).isEqualTo(compressedBody);
assertThat(loggedSize).isEqualTo(compressedLen);
assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip");
}
@Test
public void asyncNonStreamingOperation_payloadSizeLessThanCompressionThreshold_doesNotCompress() {
mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500));
PutOperationWithRequestCompressionRequest request =
PutOperationWithRequestCompressionRequest.builder()
.body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY))
.build();
asyncClient.putOperationWithRequestCompression(request);
SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockAsyncHttpClient.getLastRequest();
InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream();
String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray());
int loggedSize = Integer.valueOf(loggedRequest.firstMatchingHeader("Content-Length").get());
assertThat(loggedBody).isEqualTo(UNCOMPRESSED_BODY);
assertThat(loggedSize).isEqualTo(UNCOMPRESSED_BODY.length());
assertThat(loggedRequest.firstMatchingHeader("Content-encoding")).isEmpty();
}
@Test
public void asyncStreamingOperation_compressionEnabled_compressesCorrectly() {
mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500));
mockAsyncHttpClient.setAsyncRequestBodyLength(compressedBody.length());
PutOperationWithStreamingRequestCompressionRequest request =
PutOperationWithStreamingRequestCompressionRequest.builder().build();
asyncClient.putOperationWithStreamingRequestCompression(request, customAsyncRequestBodyWithoutContentLength(),
AsyncResponseTransformer.toBytes()).join();
SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockAsyncHttpClient.getLastRequest();
String loggedBody = new String(mockAsyncHttpClient.getStreamingPayload().get());
assertThat(loggedBody).isEqualTo(compressedBody);
assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip");
assertThat(loggedRequest.matchingHeaders("Content-Length")).isEmpty();
assertThat(loggedRequest.firstMatchingHeader("Transfer-Encoding").get()).isEqualTo("chunked");
}
@Test
public void asyncNonStreamingOperation_compressionEnabledThresholdOverriddenWithRetry_compressesCorrectly() {
mockAsyncHttpClient.stubNextResponse(mockErrorResponse(), Duration.ofMillis(500));
mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500));
PutOperationWithRequestCompressionRequest request =
PutOperationWithRequestCompressionRequest.builder()
.body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY))
.overrideConfiguration(o -> o.compressionConfiguration(
c -> c.minimumCompressionThresholdInBytes(1)))
.build();
asyncClient.putOperationWithRequestCompression(request);
SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockAsyncHttpClient.getLastRequest();
InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream();
String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray());
int loggedSize = Integer.valueOf(loggedRequest.firstMatchingHeader("Content-Length").get());
assertThat(loggedBody).isEqualTo(compressedBody);
assertThat(loggedSize).isEqualTo(compressedLen);
assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip");
}
@Test
public void asyncStreamingOperation_compressionEnabledWithRetry_compressesCorrectly() {
mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500));
mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500));
mockAsyncHttpClient.setAsyncRequestBodyLength(compressedBody.length());
PutOperationWithStreamingRequestCompressionRequest request =
PutOperationWithStreamingRequestCompressionRequest.builder().build();
asyncClient.putOperationWithStreamingRequestCompression(request, customAsyncRequestBodyWithoutContentLength(),
AsyncResponseTransformer.toBytes()).join();
SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockAsyncHttpClient.getLastRequest();
String loggedBody = new String(mockAsyncHttpClient.getStreamingPayload().get());
assertThat(loggedBody).isEqualTo(compressedBody);
assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip");
assertThat(loggedRequest.matchingHeaders("Content-Length")).isEmpty();
assertThat(loggedRequest.firstMatchingHeader("Transfer-Encoding").get()).isEqualTo("chunked");
}
private HttpExecuteResponse mockResponse() {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder().statusCode(200).build())
.build();
}
private HttpExecuteResponse mockErrorResponse() {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder().statusCode(500).build())
.build();
}
protected AsyncRequestBody customAsyncRequestBodyWithoutContentLength() {
return new AsyncRequestBody() {
@Override
public Optional<Long> contentLength() {
return Optional.empty();
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
Flowable.fromPublisher(AsyncRequestBody.fromBytes(UNCOMPRESSED_BODY.getBytes()))
.subscribe(s);
}
};
}
}
| 2,597 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/SdkPluginTest.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.services;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static software.amazon.awssdk.profiles.ProfileFile.Type.CONFIGURATION;
import java.lang.reflect.Field;
import java.net.URI;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.core.CompressionConfiguration;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkPlugin;
import software.amazon.awssdk.core.client.builder.SdkClientBuilder;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.endpoints.Endpoint;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme;
import software.amazon.awssdk.http.auth.scheme.NoAuthAuthScheme;
import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme;
import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption;
import software.amazon.awssdk.http.auth.spi.signer.HttpSigner;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.IdentityProviders;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonServiceClientConfiguration;
import software.amazon.awssdk.services.protocolrestjson.auth.scheme.ProtocolRestJsonAuthSchemeProvider;
import software.amazon.awssdk.services.protocolrestjson.endpoints.ProtocolRestJsonEndpointProvider;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
import software.amazon.awssdk.utils.ImmutableMap;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.StringInputStream;
/**
* Verify that configuration changes made by plugins are reflected in the SDK client configuration used by the request, and
* that the plugin can see all SDK configuration options.
*/
public class SdkPluginTest {
private static final AwsCredentialsProvider DEFAULT_CREDENTIALS = () -> AwsBasicCredentials.create("akid", "skid");
public static Stream<TestCase<?>> testCases() {
Map<String, AuthScheme<?>> defaultAuthSchemes =
ImmutableMap.of(AwsV4AuthScheme.SCHEME_ID, AwsV4AuthScheme.create(),
NoAuthAuthScheme.SCHEME_ID, NoAuthAuthScheme.create());
Map<String, AuthScheme<?>> nonDefaultAuthSchemes = new HashMap<>(defaultAuthSchemes);
nonDefaultAuthSchemes.put(CustomAuthScheme.SCHEME_ID, new CustomAuthScheme());
ScheduledExecutorService mockScheduledExecutor = mock(ScheduledExecutorService.class);
MetricPublisher mockMetricPublisher = mock(MetricPublisher.class);
String profileFileContent =
"[default]\n"
+ ProfileProperty.USE_FIPS_ENDPOINT + " = true"
+ "[profile some-profile]\n"
+ ProfileProperty.USE_FIPS_ENDPOINT + " = false";
ProfileFile nonDefaultProfileFile =
ProfileFile.builder()
.type(CONFIGURATION)
.content(new StringInputStream(profileFileContent))
.build();
return Stream.of(
new TestCase<URI>("endpointOverride")
.nonDefaultValue(URI.create("https://example.aws"))
.clientSetter(SdkClientBuilder::endpointOverride)
.pluginSetter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointOverride)
.pluginValidator((c, v) -> assertThat(v).isEqualTo(c.endpointOverride()))
.beforeTransmissionValidator((r, a, v) -> {
assertThat(v).isEqualTo(removePathAndQueryString(r.httpRequest().getUri()));
}),
new TestCase<ProtocolRestJsonEndpointProvider>("endpointProvider")
.defaultValue(ProtocolRestJsonEndpointProvider.defaultProvider())
.nonDefaultValue(a -> CompletableFuture.completedFuture(Endpoint.builder()
.url(URI.create("https://example.aws"))
.build()))
.clientSetter(ProtocolRestJsonClientBuilder::endpointProvider)
.requestSetter(RequestOverrideConfiguration.Builder::endpointProvider)
.pluginSetter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointProvider)
.pluginValidator((c, v) -> assertThat(c.endpointProvider()).isEqualTo(v))
.beforeTransmissionValidator((r, a, v) -> {
assertThat(removePathAndQueryString(r.httpRequest().getUri()))
.isEqualTo(v.resolveEndpoint(x -> {}).join().url());
}),
new TestCase<Map<String, AuthScheme<?>>>("authSchemes")
.defaultValue(defaultAuthSchemes)
.nonDefaultValue(nonDefaultAuthSchemes)
.clientSetter((b, v) -> v.forEach((x, scheme) -> b.putAuthScheme(scheme)))
.pluginSetter((b, v) -> v.forEach((x, scheme) -> b.putAuthScheme(scheme)))
.pluginValidator((c, v) -> v.forEach((id, s) -> assertThat(c.authSchemes()).containsEntry(id, s)))
.beforeTransmissionValidator((r, a, v) -> v.forEach((id, s) -> {
assertThat(a.getAttribute(SdkInternalExecutionAttribute.AUTH_SCHEMES)).containsEntry(id, s);
})),
new TestCase<Region>("region")
.defaultValue(Region.US_WEST_2)
.nonDefaultValue(Region.US_EAST_1)
.clientSetter(AwsClientBuilder::region)
.pluginSetter(ProtocolRestJsonServiceClientConfiguration.Builder::region)
.pluginValidator((c, v) -> assertThat(c.region()).isEqualTo(v))
.beforeTransmissionValidator((r, a, v) -> {
assertThat(r.httpRequest()
.firstMatchingHeader("Authorization")).get()
.asString()
.contains(v.id());
assertThat(r.httpRequest().getUri().getHost()).contains(v.id());
}),
new TestCase<AwsCredentialsProvider>("credentialsProvider")
.defaultValue(DEFAULT_CREDENTIALS)
.nonDefaultValue(DEFAULT_CREDENTIALS::resolveCredentials)
.clientSetter(AwsClientBuilder::credentialsProvider)
.requestSetter(AwsRequestOverrideConfiguration.Builder::credentialsProvider)
.pluginSetter(ProtocolRestJsonServiceClientConfiguration.Builder::credentialsProvider)
.pluginValidator((c, v) -> assertThat(c.credentialsProvider()).isEqualTo(v))
.beforeTransmissionValidator((r, a, v) -> {
assertThat(r.httpRequest()
.firstMatchingHeader("Authorization")).get()
.asString()
.contains(v.resolveCredentials().accessKeyId());
}),
new TestCase<ProtocolRestJsonAuthSchemeProvider>("authSchemeProvider")
.defaultValue(ProtocolRestJsonAuthSchemeProvider.defaultProvider())
.nonDefaultValue(p -> singletonList(AuthSchemeOption.builder().schemeId(NoAuthAuthScheme.SCHEME_ID).build()))
.clientSetter(ProtocolRestJsonClientBuilder::authSchemeProvider)
.pluginSetter(ProtocolRestJsonServiceClientConfiguration.Builder::authSchemeProvider)
.pluginValidator((c, v) -> assertThat(c.authSchemeProvider()).isEqualTo(v))
.beforeTransmissionValidator((r, a, v) -> {
assertThat(a.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.authSchemeOption()
.schemeId()).isEqualTo(NoAuthAuthScheme.SCHEME_ID);
assertThat(r.httpRequest().firstMatchingHeader("Authorization")).isNotPresent();
}),
new TestCase<Map<String, List<String>>>("override.headers")
.defaultValue(emptyMap())
.nonDefaultValue(singletonMap("foo", singletonList("bar")))
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.headers(v)))
.requestSetter(AwsRequestOverrideConfiguration.Builder::headers)
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.headers(v))))
.pluginValidator((c, v) -> assertThat(c.overrideConfiguration().headers()).isEqualTo(v))
.beforeTransmissionValidator((r, a, v) -> {
v.forEach((key, value) -> assertThat(r.httpRequest().headers().get(key)).isEqualTo(value));
}),
new TestCase<RetryPolicy>("override.retryPolicy")
.defaultValue(RetryPolicy.defaultRetryPolicy())
.nonDefaultValue(RetryPolicy.builder(RetryMode.STANDARD).numRetries(1).build())
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.retryPolicy(v)))
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.retryPolicy(v))))
.pluginValidator((c, v) -> assertThat(c.overrideConfiguration().retryPolicy().get().numRetries())
.isEqualTo(v.numRetries()))
.beforeTransmissionValidator((r, a, v) -> {
assertThat(r.httpRequest().firstMatchingHeader("amz-sdk-request"))
.hasValue("attempt=1; max=" + (v.numRetries() + 1));
}),
new TestCase<List<ExecutionInterceptor>>("override.executionInterceptors")
.defaultValue(emptyList())
.nonDefaultValue(singletonList(new FlagSettingInterceptor()))
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.executionInterceptors(v)))
.pluginSetter((b, v) -> {
b.overrideConfiguration(b.overrideConfiguration().copy(c -> v.forEach(c::addExecutionInterceptor)));
})
.pluginValidator((c, v) -> assertThat(c.overrideConfiguration().executionInterceptors()).containsAll(v))
.beforeTransmissionValidator((r, a, v) -> {
if (v.stream().anyMatch(i -> i instanceof FlagSettingInterceptor)) {
assertThat(a.getAttribute(FlagSettingInterceptor.FLAG)).isEqualTo(true);
} else {
assertThat(a.getAttribute(FlagSettingInterceptor.FLAG)).isNull();
}
}),
new TestCase<ScheduledExecutorService>("override.scheduledExecutorService")
.defaultValue(null)
.nonDefaultValue(mockScheduledExecutor)
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.scheduledExecutorService(v)))
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.scheduledExecutorService(v))))
.pluginValidator((c, v) -> {
Optional<ScheduledExecutorService> executor = c.overrideConfiguration().scheduledExecutorService();
if (v != null) {
// The SDK should decorate the non-default-value. Ensure that's what happened.
Runnable runnable = () -> {};
v.submit(runnable);
assertThat(v).isEqualTo(mockScheduledExecutor);
Mockito.verify(v, times(1)).submit(eq(runnable));
} else {
// Null means we're using the default, and the default should be specified by the runtime.
assertThat(executor).isPresent();
}
})
.clientConfigurationValidator((c, v) -> {
ScheduledExecutorService configuredService = c.option(SdkClientOption.SCHEDULED_EXECUTOR_SERVICE);
if (mockScheduledExecutor.equals(v)) {
// The SDK should decorate the non-default-value. Ensure that's what happened.
Runnable runnable = () -> {};
configuredService.submit(runnable);
assertThat(v).isEqualTo(mockScheduledExecutor);
Mockito.verify(v, times(1)).submit(eq(runnable));
} else {
assertThat(configuredService).isNotNull();
}
}),
new TestCase<Map<SdkAdvancedClientOption<?>, ?>>("override.advancedOptions")
.defaultValue(emptyMap())
.nonDefaultValue(singletonMap(SdkAdvancedClientOption.USER_AGENT_PREFIX, "foo"))
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.advancedOptions(v)))
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> {
v.forEach((option, value) -> unsafePutOption(c, option, value));
})))
.pluginValidator((c, v) -> {
v.forEach((o, ov) -> assertThat(c.overrideConfiguration().advancedOption(o).orElse(null)).isEqualTo(ov));
})
.clientConfigurationValidator((c, v) -> v.forEach((o, ov) -> assertThat(c.option(o)).isEqualTo(ov))),
new TestCase<Duration>("override.apiCallTimeout")
.defaultValue(null)
.nonDefaultValue(Duration.ofSeconds(5))
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.apiCallTimeout(v)))
.requestSetter(AwsRequestOverrideConfiguration.Builder::apiCallTimeout)
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.apiCallTimeout(v))))
.pluginValidator((c, v) -> assertThat(c.overrideConfiguration().apiCallTimeout().orElse(null)).isEqualTo(v))
.clientConfigurationValidator((c, v) -> assertThat(c.option(SdkClientOption.API_CALL_TIMEOUT)).isEqualTo(v)),
new TestCase<Duration>("override.apiCallAttemptTimeout")
.defaultValue(null)
.nonDefaultValue(Duration.ofSeconds(3))
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.apiCallAttemptTimeout(v)))
.requestSetter(AwsRequestOverrideConfiguration.Builder::apiCallAttemptTimeout)
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.apiCallAttemptTimeout(v))))
.pluginValidator((c, v) -> assertThat(c.overrideConfiguration().apiCallAttemptTimeout().orElse(null)).isEqualTo(v))
.clientConfigurationValidator((c, v) -> assertThat(c.option(SdkClientOption.API_CALL_ATTEMPT_TIMEOUT)).isEqualTo(v)),
new TestCase<Supplier<ProfileFile>>("override.defaultProfileFileSupplier")
.defaultValue(new Lazy<>(ProfileFile::defaultProfileFile)::getValue)
.nonDefaultValue(() -> nonDefaultProfileFile)
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.defaultProfileFileSupplier(v)))
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.defaultProfileFileSupplier(v))))
.pluginValidator((c, v) -> assertThat(c.overrideConfiguration().defaultProfileFileSupplier().get().get()).isEqualTo(v.get()))
.clientConfigurationValidator((c, v) -> {
Supplier<ProfileFile> supplier = c.option(SdkClientOption.PROFILE_FILE_SUPPLIER);
assertThat(supplier.get()).isEqualTo(v.get());
Optional<Profile> defaultProfile = v.get().profile("default");
defaultProfile.ifPresent(profile -> {
profile.booleanProperty(ProfileProperty.USE_FIPS_ENDPOINT).ifPresent(d -> {
assertThat(c.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isEqualTo(d);
});
});
if (!defaultProfile.isPresent()) {
assertThat(c.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isIn(null, false);
}
}),
new TestCase<ProfileFile>("override.defaultProfileFile")
.defaultValue(ProfileFile.defaultProfileFile())
.nonDefaultValue(nonDefaultProfileFile)
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.defaultProfileFile(v)))
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.defaultProfileFile(v))))
.pluginValidator((c, v) -> assertThat(c.overrideConfiguration().defaultProfileFile()).hasValue(v))
.clientConfigurationValidator((c, v) -> assertThat(c.option(SdkClientOption.PROFILE_FILE)).isEqualTo(v)),
new TestCase<String>("override.defaultProfileName")
.defaultValue("default")
.nonDefaultValue("some-profile")
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.defaultProfileName(v)
.defaultProfileFile(nonDefaultProfileFile)))
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.defaultProfileName(v)
.defaultProfileFile(nonDefaultProfileFile))))
.pluginValidator((c, v) -> assertThat(c.overrideConfiguration().defaultProfileName().orElse(null)).isEqualTo(v))
.clientConfigurationValidator((c, v) -> {
assertThat(c.option(SdkClientOption.PROFILE_NAME)).isEqualTo(v);
ProfileFile profileFile = c.option(SdkClientOption.PROFILE_FILE_SUPPLIER).get();
Optional<Profile> configuredProfile = profileFile.profile(v);
configuredProfile.ifPresent(profile -> {
profile.booleanProperty(ProfileProperty.USE_FIPS_ENDPOINT).ifPresent(d -> {
assertThat(c.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isEqualTo(d);
});
});
if (!configuredProfile.isPresent()) {
assertThat(c.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isIn(null, false);
}
}),
new TestCase<List<MetricPublisher>>("override.metricPublishers")
.defaultValue(emptyList())
.nonDefaultValue(singletonList(mockMetricPublisher))
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.metricPublishers(v)))
.requestSetter(AwsRequestOverrideConfiguration.Builder::metricPublishers)
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.metricPublishers(v))))
.pluginValidator((c, v) -> assertThat(c.overrideConfiguration().metricPublishers()).isEqualTo(v))
.clientConfigurationValidator((c, v) -> {
assertThat(c.option(SdkClientOption.METRIC_PUBLISHERS)).containsAll(v);
}),
new TestCase<ExecutionAttributes>("override.executionAttributes")
.defaultValue(new ExecutionAttributes())
.nonDefaultValue(new ExecutionAttributes().putAttribute(FlagSettingInterceptor.FLAG, true))
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.executionAttributes(v)))
.requestSetter(AwsRequestOverrideConfiguration.Builder::executionAttributes)
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.executionAttributes(v))))
.pluginValidator((c, v) -> assertThat(c.overrideConfiguration().executionAttributes()).isEqualTo(v))
.beforeTransmissionValidator((r, a, v) -> {
assertThat(a.getAttribute(FlagSettingInterceptor.FLAG)).isTrue();
}),
new TestCase<CompressionConfiguration>("override.compressionConfiguration")
.defaultValue(CompressionConfiguration.builder()
.requestCompressionEnabled(true)
.minimumCompressionThresholdInBytes(10_240)
.build())
.nonDefaultValue(CompressionConfiguration.builder()
.requestCompressionEnabled(true)
.minimumCompressionThresholdInBytes(1)
.build())
.clientSetter((b, v) -> b.overrideConfiguration(c -> c.compressionConfiguration(v)))
.requestSetter(AwsRequestOverrideConfiguration.Builder::compressionConfiguration)
.pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.compressionConfiguration(v))))
.pluginValidator((c, v) -> assertThat(c.overrideConfiguration().compressionConfiguration().orElse(null)).isEqualTo(v))
.clientConfigurationValidator((c, v) -> assertThat(c.option(SdkClientOption.COMPRESSION_CONFIGURATION)).isEqualTo(v))
);
}
private static <T> void unsafePutOption(ClientOverrideConfiguration.Builder config,
SdkAdvancedClientOption<T> option,
Object value) {
config.putAdvancedOption(option, option.convertValue(value));
}
@ParameterizedTest
@MethodSource("testCases")
public <T> void validateTestCaseData(TestCase<T> testCase) {
assertThat(testCase.defaultValue).isNotEqualTo(testCase.nonDefaultValue);
}
@ParameterizedTest
@MethodSource("testCases")
public <T> void clientPluginSeesDefaultValue(TestCase<T> testCase) {
ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder();
AtomicInteger timesCalled = new AtomicInteger(0);
SdkPlugin plugin = config -> {
ProtocolRestJsonServiceClientConfiguration.Builder conf =
(ProtocolRestJsonServiceClientConfiguration.Builder) config;
testCase.pluginValidator.accept(conf, testCase.defaultValue);
timesCalled.incrementAndGet();
};
ProtocolRestJsonClient client = clientBuilder.addPlugin(plugin).build();
if (testCase.clientConfigurationValidator != null) {
testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.defaultValue);
}
assertThat(timesCalled).hasValue(1);
}
@ParameterizedTest
@MethodSource("testCases")
public <T> void requestPluginSeesDefaultValue(TestCase<T> testCase) {
ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder();
AtomicInteger timesCalled = new AtomicInteger(0);
SdkPlugin plugin = config -> {
ProtocolRestJsonServiceClientConfiguration.Builder conf =
(ProtocolRestJsonServiceClientConfiguration.Builder) config;
testCase.pluginValidator.accept(conf, testCase.defaultValue);
timesCalled.incrementAndGet();
};
ProtocolRestJsonClient client = clientBuilder.httpClient(succeedingHttpClient()).build();
if (testCase.clientConfigurationValidator != null) {
testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.defaultValue);
}
client.allTypes(r -> r.overrideConfiguration(c -> c.addPlugin(plugin)));
assertThat(timesCalled).hasValue(1);
}
@ParameterizedTest
@MethodSource("testCases")
public <T> void clientPluginSeesCustomerClientConfiguredValue(TestCase<T> testCase) {
ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder();
testCase.clientSetter.accept(clientBuilder, testCase.nonDefaultValue);
AtomicInteger timesCalled = new AtomicInteger(0);
SdkPlugin plugin = config -> {
ProtocolRestJsonServiceClientConfiguration.Builder conf =
(ProtocolRestJsonServiceClientConfiguration.Builder) config;
testCase.pluginValidator.accept(conf, testCase.nonDefaultValue);
timesCalled.incrementAndGet();
};
ProtocolRestJsonClient client = clientBuilder.addPlugin(plugin).build();
if (testCase.clientConfigurationValidator != null) {
testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.nonDefaultValue);
}
assertThat(timesCalled).hasValue(1);
}
@ParameterizedTest
@MethodSource("testCases")
public <T> void requestPluginSeesCustomerClientConfiguredValue(TestCase<T> testCase) {
ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder();
testCase.clientSetter.accept(clientBuilder, testCase.nonDefaultValue);
AtomicInteger timesCalled = new AtomicInteger(0);
SdkPlugin plugin = config -> {
ProtocolRestJsonServiceClientConfiguration.Builder conf =
(ProtocolRestJsonServiceClientConfiguration.Builder) config;
testCase.pluginValidator.accept(conf, testCase.nonDefaultValue);
timesCalled.incrementAndGet();
};
ProtocolRestJsonClient client = clientBuilder.httpClient(succeedingHttpClient()).build();
if (testCase.clientConfigurationValidator != null) {
testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.nonDefaultValue);
}
client.allTypes(r -> r.overrideConfiguration(c -> c.addPlugin(plugin)));
assertThat(timesCalled).hasValue(1);
}
@ParameterizedTest
@MethodSource("testCases")
@Disabled("Request-level values are currently higher-priority than plugin settings.") // TODO(sra-identity-auth)
public <T> void requestPluginSeesCustomerRequestConfiguredValue(TestCase<T> testCase) {
if (testCase.requestSetter == null) {
System.out.println("No request setting available.");
return;
}
ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder();
AtomicInteger timesCalled = new AtomicInteger(0);
SdkPlugin plugin = config -> {
ProtocolRestJsonServiceClientConfiguration.Builder conf =
(ProtocolRestJsonServiceClientConfiguration.Builder) config;
testCase.pluginValidator.accept(conf, testCase.nonDefaultValue);
timesCalled.incrementAndGet();
};
AwsRequestOverrideConfiguration overrideConfig =
AwsRequestOverrideConfiguration.builder()
.addPlugin(plugin)
.applyMutation(c -> testCase.requestSetter.accept(c, testCase.nonDefaultValue))
.build();
ProtocolRestJsonClient client = clientBuilder.httpClient(succeedingHttpClient()).build();
if (testCase.clientConfigurationValidator != null) {
testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.defaultValue);
}
client.allTypes(r -> r.overrideConfiguration(overrideConfig));
assertThat(timesCalled).hasValue(1);
}
@ParameterizedTest
@MethodSource("testCases")
public <T> void clientPluginSetValueIsUsed(TestCase<T> testCase) {
ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder();
testCase.clientSetter.accept(clientBuilder, testCase.defaultValue);
AtomicInteger timesPluginCalled = new AtomicInteger(0);
SdkPlugin plugin = config -> {
timesPluginCalled.incrementAndGet();
ProtocolRestJsonServiceClientConfiguration.Builder conf =
(ProtocolRestJsonServiceClientConfiguration.Builder) config;
testCase.pluginSetter.accept(conf, testCase.nonDefaultValue);
};
AtomicInteger timesInterceptorCalled = new AtomicInteger(0);
ExecutionInterceptor validatingInterceptor = new ExecutionInterceptor() {
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
timesInterceptorCalled.getAndIncrement();
if (testCase.beforeTransmissionValidator != null) {
testCase.beforeTransmissionValidator.accept(context, executionAttributes, testCase.nonDefaultValue);
}
}
};
ProtocolRestJsonClient client =
clientBuilder.httpClient(succeedingHttpClient())
.addPlugin(plugin)
.overrideConfiguration(c -> c.addExecutionInterceptor(validatingInterceptor))
.build();
if (testCase.clientConfigurationValidator != null) {
testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.nonDefaultValue);
}
client.allTypes();
assertThat(timesPluginCalled).hasValue(1);
assertThat(timesInterceptorCalled).hasValueGreaterThanOrEqualTo(1);
}
@ParameterizedTest
@MethodSource("testCases")
public <T> void requestPluginSetValueIsUsed(TestCase<T> testCase) {
ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder();
testCase.clientSetter.accept(clientBuilder, testCase.defaultValue);
AtomicInteger timesPluginCalled = new AtomicInteger(0);
SdkPlugin plugin = config -> {
timesPluginCalled.incrementAndGet();
ProtocolRestJsonServiceClientConfiguration.Builder conf =
(ProtocolRestJsonServiceClientConfiguration.Builder) config;
testCase.pluginSetter.accept(conf, testCase.nonDefaultValue);
};
AtomicInteger timesInterceptorCalled = new AtomicInteger(0);
ExecutionInterceptor validatingInterceptor = new ExecutionInterceptor() {
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
timesInterceptorCalled.incrementAndGet();
if (testCase.beforeTransmissionValidator != null) {
testCase.beforeTransmissionValidator.accept(context, executionAttributes, testCase.nonDefaultValue);
}
}
};
AwsRequestOverrideConfiguration requestConfig =
AwsRequestOverrideConfiguration.builder()
.addPlugin(plugin)
.applyMutation(c -> {
// TODO(sra-identity-auth): request-level plugins should override request-level
// configuration
// if (testCase.requestSetter != null) {
// testCase.requestSetter.accept(c, testCase.defaultValue);
// }
})
.build();
ProtocolRestJsonClient client =
clientBuilder.httpClient(succeedingHttpClient())
.overrideConfiguration(c -> c.addExecutionInterceptor(validatingInterceptor))
.build();
if (testCase.clientConfigurationValidator != null) {
testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.defaultValue);
}
client.allTypes(r -> r.overrideConfiguration(requestConfig));
assertThat(timesPluginCalled).hasValue(1);
assertThat(timesInterceptorCalled).hasValueGreaterThanOrEqualTo(1);
}
private static ProtocolRestJsonClientBuilder defaultClientBuilder() {
return ProtocolRestJsonClient.builder().region(Region.US_WEST_2).credentialsProvider(DEFAULT_CREDENTIALS);
}
private SdkClientConfiguration extractClientConfiguration(ProtocolRestJsonClient client) {
try {
// Naughty, but we need to be able to verify some things that can't be easily observed with unprotected means.
Class<? extends ProtocolRestJsonClient> clientClass = client.getClass();
Field configField = clientClass.getDeclaredField("clientConfiguration");
configField.setAccessible(true);
return (SdkClientConfiguration) configField.get(client);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static class TestCase<T> {
private final String configName;
T defaultValue;
T nonDefaultValue;
BiConsumer<ProtocolRestJsonClientBuilder, T> clientSetter;
BiConsumer<AwsRequestOverrideConfiguration.Builder, T> requestSetter;
BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> pluginSetter;
BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> pluginValidator;
BiConsumer<SdkClientConfiguration, T> clientConfigurationValidator;
TriConsumer<Context.BeforeTransmission, ExecutionAttributes, T> beforeTransmissionValidator;
TestCase(String configName) {
this.configName = configName;
}
public TestCase<T> defaultValue(T defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public TestCase<T> nonDefaultValue(T nonDefaultValue) {
this.nonDefaultValue = nonDefaultValue;
return this;
}
public TestCase<T> clientSetter(BiConsumer<ProtocolRestJsonClientBuilder, T> clientSetter) {
this.clientSetter = clientSetter;
return this;
}
public TestCase<T> requestSetter(BiConsumer<AwsRequestOverrideConfiguration.Builder, T> requestSetter) {
this.requestSetter = requestSetter;
return this;
}
public TestCase<T> pluginSetter(BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> pluginSetter) {
this.pluginSetter = pluginSetter;
return this;
}
public TestCase<T> pluginValidator(BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> pluginValidator) {
this.pluginValidator = pluginValidator;
return this;
}
public TestCase<T> clientConfigurationValidator(BiConsumer<SdkClientConfiguration, T> clientConfigurationValidator) {
this.clientConfigurationValidator = clientConfigurationValidator;
return this;
}
public TestCase<T> beforeTransmissionValidator(TriConsumer<Context.BeforeTransmission, ExecutionAttributes, T> beforeTransmissionValidator) {
this.beforeTransmissionValidator = beforeTransmissionValidator;
return this;
}
@Override
public String toString() {
return configName;
}
}
private static SdkHttpClient succeedingHttpClient() {
MockSyncHttpClient client = new MockSyncHttpClient();
client.stubNextResponse200();
return client;
}
private static URI removePathAndQueryString(URI uri) {
String uriString = uri.toString();
return URI.create(uriString.substring(0, uriString.indexOf('/', "https://".length())));
}
public interface TriConsumer<T, U, V> {
void accept(T t, U u, V v);
}
private static class CustomAuthScheme implements AuthScheme<NoAuthAuthScheme.AnonymousIdentity> {
private static final String SCHEME_ID = "foo";
private static final AuthScheme<NoAuthAuthScheme.AnonymousIdentity> DELEGATE = NoAuthAuthScheme.create();
@Override
public String schemeId() {
return SCHEME_ID;
}
@Override
public IdentityProvider<NoAuthAuthScheme.AnonymousIdentity> identityProvider(IdentityProviders providers) {
return DELEGATE.identityProvider(providers);
}
@Override
public HttpSigner<NoAuthAuthScheme.AnonymousIdentity> signer() {
return DELEGATE.signer();
}
}
private static class FlagSettingInterceptor implements ExecutionInterceptor {
private static final ExecutionAttribute<Boolean> FLAG = new ExecutionAttribute<>("InterceptorAdded");
@Override
public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) {
executionAttributes.putAttribute(FLAG, true);
}
}
}
| 2,598 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/CodegenServiceClientConfigurationTest.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.services;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.Mockito.mock;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.BiConsumer;
import java.util.function.Function;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.awscore.AwsServiceClientConfiguration;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.core.client.config.ClientOption;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.endpoints.EndpointProvider;
import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeProvider;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonServiceClientConfiguration;
import software.amazon.awssdk.services.protocolrestjson.auth.scheme.ProtocolRestJsonAuthSchemeProvider;
import software.amazon.awssdk.services.protocolrestjson.internal.ProtocolRestJsonServiceClientConfigurationBuilder;
public class CodegenServiceClientConfigurationTest {
private static final EndpointProvider MOCK_ENDPOINT_PROVIDER = mock(EndpointProvider.class);
private static final IdentityProvider<AwsCredentialsIdentity> MOCK_IDENTITY_PROVIDER = mock(IdentityProvider.class);
private static final ProtocolRestJsonAuthSchemeProvider MOCK_AUTH_SCHEME_PROVIDER =
mock(ProtocolRestJsonAuthSchemeProvider.class);
private static final ScheduledExecutorService MOCK_SCHEDULED_EXECUTOR_SERVICE = mock(ScheduledExecutorService.class);
private static final Signer MOCK_SIGNER = mock(Signer.class);
@ParameterizedTest
@MethodSource("testCases")
<T> void externalInternalTransforms_preserves_propertyValues(TestCase<T> testCase) {
SdkClientConfiguration.Builder clientConfig = SdkClientConfiguration.builder();
ProtocolRestJsonServiceClientConfigurationBuilder builder =
new ProtocolRestJsonServiceClientConfigurationBuilder(clientConfig);
// Verify that initially the value is null for properties with direct mapping.
if (testCase.hasDirectMapping) {
assertThat(testCase.getter.apply(builder)).isNull();
}
// Set the value
testCase.setter.accept(builder, testCase.value);
// Assert that we can retrieve the same value
assertThat(testCase.getter.apply(builder)).isEqualTo(testCase.value);
// Build the ServiceConfiguration instance
ProtocolRestJsonServiceClientConfiguration config = builder.build();
// Assert that we can retrieve the same value
assertThat(testCase.dataGetter.apply(config)).isEqualTo(testCase.value);
// Build a new builder with the created client config
ProtocolRestJsonServiceClientConfigurationBuilder anotherBuilder =
new ProtocolRestJsonServiceClientConfigurationBuilder(clientConfig);
// Assert that we can retrieve the same value
if (testCase.hasDirectMapping) {
assertThat(testCase.getter.apply(anotherBuilder)).isEqualTo(testCase.value);
}
}
public static List<TestCase<?>> testCases() throws Exception {
return Arrays.asList(
TestCase.<Region>builder()
.option(AwsClientOption.AWS_REGION)
.value(Region.US_WEST_2)
.setter(ProtocolRestJsonServiceClientConfiguration.Builder::region)
.getter(ProtocolRestJsonServiceClientConfiguration.Builder::region)
.dataGetter(AwsServiceClientConfiguration::region)
.build(),
TestCase.<URI>builder()
.option(SdkClientOption.ENDPOINT)
.value(new URI("http://localhost:8080"))
.setter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointOverride)
.getter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointOverride)
.dataGetter(x -> x.endpointOverride().orElse(null))
.build(),
TestCase.<EndpointProvider>builder()
.option(SdkClientOption.ENDPOINT_PROVIDER)
.value(MOCK_ENDPOINT_PROVIDER)
.setter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointProvider)
.getter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointProvider)
.dataGetter(x -> x.endpointProvider().orElse(null))
.build(),
TestCase.<IdentityProvider<? extends AwsCredentialsIdentity>>builder()
.option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER)
.value(MOCK_IDENTITY_PROVIDER)
.setter(ProtocolRestJsonServiceClientConfiguration.Builder::credentialsProvider)
.getter(ProtocolRestJsonServiceClientConfiguration.Builder::credentialsProvider)
.dataGetter(AwsServiceClientConfiguration::credentialsProvider)
.build(),
TestCase.<AuthSchemeProvider>builder()
.option(SdkClientOption.AUTH_SCHEME_PROVIDER)
.value(MOCK_AUTH_SCHEME_PROVIDER)
.setter((b, p) -> b.authSchemeProvider((ProtocolRestJsonAuthSchemeProvider) p))
.getter(ProtocolRestJsonServiceClientConfiguration.Builder::authSchemeProvider)
.dataGetter(ProtocolRestJsonServiceClientConfiguration::authSchemeProvider)
.build(),
// Override configuration gets tricky
TestCase.<ScheduledExecutorService>builder()
.option(SdkClientOption.SCHEDULED_EXECUTOR_SERVICE)
.value(MOCK_SCHEDULED_EXECUTOR_SERVICE)
.setter((b, p) -> b.overrideConfiguration(
ClientOverrideConfiguration.builder()
.scheduledExecutorService(p)
.build()))
.getter(b -> b.overrideConfiguration().scheduledExecutorService().orElse(null))
.dataGetter(d -> d.overrideConfiguration().scheduledExecutorService().orElse(null))
.withoutDirectMapping()
.build(),
TestCase.<Signer>builder()
.option(SdkAdvancedClientOption.SIGNER)
.value(MOCK_SIGNER)
.setter((b, p) -> b.overrideConfiguration(
ClientOverrideConfiguration.builder()
.putAdvancedOption(SdkAdvancedClientOption.SIGNER, p)
.build()))
.getter(b -> b.overrideConfiguration().advancedOption(SdkAdvancedClientOption.SIGNER).orElse(null))
.dataGetter(d -> d.overrideConfiguration().advancedOption(SdkAdvancedClientOption.SIGNER).orElse(null))
.withoutDirectMapping()
.build()
);
}
static class TestCase<T> {
private final ClientOption<T> option;
private final T value;
private final BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> setter;
private final Function<ProtocolRestJsonServiceClientConfiguration.Builder, T> getter;
private Function<ProtocolRestJsonServiceClientConfiguration, T> dataGetter;
private final boolean hasDirectMapping;
public TestCase(Builder<T> builder) {
this.option = builder.option;
this.value = builder.value;
this.setter = builder.setter;
this.getter = builder.getter;
this.dataGetter = builder.dataGetter;
this.hasDirectMapping = builder.hasDirectMapping;
}
public static <T> Builder<T> builder() {
return new Builder();
}
static class Builder<T> {
private ClientOption<T> option;
private T value;
private BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> setter;
private Function<ProtocolRestJsonServiceClientConfiguration.Builder, T> getter;
private Function<ProtocolRestJsonServiceClientConfiguration, T> dataGetter;
private boolean hasDirectMapping = true;
Builder<T> option(ClientOption<T> option) {
this.option = option;
return this;
}
Builder<T> value(T value) {
this.value = value;
return this;
}
Builder<T> setter(BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> setter) {
this.setter = setter;
return this;
}
Builder<T> getter(Function<ProtocolRestJsonServiceClientConfiguration.Builder, T> getter) {
this.getter = getter;
return this;
}
Builder<T> dataGetter(Function<ProtocolRestJsonServiceClientConfiguration, T> dataGetter) {
this.dataGetter = dataGetter;
return this;
}
Builder<T> withoutDirectMapping() {
this.hasDirectMapping = false;
return this;
}
TestCase<T> build() {
return new TestCase<>(this);
}
}
}
}
| 2,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.