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/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/unmarshalling/UnmarshallingAssertion.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.protocol.asserts.unmarshalling; /** * Assertion on the unmarshalled result. */ public abstract class UnmarshallingAssertion { /** * @param context Context containing additional metadata about the test case * @param actual Unmarshalled result object * @throws AssertionError If any assertions fail */ public final void assertMatches(UnmarshallingTestContext context, Object actual) { // Catches the exception to play nicer with lambda's try { doAssert(context, actual); } catch (Exception e) { throw new RuntimeException(e); } } /** * Hook to allow subclasses to perform their own assertion logic. Allows subclasses to throw * checked exceptions without propogating it back to the caller. */ protected abstract void doAssert(UnmarshallingTestContext context, Object actual) throws Exception; }
2,700
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/unmarshalling/UnmarshallingTestContext.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.protocol.asserts.unmarshalling; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.core.sync.ResponseTransformer; /** * Unmarshalling assertions require some context about the service and operation being exercised. */ public class UnmarshallingTestContext { private IntermediateModel model; private String operationName; private String streamedResponse; public UnmarshallingTestContext withModel(IntermediateModel model) { this.model = model; return this; } public IntermediateModel getModel() { return model; } public UnmarshallingTestContext withOperationName(String operationName) { this.operationName = operationName; return this; } public String getOperationName() { return operationName; } /** * Streamed response will only be present for operations that have a streaming member in the output. We * capture the actual contents if via a custom {@link ResponseTransformer}. */ public UnmarshallingTestContext withStreamedResponse(String streamedResponse) { this.streamedResponse = streamedResponse; return this; } public String getStreamedResponse() { return streamedResponse; } }
2,701
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/unmarshalling/UnmarshalledResultAssertion.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.protocol.asserts.unmarshalling; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.fasterxml.jackson.databind.JsonNode; import java.io.InputStream; import java.lang.reflect.Field; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.io.IOUtils; import org.unitils.reflectionassert.ReflectionComparator; import org.unitils.reflectionassert.ReflectionComparatorFactory; import org.unitils.reflectionassert.comparator.Comparator; import org.unitils.reflectionassert.difference.Difference; import org.unitils.reflectionassert.report.impl.DefaultDifferenceReport; import software.amazon.awssdk.protocol.reflect.ShapeModelReflector; /** * Asserts on the unmarshalled result of a given operation. */ public class UnmarshalledResultAssertion extends UnmarshallingAssertion { private final JsonNode expectedResult; public UnmarshalledResultAssertion(JsonNode expectedResult) { this.expectedResult = expectedResult; } @Override protected void doAssert(UnmarshallingTestContext context, Object actual) throws Exception { ShapeModelReflector shapeModelReflector = createShapeReflector(context); Object expectedResult = shapeModelReflector.createShapeObject(); for (Field field : expectedResult.getClass().getDeclaredFields()) { assertFieldEquals(field, actual, expectedResult); } // Streaming response is captured by the response handler so we have to handle it separately if (context.getStreamedResponse() != null) { assertEquals(shapeModelReflector.getStreamingMemberValue(), context.getStreamedResponse()); } } /** * We can't use assertReflectionEquals on the result object directly. InputStreams require some * special handling so we compare field by field and use a special assertion for streaming * types. */ private void assertFieldEquals(Field field, Object actual, Object expectedResult) throws Exception { field.setAccessible(true); if (field.getType().isAssignableFrom(InputStream.class)) { assertTrue(IOUtils.contentEquals((InputStream) field.get(expectedResult), (InputStream) field.get(actual))); } else { Difference difference = CustomComparatorFactory.getComparator() .getDifference(field.get(expectedResult), field.get(actual)); if (difference != null) { fail(new DefaultDifferenceReport().createReport(difference)); } } } private ShapeModelReflector createShapeReflector(UnmarshallingTestContext context) { return new ShapeModelReflector(context.getModel(), getOutputClassName(context), this.expectedResult); } /** * @return Class name of the output model. */ private String getOutputClassName(UnmarshallingTestContext context) { return context.getModel().getOperations().get(context.getOperationName()).getReturnType() .getReturnType(); } private static class CustomComparatorFactory extends ReflectionComparatorFactory { private static ReflectionComparator getComparator() { List<Comparator> comparators = new ArrayList<>(); comparators.add(new InstantComparator()); comparators.addAll(ReflectionComparatorFactory.getComparatorChain(Collections.emptySet())); return new ReflectionComparator(comparators); } } private static class InstantComparator implements Comparator { @Override public boolean canCompare(Object left, Object right) { return left instanceof Instant || right instanceof Instant; } @Override public Difference compare(Object left, Object right, boolean onlyFirstDifference, ReflectionComparator reflectionComparator) { if (right == null) { return new Difference("Right value null.", left, null); } if (!left.equals(right)) { return new Difference("Different values.", left, right); } return null; } } }
2,702
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/When.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.protocol.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; public class When { @JsonDeserialize(using = WhenActionDeserialzer.class) private WhenAction action; @JsonProperty(value = "operation") private String operationName; public WhenAction getAction() { return action; } public void setAction(WhenAction action) { this.action = action; } public String getOperationName() { return operationName; } public void setOperationName(String operationName) { this.operationName = operationName; } }
2,703
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/WhenActionDeserialzer.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.protocol.model; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import java.io.IOException; class WhenActionDeserialzer extends JsonDeserializer<WhenAction> { @Override public WhenAction deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { return WhenAction.fromValue(p.getText()); } }
2,704
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/WhenAction.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.protocol.model; public enum WhenAction { MARSHALL("marshall"), UNMARSHALL("unmarshall"); private final String action; WhenAction(String action) { this.action = action; } public static WhenAction fromValue(String action) { switch (action) { case "marshall": return MARSHALL; case "unmarshall": return UNMARSHALL; default: throw new IllegalArgumentException("Unsupported test action " + action); } } }
2,705
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/SdkHttpMethodDeserializer.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.protocol.model; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import java.io.IOException; import software.amazon.awssdk.http.SdkHttpMethod; public class SdkHttpMethodDeserializer extends JsonDeserializer<SdkHttpMethod> { @Override public SdkHttpMethod deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { return SdkHttpMethod.fromValue(p.getText()); } }
2,706
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/Then.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.protocol.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import software.amazon.awssdk.protocol.asserts.marshalling.MarshallingAssertion; import software.amazon.awssdk.protocol.asserts.marshalling.SerializedAs; import software.amazon.awssdk.protocol.asserts.unmarshalling.UnmarshalledResultAssertion; import software.amazon.awssdk.protocol.asserts.unmarshalling.UnmarshallingAssertion; public class Then { private final MarshallingAssertion serializedAs; private final UnmarshallingAssertion deserializedAs; @JsonCreator public Then(@JsonProperty("serializedAs") SerializedAs serializedAs, @JsonProperty("deserializedAs") JsonNode deserializedAs) { this.serializedAs = serializedAs; this.deserializedAs = new UnmarshalledResultAssertion(deserializedAs); } /** * @return The assertion object to use for marshalling tests */ public MarshallingAssertion getMarshallingAssertion() { return serializedAs; } /** * @return The assertion object to use for unmarshalling tests */ public UnmarshallingAssertion getUnmarshallingAssertion() { return deserializedAs; } }
2,707
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/GivenResponse.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.protocol.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Map; public class GivenResponse { @JsonProperty(value = "status_code") private Integer statusCode; private Map<String, List<String>> headers; private String body; public Integer getStatusCode() { return statusCode; } public void setStatusCode(Integer statusCode) { this.statusCode = statusCode; } public Map<String, List<String>> getHeaders() { return headers; } public void setHeaders(Map<String, List<String>> headers) { this.headers = headers; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } }
2,708
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/Given.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.protocol.model; import com.fasterxml.jackson.databind.JsonNode; public class Given { private JsonNode input; private GivenResponse response; public JsonNode getInput() { return input; } public void setInput(JsonNode input) { this.input = input; } public GivenResponse getResponse() { return response; } public void setResponse(GivenResponse response) { this.response = response; } }
2,709
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/TestCase.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.protocol.model; public class TestCase { private String description; // Given is optional private Given given = new Given(); private When when; private Then then; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Given getGiven() { return given; } public void setGiven(Given given) { this.given = given; } public When getWhen() { return when; } public void setWhen(When when) { this.when = when; } public Then getThen() { return then; } public void setThen(Then then) { this.then = then; } @Override public String toString() { return description; } }
2,710
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/TestSuite.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.protocol.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class TestSuite { private final List<String> testCases; @JsonCreator public TestSuite(@JsonProperty("testCases") List<String> testCases) { this.testCases = testCases; } public List<String> getTestCases() { return testCases; } }
2,711
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/runners/ProtocolTestRunner.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.protocol.runners; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.protocol.model.TestCase; import software.amazon.awssdk.protocol.reflect.ClientReflector; import software.amazon.awssdk.protocol.wiremock.WireMockUtils; /** * Runs a list of test cases (either marshalling or unmarshalling). */ public final class ProtocolTestRunner { private static final Logger log = LoggerFactory.getLogger(ProtocolTestRunner.class); private static final ObjectMapper MAPPER = new ObjectMapper() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .enable(JsonParser.Feature.ALLOW_COMMENTS); private final ClientReflector clientReflector; private final MarshallingTestRunner marshallingTestRunner; private final UnmarshallingTestRunner unmarshallingTestRunner; public ProtocolTestRunner(String intermediateModelLocation) { WireMockUtils.startWireMockServer(); IntermediateModel model = loadModel(intermediateModelLocation); this.clientReflector = new ClientReflector(model); this.marshallingTestRunner = new MarshallingTestRunner(model, clientReflector); this.unmarshallingTestRunner = new UnmarshallingTestRunner(model, clientReflector); } private IntermediateModel loadModel(String intermedidateModelLocation) { try { return MAPPER.readValue(getClass().getResource(intermedidateModelLocation), IntermediateModel.class); } catch (IOException e) { throw new RuntimeException(e); } } public void runTests(List<TestCase> tests) throws Exception { for (TestCase testCase : tests) { runTest(testCase); } clientReflector.close(); } public void runTest(TestCase testCase) throws Exception { log.info("Running test: {}", testCase.getDescription()); switch (testCase.getWhen().getAction()) { case MARSHALL: marshallingTestRunner.runTest(testCase); break; case UNMARSHALL: unmarshallingTestRunner.runTest(testCase); break; default: throw new IllegalArgumentException( "Unsupported action " + testCase.getWhen().getAction()); } } }
2,712
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/runners/MarshallingTestRunner.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.protocol.runners; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static org.junit.Assert.assertEquals; import com.fasterxml.jackson.databind.JsonNode; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.util.List; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.protocol.model.TestCase; import software.amazon.awssdk.protocol.reflect.ClientReflector; import software.amazon.awssdk.protocol.reflect.ShapeModelReflector; import software.amazon.awssdk.protocol.wiremock.WireMockUtils; /** * Test runner for test cases exercising the client marshallers. */ class MarshallingTestRunner { private final IntermediateModel model; private final ClientReflector clientReflector; MarshallingTestRunner(IntermediateModel model, ClientReflector clientReflector) { this.model = model; this.clientReflector = clientReflector; } /** * @return LoggedRequest that wire mock captured. */ private static LoggedRequest getLoggedRequest() { List<LoggedRequest> requests = WireMockUtils.findAllLoggedRequests(); assertEquals(1, requests.size()); return requests.get(0); } void runTest(TestCase testCase) throws Exception { resetWireMock(); ShapeModelReflector shapeModelReflector = createShapeModelReflector(testCase); if (!model.getShapes().get(testCase.getWhen().getOperationName() + "Request").isHasStreamingMember()) { clientReflector.invokeMethod(testCase, shapeModelReflector.createShapeObject()); } else { clientReflector.invokeMethod(testCase, shapeModelReflector.createShapeObject(), RequestBody.fromString(shapeModelReflector.getStreamingMemberValue())); } LoggedRequest actualRequest = getLoggedRequest(); testCase.getThen().getMarshallingAssertion().assertMatches(actualRequest); } /** * Reset wire mock and re-configure stubbing. */ private void resetWireMock() { WireMock.reset(); // Stub to return 200 for all requests ResponseDefinitionBuilder responseDefBuilder = aResponse().withStatus(200); // XML Unmarshallers expect at least one level in the XML document. if (model.getMetadata().isXmlProtocol()) { responseDefBuilder.withBody("<foo></foo>"); } stubFor(any(urlMatching(".*")).willReturn(responseDefBuilder)); } private ShapeModelReflector createShapeModelReflector(TestCase testCase) { String operationName = testCase.getWhen().getOperationName(); String requestClassName = getOperationRequestClassName(operationName); JsonNode input = testCase.getGiven().getInput(); return new ShapeModelReflector(model, requestClassName, input); } /** * @return Name of the request class that corresponds to the given operation. */ private String getOperationRequestClassName(String operationName) { return operationName + "Request"; } }
2,713
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/runners/UnmarshallingTestRunner.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.protocol.runners; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import com.fasterxml.jackson.databind.JsonNode; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.client.WireMock; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.protocol.asserts.unmarshalling.UnmarshallingTestContext; import software.amazon.awssdk.protocol.model.GivenResponse; import software.amazon.awssdk.protocol.model.TestCase; import software.amazon.awssdk.protocol.reflect.ClientReflector; import software.amazon.awssdk.protocol.reflect.ShapeModelReflector; import software.amazon.awssdk.utils.IoUtils; /** * Test runner for test cases exercising the client unmarshallers. */ class UnmarshallingTestRunner { private final IntermediateModel model; private final Metadata metadata; private final ClientReflector clientReflector; UnmarshallingTestRunner(IntermediateModel model, ClientReflector clientReflector) { this.model = model; this.metadata = model.getMetadata(); this.clientReflector = clientReflector; } void runTest(TestCase testCase) throws Exception { resetWireMock(testCase.getGiven().getResponse()); String operationName = testCase.getWhen().getOperationName(); ShapeModelReflector shapeModelReflector = createShapeModelReflector(testCase); if (!hasStreamingMember(operationName)) { Object actualResult = clientReflector.invokeMethod(testCase, shapeModelReflector.createShapeObject()); testCase.getThen().getUnmarshallingAssertion().assertMatches(createContext(operationName), actualResult); } else { CapturingResponseTransformer responseHandler = new CapturingResponseTransformer(); Object actualResult = clientReflector .invokeStreamingMethod(testCase, shapeModelReflector.createShapeObject(), responseHandler); testCase.getThen().getUnmarshallingAssertion() .assertMatches(createContext(operationName, responseHandler.captured), actualResult); } } /** * {@link ResponseTransformer} that simply captures all the content as a String so we * can compare it with the expected in * {@link software.amazon.awssdk.protocol.asserts.unmarshalling.UnmarshalledResultAssertion}. */ private static class CapturingResponseTransformer implements ResponseTransformer<Object, Void> { private String captured; @Override public Void transform(Object response, AbortableInputStream inputStream) throws Exception { this.captured = IoUtils.toUtf8String(inputStream); return null; } } private boolean hasStreamingMember(String operationName) { return model.getShapes().get(operationName + "Response").isHasStreamingMember(); } /** * Reset wire mock and re-configure stubbing. */ private void resetWireMock(GivenResponse givenResponse) { WireMock.reset(); // Stub to return given response in test definition. stubFor(any(urlMatching(".*")).willReturn(toResponseBuilder(givenResponse))); } private ResponseDefinitionBuilder toResponseBuilder(GivenResponse givenResponse) { ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(200); if (givenResponse.getHeaders() != null) { givenResponse.getHeaders().forEach((key, values) -> { responseBuilder.withHeader(key, values.toArray(new String[0])); }); } if (givenResponse.getStatusCode() != null) { responseBuilder.withStatus(givenResponse.getStatusCode()); } if (givenResponse.getBody() != null) { responseBuilder.withBody(givenResponse.getBody()); } else if (metadata.isXmlProtocol()) { // XML Unmarshallers expect at least one level in the XML document. If no body is explicitly // set by the test add a fake one here. responseBuilder.withBody("<foo></foo>"); } return responseBuilder; } private ShapeModelReflector createShapeModelReflector(TestCase testCase) { String operationName = testCase.getWhen().getOperationName(); String requestClassName = getOperationRequestClassName(operationName); JsonNode input = testCase.getGiven().getInput(); return new ShapeModelReflector(model, requestClassName, input); } private UnmarshallingTestContext createContext(String operationName) { return createContext(operationName, null); } private UnmarshallingTestContext createContext(String operationName, String streamedResponse) { return new UnmarshallingTestContext() .withModel(model) .withOperationName(operationName) .withStreamedResponse(streamedResponse); } /** * @return Name of the request class that corresponds to the given operation. */ private String getOperationRequestClassName(String operationName) { return model.getOperations().get(operationName).getInput().getVariableType(); } }
2,714
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/wiremock/WireMockUtils.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.protocol.wiremock; import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.http.RequestMethod; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.util.List; /** * Utils to start the WireMock server and retrieve the chosen port. */ public final class WireMockUtils { // Use 0 to dynamically assign an available port. private static final WireMockServer WIRE_MOCK = new WireMockServer(wireMockConfig().port(0)); private WireMockUtils() { } public static void startWireMockServer() { WIRE_MOCK.start(); WireMock.configureFor(WIRE_MOCK.port()); } /** * @return The port that was chosen by the WireMock server. */ public static int port() { return WIRE_MOCK.port(); } /** * @return All LoggedRequests that wire mock captured. */ public static List<LoggedRequest> findAllLoggedRequests() { List<LoggedRequest> requests = findAll( new RequestPatternBuilder(RequestMethod.ANY, urlMatching(".*"))); return requests; } public static void verifyRequestCount(int expectedCount, WireMockRule wireMock) { wireMock.verify(expectedCount, anyRequestedFor(anyUrl())); } }
2,715
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerBenchmarkConfig.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.s3benchmarks; import java.time.Duration; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.utils.ToString; public final class TransferManagerBenchmarkConfig { private final String filePath; private final String bucket; private final String key; private final Double targetThroughput; private final Long partSizeInMb; private final ChecksumAlgorithm checksumAlgorithm; private final Integer iteration; private final Long contentLengthInMb; private final Duration timeout; private final Long memoryUsageInMb; private final Long connectionAcquisitionTimeoutInSec; private final Boolean forceCrtHttpClient; private final Integer maxConcurrency; private final Long readBufferSizeInMb; private final BenchmarkRunner.TransferManagerOperation operation; private String prefix; private TransferManagerBenchmarkConfig(Builder builder) { this.filePath = builder.filePath; this.bucket = builder.bucket; this.key = builder.key; this.targetThroughput = builder.targetThroughput; this.partSizeInMb = builder.partSizeInMb; this.checksumAlgorithm = builder.checksumAlgorithm; this.iteration = builder.iteration; this.readBufferSizeInMb = builder.readBufferSizeInMb; this.operation = builder.operation; this.prefix = builder.prefix; this.contentLengthInMb = builder.contentLengthInMb; this.timeout = builder.timeout; this.memoryUsageInMb = builder.memoryUsage; this.connectionAcquisitionTimeoutInSec = builder.connectionAcquisitionTimeoutInSec; this.forceCrtHttpClient = builder.forceCrtHttpClient; this.maxConcurrency = builder.maxConcurrency; } public String filePath() { return filePath; } public String bucket() { return bucket; } public String key() { return key; } public Double targetThroughput() { return targetThroughput; } public Long partSizeInMb() { return partSizeInMb; } public ChecksumAlgorithm checksumAlgorithm() { return checksumAlgorithm; } public Integer iteration() { return iteration; } public Long readBufferSizeInMb() { return readBufferSizeInMb; } public BenchmarkRunner.TransferManagerOperation operation() { return operation; } public String prefix() { return prefix; } public Long contentLengthInMb() { return contentLengthInMb; } public Duration timeout() { return this.timeout; } public Long memoryUsageInMb() { return this.memoryUsageInMb; } public Long connectionAcquisitionTimeoutInSec() { return this.connectionAcquisitionTimeoutInSec; } public boolean forceCrtHttpClient() { return this.forceCrtHttpClient; } public Integer maxConcurrency() { return this.maxConcurrency; } public static Builder builder() { return new Builder(); } @Override public String toString() { return ToString.builder("TransferManagerBenchmarkConfig") .add("filePath", filePath) .add("bucket", bucket) .add("key", key) .add("targetThroughput", targetThroughput) .add("partSizeInMb", partSizeInMb) .add("checksumAlgorithm", checksumAlgorithm) .add("iteration", iteration) .add("contentLengthInMb", contentLengthInMb) .add("timeout", timeout) .add("memoryUsageInMb", memoryUsageInMb) .add("connectionAcquisitionTimeoutInSec", connectionAcquisitionTimeoutInSec) .add("forceCrtHttpClient", forceCrtHttpClient) .add("maxConcurrency", maxConcurrency) .add("readBufferSizeInMb", readBufferSizeInMb) .add("operation", operation) .add("prefix", prefix) .build(); } static final class Builder { private Long readBufferSizeInMb; private ChecksumAlgorithm checksumAlgorithm; private String filePath; private String bucket; private String key; private Double targetThroughput; private Long partSizeInMb; private Long contentLengthInMb; private Long memoryUsage; private Long connectionAcquisitionTimeoutInSec; private Boolean forceCrtHttpClient; private Integer maxConcurrency; private Integer iteration; private BenchmarkRunner.TransferManagerOperation operation; private String prefix; private Duration timeout; public Builder filePath(String filePath) { this.filePath = filePath; return this; } public Builder bucket(String bucket) { this.bucket = bucket; return this; } public Builder key(String key) { this.key = key; return this; } public Builder targetThroughput(Double targetThroughput) { this.targetThroughput = targetThroughput; return this; } public Builder partSizeInMb(Long partSizeInMb) { this.partSizeInMb = partSizeInMb; return this; } public Builder checksumAlgorithm(ChecksumAlgorithm checksumAlgorithm) { this.checksumAlgorithm = checksumAlgorithm; return this; } public Builder iteration(Integer iteration) { this.iteration = iteration; return this; } public Builder operation(BenchmarkRunner.TransferManagerOperation operation) { this.operation = operation; return this; } public Builder readBufferSizeInMb(Long readBufferSizeInMb) { this.readBufferSizeInMb = readBufferSizeInMb; return this; } public Builder prefix(String prefix) { this.prefix = prefix; return this; } public Builder contentLengthInMb(Long contentLengthInMb) { this.contentLengthInMb = contentLengthInMb; return this; } public Builder timeout(Duration timeout) { this.timeout = timeout; return this; } public Builder memoryUsageInMb(Long memoryUsage) { this.memoryUsage = memoryUsage; return this; } public Builder connectionAcquisitionTimeoutInSec(Long connectionAcquisitionTimeoutInSec) { this.connectionAcquisitionTimeoutInSec = connectionAcquisitionTimeoutInSec; return this; } public Builder forceCrtHttpClient(Boolean forceCrtHttpClient) { this.forceCrtHttpClient = forceCrtHttpClient; return this; } public Builder maxConcurrency(Integer maxConcurrency) { this.maxConcurrency = maxConcurrency; return this; } public TransferManagerBenchmarkConfig build() { return new TransferManagerBenchmarkConfig(this); } } }
2,716
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerUploadDirectoryBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload; import software.amazon.awssdk.transfer.s3.model.DirectoryUpload; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class TransferManagerUploadDirectoryBenchmark extends BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("TransferManagerUploadDirectoryBenchmark"); private final TransferManagerBenchmarkConfig config; public TransferManagerUploadDirectoryBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.filePath(), "File path must not be null"); this.config = config; } @Override protected void doRunBenchmark() { try { uploadDirectory(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } } private void uploadDirectory(int count, boolean printoutResult) throws Exception { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to upload directory"); for (int i = 0; i < count; i++) { uploadOnce(metrics); } if (printoutResult) { printOutResult(metrics, "TM v2 Upload Directory"); } } private void uploadOnce(List<Double> latencies) throws Exception { Path uploadPath = new File(this.path).toPath(); long start = System.currentTimeMillis(); DirectoryUpload upload = transferManager.uploadDirectory(b -> b.bucket(bucket) .s3Prefix(config.prefix()) .source(uploadPath)); CompletedDirectoryUpload completedDirectoryUpload = upload.completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS); if (completedDirectoryUpload.failedTransfers().isEmpty()) { long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } else { logger.error(() -> "Some transfers failed: " + completedDirectoryUpload.failedTransfers()); } } }
2,717
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/JavaS3ClientUploadBenchmark.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.s3benchmarks; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.utils.async.SimplePublisher; public class JavaS3ClientUploadBenchmark extends BaseJavaS3ClientBenchmark { private final String filePath; private final Long contentLengthInMb; private final Long partSizeInMb; private final ChecksumAlgorithm checksumAlgorithm; public JavaS3ClientUploadBenchmark(TransferManagerBenchmarkConfig config) { super(config); this.filePath = config.filePath(); this.contentLengthInMb = config.contentLengthInMb(); this.partSizeInMb = config.partSizeInMb(); this.checksumAlgorithm = config.checksumAlgorithm(); } @Override protected void sendOneRequest(List<Double> latencies) throws Exception { if (filePath == null) { double latency = uploadFromMemory(); latencies.add(latency); return; } Double latency = runWithTime( s3AsyncClient.putObject(req -> req.key(key).bucket(bucket).checksumAlgorithm(checksumAlgorithm), Paths.get(filePath))::join).latency(); latencies.add(latency); } private double uploadFromMemory() throws Exception { if (contentLengthInMb == null) { throw new UnsupportedOperationException("Java upload benchmark - contentLengthInMb required for upload from memory"); } long partSizeInBytes = partSizeInMb * MB; // upload using known content length SimplePublisher<ByteBuffer> publisher = new SimplePublisher<>(); byte[] bytes = new byte[(int) partSizeInBytes]; Thread uploadThread = Executors.defaultThreadFactory().newThread(() -> { long remaining = contentLengthInMb * MB; while (remaining > 0) { publisher.send(ByteBuffer.wrap(bytes)); remaining -= partSizeInBytes; } publisher.complete(); }); CompletableFuture<PutObjectResponse> responseFuture = s3AsyncClient.putObject(r -> r.bucket(bucket) .key(key) .contentLength(contentLengthInMb * MB) .checksumAlgorithm(checksumAlgorithm), AsyncRequestBody.fromPublisher(publisher)); uploadThread.start(); long start = System.currentTimeMillis(); responseFuture.get(timeout.getSeconds(), TimeUnit.SECONDS); long end = System.currentTimeMillis(); return (end - start) / 1000.0; } @Override protected long contentLength() throws Exception { return filePath != null ? Files.size(Paths.get(filePath)) : contentLengthInMb * MB; } }
2,718
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/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.s3benchmarks; import static software.amazon.awssdk.transfer.s3.SizeConstant.GB; import java.time.Duration; import java.util.Collection; import java.util.List; import software.amazon.awssdk.utils.Logger; public final class BenchmarkUtils { static final int PRE_WARMUP_ITERATIONS = 10; static final int PRE_WARMUP_RUNS = 20; static final int BENCHMARK_ITERATIONS = 10; static final Duration DEFAULT_TIMEOUT = Duration.ofMinutes(10); static final String WARMUP_KEY = "warmupobject"; static final String COPY_SUFFIX = "_copy"; private static final Logger logger = Logger.loggerFor("TransferManagerBenchmark"); private BenchmarkUtils() { } public static void printOutResult(List<Double> metrics, String name, long contentLengthInByte) { logger.info(() -> String.format("=============== %s Result ================", name)); logger.info(() -> String.valueOf(metrics)); double averageLatency = metrics.stream() .mapToDouble(a -> a) .average() .orElse(0.0); double lowestLatency = metrics.stream() .mapToDouble(a -> a) .min().orElse(0.0); double contentLengthInGigabit = (contentLengthInByte / (double) GB) * 8.0; logger.info(() -> "Average latency (s): " + averageLatency); logger.info(() -> "Latency variance (s): " + variance(metrics, averageLatency)); logger.info(() -> "Object size (Gigabit): " + contentLengthInGigabit); logger.info(() -> "Average throughput (Gbps): " + contentLengthInGigabit / averageLatency); logger.info(() -> "Highest average throughput (Gbps): " + contentLengthInGigabit / lowestLatency); logger.info(() -> "=========================================================="); } public static void printOutResult(List<Double> metrics, String name) { logger.info(() -> String.format("=============== %s Result ================", name)); logger.info(() -> String.valueOf(metrics)); double averageLatency = metrics.stream() .mapToDouble(a -> a) .average() .orElse(0.0); double lowestLatency = metrics.stream() .mapToDouble(a -> a) .min() .orElse(0.0); logger.info(() -> "Average latency (s): " + averageLatency); logger.info(() -> "Lowest latency (s): " + lowestLatency); logger.info(() -> "Latency variance (s): " + variance(metrics, averageLatency)); logger.info(() -> "=========================================================="); } /** * calculates the variance (std deviation squared) of the sample * @param sample the values to calculate the variance for * @param mean the known mean of the sample * @return the variance value */ private static double variance(Collection<Double> sample, double mean) { double numerator = 0; for (double value : sample) { double diff = value - mean; numerator += (diff * diff); } return numerator / sample.size(); } }
2,719
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1TransferManagerUploadBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import java.io.File; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class V1TransferManagerUploadBenchmark extends V1BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("V1TransferManagerUploadBenchmark"); private final File sourceFile; V1TransferManagerUploadBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); Validate.notNull(config.filePath(), "File path must not be null"); sourceFile = new File(path); } @Override protected void doRunBenchmark() { uploadFile(); } private void uploadFile() { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to upload"); for (int i = 0; i < iteration; i++) { uploadOnce(metrics); } long contentLength = sourceFile.length(); printOutResult(metrics, "TM v1 Upload File", contentLength); } private void uploadOnce(List<Double> latencies) { long start = System.currentTimeMillis(); try { transferManager.upload(bucket, key, sourceFile).waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
2,720
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerUploadBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import java.io.File; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.transfer.s3.model.Upload; import software.amazon.awssdk.transfer.s3.model.UploadRequest; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.async.SimplePublisher; public class TransferManagerUploadBenchmark extends BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("TransferManagerUploadBenchmark"); private final TransferManagerBenchmarkConfig config; public TransferManagerUploadBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); Validate.mutuallyExclusive("Only one of --file or --contentLengthInMB option must be specified, but both were.", config.filePath(), config.contentLengthInMb()); if (config.filePath() == null && config.contentLengthInMb() == null) { throw new IllegalArgumentException("Either --file or --contentLengthInMB must be specified, but none were."); } this.config = config; } @Override protected void doRunBenchmark() { try { doUpload(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } } @Override protected void additionalWarmup() { try { doUpload(3, false); } catch (Exception exception) { logger.error(() -> "Warmup failed: ", exception); } } private void doUpload(int count, boolean printOutResult) throws Exception { List<Double> metrics = new ArrayList<>(); for (int i = 0; i < count; i++) { if (config.contentLengthInMb() == null) { logger.info(() -> "Starting to upload from file"); uploadOnceFromFile(metrics); } else { logger.info(() -> "Starting to upload from memory"); uploadOnceFromMemory(metrics); } } if (printOutResult) { if (config.contentLengthInMb() == null) { printOutResult(metrics, "Upload from File", Files.size(Paths.get(path))); } else { printOutResult(metrics, "Upload from Memory", config.contentLengthInMb() * MB); } } } private void uploadOnceFromFile(List<Double> latencies) { File sourceFile = new File(path); long start = System.currentTimeMillis(); transferManager.uploadFile(b -> b.putObjectRequest(r -> r.bucket(bucket) .key(key) .checksumAlgorithm(config.checksumAlgorithm())) .source(sourceFile.toPath())) .completionFuture().join(); long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } private void uploadOnceFromMemory(List<Double> latencies) throws Exception { SimplePublisher<ByteBuffer> publisher = new SimplePublisher<>(); long partSizeInBytes = config.partSizeInMb() * MB; byte[] bytes = new byte[(int) partSizeInBytes]; UploadRequest uploadRequest = UploadRequest .builder() .putObjectRequest(r -> r.bucket(bucket) .key(key) .contentLength(config.contentLengthInMb() * MB) .checksumAlgorithm(config.checksumAlgorithm())) .requestBody(AsyncRequestBody.fromPublisher(publisher)) .build(); Thread uploadThread = Executors.defaultThreadFactory().newThread(() -> { long remaining = config.contentLengthInMb() * MB; while (remaining > 0) { publisher.send(ByteBuffer.wrap(bytes)); remaining -= partSizeInBytes; } publisher.complete(); }); Upload upload = transferManager.upload(uploadRequest); uploadThread.start(); long start = System.currentTimeMillis(); upload.completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS); long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
2,721
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1TransferManagerDownloadBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class V1TransferManagerDownloadBenchmark extends V1BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("V1TransferManagerDownloadBenchmark"); V1TransferManagerDownloadBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); Validate.notNull(config.filePath(), "File path must not be null"); } @Override protected void doRunBenchmark() { downloadToFile(); } private void downloadToFile() { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to download to file"); for (int i = 0; i < iteration; i++) { downloadOnceToFile(metrics); } long contentLength = s3Client.getObjectMetadata(bucket, key).getContentLength(); printOutResult(metrics, "V1 Download to File", contentLength); } private void downloadOnceToFile(List<Double> latencies) { Path downloadPath = new File(this.path).toPath(); long start = System.currentTimeMillis(); try { transferManager.download(bucket, key, new File(this.path)).waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); runAndLogError(logger.logger(), "Deleting file failed", () -> Files.delete(downloadPath)); } }
2,722
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/CrtS3ClientDownloadBenchmark.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.s3benchmarks; import java.net.URI; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.crt.http.HttpHeader; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.crt.s3.S3MetaRequest; import software.amazon.awssdk.crt.s3.S3MetaRequestOptions; import software.amazon.awssdk.crt.s3.S3MetaRequestResponseHandler; public class CrtS3ClientDownloadBenchmark extends BaseCrtClientBenchmark { public CrtS3ClientDownloadBenchmark(TransferManagerBenchmarkConfig config) { super(config); } @Override protected void sendOneRequest(List<Double> latencies) throws Exception { CompletableFuture<Void> resultFuture = new CompletableFuture<>(); S3MetaRequestResponseHandler responseHandler = new TestS3MetaRequestResponseHandler(resultFuture); String endpoint = bucket + ".s3." + region + ".amazonaws.com"; HttpHeader[] headers = {new HttpHeader("Host", endpoint)}; HttpRequest httpRequest = new HttpRequest("GET", "/" + key, headers, null); S3MetaRequestOptions metaRequestOptions = new S3MetaRequestOptions() .withEndpoint(URI.create("https://" + endpoint)) .withMetaRequestType(S3MetaRequestOptions.MetaRequestType.GET_OBJECT).withHttpRequest(httpRequest) .withResponseHandler(responseHandler); long start = System.currentTimeMillis(); try (S3MetaRequest metaRequest = crtS3Client.makeMetaRequest(metaRequestOptions)) { resultFuture.get(10, TimeUnit.MINUTES); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
2,723
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1TransferManagerUploadDirectoryBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import java.io.File; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class V1TransferManagerUploadDirectoryBenchmark extends V1BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("V1TransferManagerUploadDirectoryBenchmark"); private final TransferManagerBenchmarkConfig config; private final File sourceFile; V1TransferManagerUploadDirectoryBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.filePath(), "File path must not be null"); sourceFile = new File(path); this.config = config; } @Override protected void doRunBenchmark() { upload(); } private void upload() { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to upload directory"); for (int i = 0; i < iteration; i++) { uploadOnce(metrics); } printOutResult(metrics, "TM v1 Upload Directory"); } private void uploadOnce(List<Double> latencies) { long start = System.currentTimeMillis(); try { transferManager.uploadDirectory(bucket, config.prefix(), sourceFile, true).waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
2,724
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/JavaS3ClientCopyBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.COPY_SUFFIX; import java.util.List; import software.amazon.awssdk.utils.Logger; public class JavaS3ClientCopyBenchmark extends BaseJavaS3ClientBenchmark { private static final Logger log = Logger.loggerFor(JavaS3ClientCopyBenchmark.class); public JavaS3ClientCopyBenchmark(TransferManagerBenchmarkConfig config) { super(config); } @Override protected void sendOneRequest(List<Double> latencies) throws Exception { log.info(() -> "Starting copy"); Double latency = runWithTime(s3AsyncClient.copyObject( req -> req.sourceKey(key).sourceBucket(bucket) .destinationBucket(bucket).destinationKey(key + COPY_SUFFIX) )::join).latency(); latencies.add(latency); } @Override protected long contentLength() throws Exception { return s3Client.headObject(b -> b.bucket(bucket).key(key)).contentLength(); } }
2,725
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/BaseCrtClientBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.BENCHMARK_ITERATIONS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.s3.S3Client; import software.amazon.awssdk.crt.s3.S3ClientOptions; import software.amazon.awssdk.crt.s3.S3FinishedResponseContext; import software.amazon.awssdk.crt.s3.S3MetaRequestResponseHandler; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.providers.AwsRegionProvider; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.services.s3.internal.crt.S3NativeClientConfiguration; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public abstract class BaseCrtClientBenchmark implements TransferManagerBenchmark { private static final Logger logger = Logger.loggerFor(BaseCrtClientBenchmark.class); protected final String bucket; protected final String key; protected final int iteration; protected final S3NativeClientConfiguration s3NativeClientConfiguration; protected final S3Client crtS3Client; protected final software.amazon.awssdk.services.s3.S3Client s3Sync; protected final Region region; protected final long contentLength; protected BaseCrtClientBenchmark(TransferManagerBenchmarkConfig config) { logger.info(() -> "Benchmark config: " + config); Validate.isNull(config.filePath(), "File path is not supported in CrtS3ClientBenchmark"); Long partSizeInBytes = config.partSizeInMb() == null ? null : config.partSizeInMb() * MB; this.s3NativeClientConfiguration = S3NativeClientConfiguration.builder() .partSizeInBytes(partSizeInBytes) .targetThroughputInGbps(config.targetThroughput() == null ? Double.valueOf(100.0) : config.targetThroughput()) .checksumValidationEnabled(true) .build(); this.bucket = config.bucket(); this.key = config.key(); this.iteration = config.iteration() == null ? BENCHMARK_ITERATIONS : config.iteration(); S3ClientOptions s3ClientOptions = new S3ClientOptions().withRegion(s3NativeClientConfiguration.signingRegion()) .withEndpoint(s3NativeClientConfiguration.endpointOverride() == null ? null : s3NativeClientConfiguration.endpointOverride().toString()) .withCredentialsProvider(s3NativeClientConfiguration.credentialsProvider()) .withClientBootstrap(s3NativeClientConfiguration.clientBootstrap()) .withPartSize(s3NativeClientConfiguration.partSizeBytes()) .withComputeContentMd5(false) .withThroughputTargetGbps(s3NativeClientConfiguration.targetThroughputInGbps()); Long readBufferSizeInMb = config.readBufferSizeInMb() == null ? null : config.readBufferSizeInMb() * MB; if (readBufferSizeInMb != null) { s3ClientOptions.withInitialReadWindowSize(readBufferSizeInMb); s3ClientOptions.withReadBackpressureEnabled(true); } this.crtS3Client = new S3Client(s3ClientOptions); s3Sync = software.amazon.awssdk.services.s3.S3Client.builder().build(); this.contentLength = s3Sync.headObject(b -> b.bucket(bucket).key(key)).contentLength(); AwsRegionProvider instanceProfileRegionProvider = new DefaultAwsRegionProviderChain(); region = instanceProfileRegionProvider.getRegion(); } protected abstract void sendOneRequest(List<Double> latencies) throws Exception; @Override public void run() { try { warmUp(); doRunBenchmark(); } catch (Exception e) { logger.error(() -> "Exception occurred", e); } finally { cleanup(); } } private void cleanup() { s3Sync.close(); s3NativeClientConfiguration.close(); crtS3Client.close(); } private void warmUp() throws Exception { logger.info(() -> "Starting to warm up"); for (int i = 0; i < 3; i++) { sendOneRequest(new ArrayList<>()); Thread.sleep(500); } logger.info(() -> "Ending warm up"); } private void doRunBenchmark() throws Exception { List<Double> metrics = new ArrayList<>(); for (int i = 0; i < iteration; i++) { sendOneRequest(metrics); } printOutResult(metrics, "Download to File", contentLength); } protected static final class TestS3MetaRequestResponseHandler implements S3MetaRequestResponseHandler { private final CompletableFuture<Void> resultFuture; TestS3MetaRequestResponseHandler(CompletableFuture<Void> resultFuture) { this.resultFuture = resultFuture; } @Override public int onResponseBody(ByteBuffer bodyBytesIn, long objectRangeStart, long objectRangeEnd) { return bodyBytesIn.remaining(); } @Override public void onFinished(S3FinishedResponseContext context) { if (context.getErrorCode() != 0) { String errorMessage = String.format("Request failed. %s Response status: %s ", CRT.awsErrorString(context.getErrorCode()), context.getResponseStatus()); resultFuture.completeExceptionally( SdkClientException.create(errorMessage)); return; } resultFuture.complete(null); } } }
2,726
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1TransferManagerDownloadDirectoryBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.testutils.FileUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class V1TransferManagerDownloadDirectoryBenchmark extends V1BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("V1TransferManagerDownloadDirectoryBenchmark"); private final TransferManagerBenchmarkConfig config; V1TransferManagerDownloadDirectoryBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.filePath(), "File path must not be null"); this.config = config; } @Override protected void doRunBenchmark() { downloadDirectory(); } private void downloadDirectory() { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to download to file"); for (int i = 0; i < iteration; i++) { downloadOnce(metrics); } printOutResult(metrics, "TM v1 Download Directory"); } private void downloadOnce(List<Double> latencies) { Path downloadPath = new File(this.path).toPath(); long start = System.currentTimeMillis(); try { transferManager.downloadDirectory(bucket, config.prefix(), new File(this.path)).waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); runAndLogError(logger.logger(), "Deleting directory failed " + downloadPath, () -> FileUtils.cleanUpTestDirectory(downloadPath)); } }
2,727
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerDownloadDirectoryBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.testutils.FileUtils; import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload; import software.amazon.awssdk.transfer.s3.model.DirectoryDownload; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class TransferManagerDownloadDirectoryBenchmark extends BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("TransferManagerDownloadDirectoryBenchmark"); private final TransferManagerBenchmarkConfig config; public TransferManagerDownloadDirectoryBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.filePath(), "File path must not be null"); this.config = config; } @Override protected void doRunBenchmark() { try { downloadDirectory(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } } private void downloadDirectory(int count, boolean printoutResult) throws Exception { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to download to file"); for (int i = 0; i < count; i++) { downloadOnce(metrics); } if (printoutResult) { printOutResult(metrics, "TM v2 Download Directory"); } } private void downloadOnce(List<Double> latencies) throws Exception { Path downloadPath = new File(this.path).toPath(); long start = System.currentTimeMillis(); DirectoryDownload download = transferManager.downloadDirectory(b -> b.bucket(bucket) .destination(downloadPath) .listObjectsV2RequestTransformer(l -> l.prefix(config.prefix()))); CompletedDirectoryDownload completedDirectoryDownload = download.completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS); if (completedDirectoryDownload.failedTransfers().isEmpty()) { long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } else { logger.error(() -> "Some transfers failed: " + completedDirectoryDownload.failedTransfers()); } runAndLogError(logger.logger(), "Deleting directory failed " + downloadPath, () -> FileUtils.cleanUpTestDirectory(downloadPath)); } }
2,728
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/BenchmarkRunner.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.s3benchmarks; import java.time.Duration; import java.util.EnumMap; import java.util.Locale; import java.util.Map; import java.util.function.Function; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; public final class BenchmarkRunner { private static final String PART_SIZE_IN_MB = "partSizeInMB"; private static final String FILE = "file"; private static final String BUCKET = "bucket"; private static final String MAX_THROUGHPUT = "maxThroughput"; private static final String KEY = "key"; private static final String OPERATION = "operation"; private static final String CHECKSUM_ALGORITHM = "checksumAlgo"; private static final String ITERATION = "iteration"; private static final String CONTENT_LENGTH = "contentLengthInMB"; private static final String READ_BUFFER_IN_MB = "readBufferInMB"; private static final String VERSION = "version"; private static final String PREFIX = "prefix"; private static final String TIMEOUT = "timeoutInMin"; private static final String CONN_ACQ_TIMEOUT_IN_SEC = "connAcqTimeoutInSec"; private static final String FORCE_CRT_HTTP_CLIENT = "crtHttp"; private static final String MAX_CONCURRENCY = "maxConcurrency"; private static final Map<TransferManagerOperation, Function<TransferManagerBenchmarkConfig, TransferManagerBenchmark>> OPERATION_TO_BENCHMARK_V1 = new EnumMap<>(TransferManagerOperation.class); private static final Map<TransferManagerOperation, Function<TransferManagerBenchmarkConfig, TransferManagerBenchmark>> OPERATION_TO_BENCHMARK_V2 = new EnumMap<>(TransferManagerOperation.class); static { OPERATION_TO_BENCHMARK_V2.put(TransferManagerOperation.COPY, TransferManagerBenchmark::copy); OPERATION_TO_BENCHMARK_V2.put(TransferManagerOperation.DOWNLOAD, TransferManagerBenchmark::v2Download); OPERATION_TO_BENCHMARK_V2.put(TransferManagerOperation.UPLOAD, TransferManagerBenchmark::v2Upload); OPERATION_TO_BENCHMARK_V2.put(TransferManagerOperation.DOWNLOAD_DIRECTORY, TransferManagerBenchmark::downloadDirectory); OPERATION_TO_BENCHMARK_V2.put(TransferManagerOperation.UPLOAD_DIRECTORY, TransferManagerBenchmark::uploadDirectory); OPERATION_TO_BENCHMARK_V1.put(TransferManagerOperation.COPY, TransferManagerBenchmark::v1Copy); OPERATION_TO_BENCHMARK_V1.put(TransferManagerOperation.DOWNLOAD, TransferManagerBenchmark::v1Download); OPERATION_TO_BENCHMARK_V1.put(TransferManagerOperation.UPLOAD, TransferManagerBenchmark::v1Upload); OPERATION_TO_BENCHMARK_V1.put(TransferManagerOperation.DOWNLOAD_DIRECTORY, TransferManagerBenchmark::v1DownloadDirectory); OPERATION_TO_BENCHMARK_V1.put(TransferManagerOperation.UPLOAD_DIRECTORY, TransferManagerBenchmark::v1UploadDirectory); } private BenchmarkRunner() { } public static void main(String... args) throws org.apache.commons.cli.ParseException { CommandLineParser parser = new DefaultParser(); Options options = new Options(); options.addRequiredOption(null, BUCKET, true, "The s3 bucket"); options.addOption(null, KEY, true, "The s3 key"); options.addRequiredOption(null, OPERATION, true, "The operation to run tests: download | upload | download_directory | " + "upload_directory | copy"); options.addOption(null, FILE, true, "Destination file path to be written to or source file path to be " + "uploaded"); options.addOption(null, PART_SIZE_IN_MB, true, "Part size in MB"); options.addOption(null, MAX_THROUGHPUT, true, "The max throughput"); options.addOption(null, CHECKSUM_ALGORITHM, true, "The checksum algorithm to use"); options.addOption(null, ITERATION, true, "The number of iterations"); options.addOption(null, READ_BUFFER_IN_MB, true, "Read buffer size in MB"); options.addOption(null, VERSION, true, "The major version of the transfer manager to run test: " + "v1 | v2 | crt | java, default: v2"); options.addOption(null, PREFIX, true, "S3 Prefix used in downloadDirectory and uploadDirectory"); options.addOption(null, CONTENT_LENGTH, true, "Content length to upload from memory. Used only in the " + "CRT Upload Benchmark, but " + "is required for this test case."); options.addOption(null, TIMEOUT, true, "Amount of minute to wait before a single operation " + "times out and is cancelled. Optional, defaults to 10 minutes if no specified"); options.addOption(null, CONN_ACQ_TIMEOUT_IN_SEC, true, "Timeout for acquiring an already-established" + " connection from a connection pool to a remote service."); options.addOption(null, FORCE_CRT_HTTP_CLIENT, true, "Force the CRT http client to be used in JavaBased benchmarks"); options.addOption(null, MAX_CONCURRENCY, true, "The Maximum number of allowed concurrent requests. For HTTP/1.1 this is the same as max connections."); CommandLine cmd = parser.parse(options, args); TransferManagerBenchmarkConfig config = parseConfig(cmd); SdkVersion version = SdkVersion.valueOf(cmd.getOptionValue(VERSION, "V2") .toUpperCase(Locale.ENGLISH)); TransferManagerOperation operation = config.operation(); TransferManagerBenchmark benchmark; switch (version) { case V1: benchmark = OPERATION_TO_BENCHMARK_V1.get(operation).apply(config); break; case V2: benchmark = OPERATION_TO_BENCHMARK_V2.get(operation).apply(config); break; case CRT: if (operation == TransferManagerOperation.DOWNLOAD) { benchmark = new CrtS3ClientDownloadBenchmark(config); break; } if (operation == TransferManagerOperation.UPLOAD) { benchmark = new CrtS3ClientUploadBenchmark(config); break; } throw new UnsupportedOperationException(); case JAVA: if (operation == TransferManagerOperation.UPLOAD) { benchmark = new JavaS3ClientUploadBenchmark(config); break; } if (operation == TransferManagerOperation.COPY) { benchmark = new JavaS3ClientCopyBenchmark(config); break; } throw new UnsupportedOperationException("Java based s3 client benchmark only support upload and copy"); default: throw new UnsupportedOperationException(); } benchmark.run(); } private static TransferManagerBenchmarkConfig parseConfig(CommandLine cmd) { TransferManagerOperation operation = TransferManagerOperation.valueOf(cmd.getOptionValue(OPERATION) .toUpperCase(Locale.ENGLISH)); String filePath = cmd.getOptionValue(FILE); String bucket = cmd.getOptionValue(BUCKET); String key = cmd.getOptionValue(KEY); Long partSize = cmd.getOptionValue(PART_SIZE_IN_MB) == null ? null : Long.parseLong(cmd.getOptionValue(PART_SIZE_IN_MB)); Double maxThroughput = cmd.getOptionValue(MAX_THROUGHPUT) == null ? null : Double.parseDouble(cmd.getOptionValue(MAX_THROUGHPUT)); ChecksumAlgorithm checksumAlgorithm = null; if (cmd.getOptionValue(CHECKSUM_ALGORITHM) != null) { checksumAlgorithm = ChecksumAlgorithm.fromValue(cmd.getOptionValue(CHECKSUM_ALGORITHM) .toUpperCase(Locale.ENGLISH)); } Integer iteration = cmd.getOptionValue(ITERATION) == null ? null : Integer.parseInt(cmd.getOptionValue(ITERATION)); Long readBufferInMB = cmd.getOptionValue(READ_BUFFER_IN_MB) == null ? null : Long.parseLong(cmd.getOptionValue(READ_BUFFER_IN_MB)); String prefix = cmd.getOptionValue(PREFIX); Long contentLengthInMb = cmd.getOptionValue(CONTENT_LENGTH) == null ? null : Long.parseLong(cmd.getOptionValue(CONTENT_LENGTH)); Duration timeout = cmd.getOptionValue(TIMEOUT) == null ? null : Duration.ofMinutes(Long.parseLong(cmd.getOptionValue(TIMEOUT))); Long connAcqTimeoutInSec = cmd.getOptionValue(CONN_ACQ_TIMEOUT_IN_SEC) == null ? null : Long.parseLong(cmd.getOptionValue(CONN_ACQ_TIMEOUT_IN_SEC)); Boolean forceCrtHttpClient = cmd.getOptionValue(FORCE_CRT_HTTP_CLIENT) != null && Boolean.parseBoolean(cmd.getOptionValue(FORCE_CRT_HTTP_CLIENT)); Integer maxConcurrency = cmd.getOptionValue(MAX_CONCURRENCY) == null ? null : Integer.parseInt(cmd.getOptionValue(MAX_CONCURRENCY)); return TransferManagerBenchmarkConfig.builder() .key(key) .bucket(bucket) .partSizeInMb(partSize) .checksumAlgorithm(checksumAlgorithm) .targetThroughput(maxThroughput) .readBufferSizeInMb(readBufferInMB) .filePath(filePath) .iteration(iteration) .operation(operation) .prefix(prefix) .contentLengthInMb(contentLengthInMb) .timeout(timeout) .connectionAcquisitionTimeoutInSec(connAcqTimeoutInSec) .forceCrtHttpClient(forceCrtHttpClient) .maxConcurrency(maxConcurrency) .build(); } public enum TransferManagerOperation { DOWNLOAD, UPLOAD, COPY, DOWNLOAD_DIRECTORY, UPLOAD_DIRECTORY } private enum SdkVersion { V1, V2, CRT, JAVA } }
2,729
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerCopyBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.COPY_SUFFIX; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.transfer.s3.model.Copy; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class TransferManagerCopyBenchmark extends BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("TransferManagerCopyBenchmark"); private final long contentLength; public TransferManagerCopyBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); this.contentLength = s3Sync.headObject(b -> b.bucket(bucket).key(key)).contentLength(); } @Override protected void doRunBenchmark() { try { copy(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } } @Override protected void additionalWarmup() throws Exception { copy(5, false); } private void copy(int count, boolean printoutResult) throws Exception { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to copy"); for (int i = 0; i < count; i++) { copyOnce(metrics); } if (printoutResult) { printOutResult(metrics, "TM v2 copy", contentLength); } } private void copyOnce(List<Double> latencies) throws Exception { long start = System.currentTimeMillis(); Copy copy = transferManager.copy(b -> b.copyObjectRequest(c -> c.sourceBucket(bucket).sourceKey(key) .destinationBucket(bucket).destinationKey(key + COPY_SUFFIX))); copy.completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS); long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
2,730
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerDownloadBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.transfer.s3.model.DownloadRequest; import software.amazon.awssdk.transfer.s3.model.FileDownload; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class TransferManagerDownloadBenchmark extends BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("TransferManagerDownloadBenchmark"); private final long contentLength; public TransferManagerDownloadBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); this.contentLength = s3Sync.headObject(b -> b.bucket(bucket).key(key)).contentLength(); } @Override protected void doRunBenchmark() { if (path == null) { try { downloadToMemory(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } return; } try { downloadToFile(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } } private void downloadToMemory(int count, boolean printoutResult) throws Exception { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to download to memory"); for (int i = 0; i < count; i++) { downloadOnceToMemory(metrics); } if (printoutResult) { printOutResult(metrics, "TM v2 Download to Memory", contentLength); } } private void downloadToFile(int count, boolean printoutResult) throws Exception { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to download to file"); for (int i = 0; i < count; i++) { downloadOnceToFile(metrics); } if (printoutResult) { printOutResult(metrics, "TM v2 Download to File", contentLength); } } private void downloadOnceToFile(List<Double> latencies) throws Exception { Path downloadPath = new File(this.path).toPath(); long start = System.currentTimeMillis(); FileDownload download = transferManager.downloadFile(b -> b.getObjectRequest(r -> r.bucket(bucket).key(key)) .destination(downloadPath)); download.completionFuture().get(10, TimeUnit.MINUTES); long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); runAndLogError(logger.logger(), "Deleting file failed", () -> Files.delete(downloadPath)); } private void downloadOnceToMemory(List<Double> latencies) throws Exception { long start = System.currentTimeMillis(); AsyncResponseTransformer<GetObjectResponse, Void> responseTransformer = new NoOpResponseTransformer<>(); transferManager.download(DownloadRequest.builder() .getObjectRequest(req -> req.bucket(bucket).key(key)) .responseTransformer(responseTransformer) .build()) .completionFuture() .get(timeout.getSeconds(), TimeUnit.SECONDS); long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
2,731
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/CrtS3ClientUploadBenchmark.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.s3benchmarks; import java.net.URI; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.crt.http.HttpHeader; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.crt.http.HttpRequestBodyStream; import software.amazon.awssdk.crt.s3.S3MetaRequest; import software.amazon.awssdk.crt.s3.S3MetaRequestOptions; import software.amazon.awssdk.crt.s3.S3MetaRequestResponseHandler; import software.amazon.awssdk.crt.utils.ByteBufferUtils; public class CrtS3ClientUploadBenchmark extends BaseCrtClientBenchmark { private final String filepath; public CrtS3ClientUploadBenchmark(TransferManagerBenchmarkConfig config) { super(config); this.filepath = config.filePath(); } @Override public void sendOneRequest(List<Double> latencies) throws Exception { CompletableFuture<Void> resultFuture = new CompletableFuture<>(); S3MetaRequestResponseHandler responseHandler = new TestS3MetaRequestResponseHandler(resultFuture); String endpoint = bucket + ".s3." + region + ".amazonaws.com"; ByteBuffer payload = ByteBuffer.wrap(Files.readAllBytes(Paths.get(filepath))); HttpRequestBodyStream payloadStream = new PayloadStream(payload); HttpHeader[] headers = {new HttpHeader("Host", endpoint)}; HttpRequest httpRequest = new HttpRequest( "PUT", "/" + key, headers, payloadStream); S3MetaRequestOptions metaRequestOptions = new S3MetaRequestOptions() .withEndpoint(URI.create("https://" + endpoint)) .withMetaRequestType(S3MetaRequestOptions.MetaRequestType.PUT_OBJECT) .withHttpRequest(httpRequest) .withResponseHandler(responseHandler); long start = System.currentTimeMillis(); try (S3MetaRequest metaRequest = crtS3Client.makeMetaRequest(metaRequestOptions)) { resultFuture.get(10, TimeUnit.MINUTES); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } private static class PayloadStream implements HttpRequestBodyStream { private ByteBuffer payload; private PayloadStream(ByteBuffer payload) { this.payload = payload; } @Override public boolean sendRequestBody(ByteBuffer outBuffer) { ByteBufferUtils.transferData(payload, outBuffer); return payload.remaining() == 0; } @Override public boolean resetPosition() { return true; } @Override public long getLength() { return payload.capacity(); } } }
2,732
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/BaseTransferManagerBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.BENCHMARK_ITERATIONS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.COPY_SUFFIX; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.DEFAULT_TIMEOUT; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.WARMUP_KEY; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3CrtAsyncClientBuilder; import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.utils.Logger; public abstract class BaseTransferManagerBenchmark implements TransferManagerBenchmark { protected static final int WARMUP_ITERATIONS = 10; private static final Logger logger = Logger.loggerFor("TransferManagerBenchmark"); protected final S3TransferManager transferManager; protected final S3AsyncClient s3; protected final S3Client s3Sync; protected final String bucket; protected final String key; protected final String path; protected final int iteration; protected final Duration timeout; private final File file; BaseTransferManagerBenchmark(TransferManagerBenchmarkConfig config) { logger.info(() -> "Benchmark config: " + config); Long partSizeInMb = config.partSizeInMb() == null ? null : config.partSizeInMb() * MB; Long readBufferSizeInMb = config.readBufferSizeInMb() == null ? null : config.readBufferSizeInMb() * MB; S3CrtAsyncClientBuilder builder = S3CrtAsyncClient.builder() .targetThroughputInGbps(config.targetThroughput()) .minimumPartSizeInBytes(partSizeInMb) .initialReadBufferSizeInBytes(readBufferSizeInMb) .targetThroughputInGbps(config.targetThroughput() == null ? Double.valueOf(100.0) : config.targetThroughput()); if (config.maxConcurrency() != null) { builder.maxConcurrency(config.maxConcurrency()); } s3 = builder.build(); s3Sync = S3Client.builder().build(); transferManager = S3TransferManager.builder() .s3Client(s3) .build(); bucket = config.bucket(); key = config.key(); path = config.filePath(); iteration = config.iteration() == null ? BENCHMARK_ITERATIONS : config.iteration(); timeout = config.timeout() == null ? DEFAULT_TIMEOUT : config.timeout(); try { file = new RandomTempFile(10 * MB); file.deleteOnExit(); } catch (IOException e) { logger.error(() -> "Failed to create the file"); throw new RuntimeException("Failed to create the temp file", e); } } @Override public void run() { try { warmUp(); doRunBenchmark(); } catch (Exception e) { logger.error(() -> "Exception occurred", e); } finally { cleanup(); } } /** * Hook method to allow subclasses to add additional warm up */ protected void additionalWarmup() throws Exception { // default to no-op } protected abstract void doRunBenchmark(); private void cleanup() { try { s3Sync.deleteObject(b -> b.bucket(bucket).key(WARMUP_KEY)); } catch (Exception exception) { logger.error(() -> "Failed to delete object: " + WARMUP_KEY); } String copyObject = WARMUP_KEY + COPY_SUFFIX; try { s3Sync.deleteObject(b -> b.bucket(bucket).key(copyObject)); } catch (Exception exception) { logger.error(() -> "Failed to delete object: " + copyObject); } s3.close(); s3Sync.close(); transferManager.close(); } private void warmUp() throws Exception { logger.info(() -> "Starting to warm up"); for (int i = 0; i < WARMUP_ITERATIONS; i++) { warmUpUploadBatch(); warmUpDownloadBatch(); warmUpCopyBatch(); Thread.sleep(500); } additionalWarmup(); logger.info(() -> "Ending warm up"); } private void warmUpCopyBatch() { List<CompletableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { futures.add(transferManager.copy( c -> c.copyObjectRequest(r -> r.sourceKey(WARMUP_KEY) .sourceBucket(bucket) .destinationKey(WARMUP_KEY + "_copy") .destinationBucket(bucket))) .completionFuture()); } CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).join(); } private void warmUpDownloadBatch() { List<CompletableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < 20; i++) { Path tempFile = RandomTempFile.randomUncreatedFile().toPath(); futures.add(s3.getObject(GetObjectRequest.builder().bucket(bucket).key(WARMUP_KEY).build(), AsyncResponseTransformer.toFile(tempFile)).whenComplete((r, t) -> runAndLogError( logger.logger(), "Deleting file failed", () -> Files.delete(tempFile)))); } CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).join(); } private void warmUpUploadBatch() { List<CompletableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < 20; i++) { futures.add(s3.putObject(PutObjectRequest.builder().bucket(bucket).key(WARMUP_KEY).build(), AsyncRequestBody.fromFile(file))); } CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).join(); } }
2,733
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1BaseTransferManagerBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.BENCHMARK_ITERATIONS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.COPY_SUFFIX; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.PRE_WARMUP_ITERATIONS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.PRE_WARMUP_RUNS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.WARMUP_KEY; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import com.amazonaws.ClientConfiguration; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.transfer.Copy; import com.amazonaws.services.s3.transfer.Download; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.TransferManagerBuilder; import com.amazonaws.services.s3.transfer.Upload; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.utils.Logger; abstract class V1BaseTransferManagerBenchmark implements TransferManagerBenchmark { private static final int MAX_CONCURRENCY = 100; private static final Logger logger = Logger.loggerFor("TransferManagerBenchmark"); protected final TransferManager transferManager; protected final AmazonS3 s3Client; protected final String bucket; protected final String key; protected final int iteration; protected final String path; private final File tmpFile; private final ExecutorService executorService; V1BaseTransferManagerBenchmark(TransferManagerBenchmarkConfig config) { logger.info(() -> "Benchmark config: " + config); Long partSizeInMb = config.partSizeInMb() == null ? null : config.partSizeInMb() * MB; s3Client = AmazonS3Client.builder() .withClientConfiguration(new ClientConfiguration().withMaxConnections(MAX_CONCURRENCY)) .build(); executorService = Executors.newFixedThreadPool(MAX_CONCURRENCY); transferManager = TransferManagerBuilder.standard() .withMinimumUploadPartSize(partSizeInMb) .withS3Client(s3Client) .withExecutorFactory(() -> executorService) .build(); bucket = config.bucket(); key = config.key(); path = config.filePath(); iteration = config.iteration() == null ? BENCHMARK_ITERATIONS : config.iteration(); try { tmpFile = new RandomTempFile(20 * MB); } catch (IOException e) { logger.error(() -> "Failed to create the file"); throw new RuntimeException("Failed to create the temp file", e); } } @Override public void run() { try { warmUp(); additionalWarmup(); doRunBenchmark(); } catch (Exception e) { logger.error(() -> "Exception occurred", e); } finally { cleanup(); } } protected void additionalWarmup() { // default to no-op } protected abstract void doRunBenchmark(); private void cleanup() { executorService.shutdown(); transferManager.shutdownNow(); s3Client.shutdown(); } private void warmUp() { logger.info(() -> "Starting to warm up"); for (int i = 0; i < PRE_WARMUP_ITERATIONS; i++) { warmUpUploadBatch(); warmUpDownloadBatch(); warmUpCopyBatch(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } } logger.info(() -> "Ending warm up"); } private void warmUpCopyBatch() { List<Copy> uploads = new ArrayList<>(); for (int i = 0; i < 3; i++) { uploads.add(transferManager.copy(bucket, WARMUP_KEY, bucket, WARMUP_KEY + COPY_SUFFIX)); } uploads.forEach(u -> { try { u.waitForCopyResult(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error(() -> "Thread interrupted ", e); } }); } private void warmUpDownloadBatch() { List<Download> downloads = new ArrayList<>(); List<File> tmpFiles = new ArrayList<>(); for (int i = 0; i < PRE_WARMUP_RUNS; i++) { File tmpFile = RandomTempFile.randomUncreatedFile(); tmpFiles.add(tmpFile); downloads.add(transferManager.download(bucket, WARMUP_KEY, tmpFile)); } downloads.forEach(u -> { try { u.waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error(() -> "Thread interrupted ", e); } }); tmpFiles.forEach(f -> runAndLogError(logger.logger(), "Deleting file failed", () -> Files.delete(f.toPath()))); } private void warmUpUploadBatch() { List<Upload> uploads = new ArrayList<>(); for (int i = 0; i < PRE_WARMUP_RUNS; i++) { uploads.add(transferManager.upload(bucket, WARMUP_KEY, tmpFile)); } uploads.forEach(u -> { try { u.waitForUploadResult(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error(() -> "Thread interrupted ", e); } }); } }
2,734
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/NoOpResponseTransformer.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.s3benchmarks; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; /** * A no-op {@link AsyncResponseTransformer} */ public class NoOpResponseTransformer<T> implements AsyncResponseTransformer<T, Void> { private CompletableFuture<Void> future; @Override public CompletableFuture<Void> prepare() { future = new CompletableFuture<>(); return future; } @Override public void onResponse(T response) { // do nothing } @Override public void onStream(SdkPublisher<ByteBuffer> publisher) { publisher.subscribe(new NoOpSubscriber(future)); } @Override public void exceptionOccurred(Throwable error) { future.completeExceptionally(error); } static class NoOpSubscriber implements Subscriber<ByteBuffer> { private final CompletableFuture<Void> future; private Subscription subscription; NoOpSubscriber(CompletableFuture<Void> future) { this.future = future; } @Override public void onSubscribe(Subscription s) { this.subscription = s; subscription.request(Long.MAX_VALUE); } @Override public void onNext(ByteBuffer byteBuffer) { subscription.request(1); } @Override public void onError(Throwable throwable) { future.completeExceptionally(throwable); } @Override public void onComplete() { future.complete(null); } } }
2,735
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1TransferManagerCopyBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.COPY_SUFFIX; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class V1TransferManagerCopyBenchmark extends V1BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("V1TransferManagerCopyBenchmark"); V1TransferManagerCopyBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); } @Override protected void doRunBenchmark() { copy(); } @Override protected void additionalWarmup() { for (int i = 0; i < 3; i++) { copyOnce(new ArrayList<>()); } } private void copy() { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to copy"); for (int i = 0; i < iteration; i++) { copyOnce(metrics); } long contentLength = s3Client.getObjectMetadata(bucket, key).getContentLength(); printOutResult(metrics, "V1 copy", contentLength); } private void copyOnce(List<Double> latencies) { long start = System.currentTimeMillis(); try { transferManager.copy(bucket, key, bucket, key + COPY_SUFFIX).waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
2,736
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/BaseJavaS3ClientBenchmark.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.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.BENCHMARK_ITERATIONS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.DEFAULT_TIMEOUT; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import java.time.Duration; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public abstract class BaseJavaS3ClientBenchmark implements TransferManagerBenchmark { private static final Logger logger = Logger.loggerFor(BaseJavaS3ClientBenchmark.class); protected final S3Client s3Client; protected final S3AsyncClient s3AsyncClient; protected final String bucket; protected final String key; protected final Duration timeout; private final ChecksumAlgorithm checksumAlgorithm; private final int iteration; protected BaseJavaS3ClientBenchmark(TransferManagerBenchmarkConfig config) { this.bucket = Validate.paramNotNull(config.bucket(), "bucket"); this.key = Validate.paramNotNull(config.key(), "key"); this.timeout = Validate.getOrDefault(config.timeout(), () -> DEFAULT_TIMEOUT); this.iteration = Validate.getOrDefault(config.iteration(), () -> BENCHMARK_ITERATIONS); this.checksumAlgorithm = config.checksumAlgorithm(); this.s3Client = S3Client.create(); long partSizeInMb = Validate.paramNotNull(config.partSizeInMb(), "partSize"); long readBufferInMb = Validate.paramNotNull(config.readBufferSizeInMb(), "readBufferSizeInMb"); Validate.mutuallyExclusive("cannot use forceCrtHttpClient and connectionAcquisitionTimeoutInSec", config.forceCrtHttpClient(), config.connectionAcquisitionTimeoutInSec()); this.s3AsyncClient = S3AsyncClient.builder() .multipartEnabled(true) .multipartConfiguration(c -> c.minimumPartSizeInBytes(partSizeInMb * MB) .thresholdInBytes(partSizeInMb * 2 * MB) .apiCallBufferSizeInBytes(readBufferInMb * MB)) .httpClientBuilder(httpClient(config)) .build(); } private SdkAsyncHttpClient.Builder httpClient(TransferManagerBenchmarkConfig config) { if (config.forceCrtHttpClient()) { logger.info(() -> "Using CRT HTTP client"); AwsCrtAsyncHttpClient.Builder builder = AwsCrtAsyncHttpClient.builder(); if (config.readBufferSizeInMb() != null) { builder.readBufferSizeInBytes(config.readBufferSizeInMb() * MB); } if (config.maxConcurrency() != null) { builder.maxConcurrency(config.maxConcurrency()); } return builder; } NettyNioAsyncHttpClient.Builder builder = NettyNioAsyncHttpClient.builder(); if (config.connectionAcquisitionTimeoutInSec() != null) { Duration connAcqTimeout = Duration.ofSeconds(config.connectionAcquisitionTimeoutInSec()); builder.connectionAcquisitionTimeout(connAcqTimeout); } if (config.maxConcurrency() != null) { builder.maxConcurrency(config.maxConcurrency()); } return builder; } protected abstract void sendOneRequest(List<Double> latencies) throws Exception; protected abstract long contentLength() throws Exception; @Override public void run() { try { warmUp(); doRunBenchmark(); } catch (Exception e) { logger.error(() -> "Exception occurred", e); } finally { cleanup(); } } private void cleanup() { s3Client.close(); s3AsyncClient.close(); } private void warmUp() throws Exception { logger.info(() -> "Starting to warm up"); for (int i = 0; i < 3; i++) { sendOneRequest(new ArrayList<>()); Thread.sleep(500); } logger.info(() -> "Ending warm up"); } private void doRunBenchmark() throws Exception { List<Double> metrics = new ArrayList<>(); for (int i = 0; i < iteration; i++) { sendOneRequest(metrics); } printOutResult(metrics, "S3 Async client", contentLength()); } }
2,737
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerBenchmark.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.s3benchmarks; import java.util.function.Supplier; /** * Factory to create the benchmark */ @FunctionalInterface public interface TransferManagerBenchmark { /** * The benchmark method to run */ void run(); static TransferManagerBenchmark v2Download(TransferManagerBenchmarkConfig config) { return new TransferManagerDownloadBenchmark(config); } static TransferManagerBenchmark downloadDirectory(TransferManagerBenchmarkConfig config) { return new TransferManagerDownloadDirectoryBenchmark(config); } static TransferManagerBenchmark v2Upload(TransferManagerBenchmarkConfig config) { return new TransferManagerUploadBenchmark(config); } static TransferManagerBenchmark uploadDirectory(TransferManagerBenchmarkConfig config) { return new TransferManagerUploadDirectoryBenchmark(config); } static TransferManagerBenchmark copy(TransferManagerBenchmarkConfig config) { return new TransferManagerCopyBenchmark(config); } static TransferManagerBenchmark v1Download(TransferManagerBenchmarkConfig config) { return new V1TransferManagerDownloadBenchmark(config); } static TransferManagerBenchmark v1DownloadDirectory(TransferManagerBenchmarkConfig config) { return new V1TransferManagerDownloadDirectoryBenchmark(config); } static TransferManagerBenchmark v1Upload(TransferManagerBenchmarkConfig config) { return new V1TransferManagerUploadBenchmark(config); } static TransferManagerBenchmark v1UploadDirectory(TransferManagerBenchmarkConfig config) { return new V1TransferManagerUploadDirectoryBenchmark(config); } static TransferManagerBenchmark v1Copy(TransferManagerBenchmarkConfig config) { return new V1TransferManagerCopyBenchmark(config); } default <T> TimedResult<T> runWithTime(Supplier<T> toRun) { long start = System.currentTimeMillis(); T result = toRun.get(); long end = System.currentTimeMillis(); return new TimedResult<>(result, (end - start) / 1000.0); } final class TimedResult<T> { private final Double latency; private final T result; public TimedResult(T result, Double latency) { this.result = result; this.latency = latency; } public Double latency() { return latency; } public T result() { return result; } } }
2,738
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/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.http; import java.nio.ByteBuffer; import java.util.Optional; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; public class EmptyPublisher implements SdkHttpContentPublisher { @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { subscriber.onSubscribe(new EmptySubscription(subscriber)); } @Override public Optional<Long> contentLength() { return Optional.of(0L); } private static class EmptySubscription implements Subscription { private final Subscriber subscriber; private volatile boolean done; EmptySubscription(Subscriber subscriber) { this.subscriber = subscriber; } @Override public void request(long l) { if (!done) { done = true; if (l <= 0) { this.subscriber.onError(new IllegalArgumentException("Demand must be positive")); } else { this.subscriber.onComplete(); } } } @Override public void cancel() { done = true; } } }
2,739
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/SimpleHttpContentPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.nio.ByteBuffer; import java.util.Optional; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.utils.IoUtils; /** * Implementation of {@link SdkHttpContentPublisher} that provides all it's data at once. Useful for * non streaming operations that are already marshalled into memory. */ @SdkInternalApi public final class SimpleHttpContentPublisher implements SdkHttpContentPublisher { private final ByteBuffer content; private final int length; public SimpleHttpContentPublisher(SdkHttpFullRequest request) { this.content = request.contentStreamProvider().map(p -> invokeSafely(() -> ByteBuffer.wrap(IoUtils.toByteArray(p.newStream())))) .orElseGet(() -> ByteBuffer.wrap(new byte[0])); this.length = content.remaining(); } public SimpleHttpContentPublisher(byte[] body) { this(ByteBuffer.wrap(body)); } public SimpleHttpContentPublisher(ByteBuffer byteBuffer) { this.content = byteBuffer; this.length = byteBuffer.remaining(); } @Override public Optional<Long> contentLength() { return Optional.of((long) length); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { s.onSubscribe(new SubscriptionImpl(s)); } private class SubscriptionImpl implements Subscription { private boolean running = true; private final Subscriber<? super ByteBuffer> s; private SubscriptionImpl(Subscriber<? super ByteBuffer> s) { this.s = s; } @Override public void request(long n) { if (running) { running = false; if (n <= 0) { s.onError(new IllegalArgumentException("Demand must be positive")); } else { s.onNext(content); s.onComplete(); } } } @Override public void cancel() { running = false; } } }
2,740
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/SdkAsyncHttpClientH1TestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE; import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE; import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN; import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.util.SelfSignedCertificate; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; /** * A set of tests validating that the functionality implemented by a {@link SdkAsyncHttpClient} for HTTP/1 requests * * This is used by an HTTP plugin implementation by extending this class and implementing the abstract methods to provide this * suite with a testable HTTP client implementation. */ public abstract class SdkAsyncHttpClientH1TestSuite { private Server server; private SdkAsyncHttpClient client; protected abstract SdkAsyncHttpClient setupClient(); @BeforeEach public void setup() throws Exception { server = new Server(); server.init(); this.client = setupClient(); } @AfterEach public void teardown() throws InterruptedException { if (server != null) { server.shutdown(); } if (client != null) { client.close(); } server = null; } @Test public void connectionReceiveServerErrorStatusShouldNotReuseConnection() { server.return500OnFirstRequest = true; server.closeConnection = false; HttpTestUtils.sendGetRequest(server.port(), client).join(); HttpTestUtils.sendGetRequest(server.port(), client).join(); assertThat(server.channels.size()).isEqualTo(2); } @Test public void connectionReceiveOkStatusShouldReuseConnection() throws Exception { server.return500OnFirstRequest = false; server.closeConnection = false; HttpTestUtils.sendGetRequest(server.port(), client).join(); // The request-complete-future does not await the channel-release-future // Wait a small amount to allow the channel release to complete Thread.sleep(100); HttpTestUtils.sendGetRequest(server.port(), client).join(); assertThat(server.channels.size()).isEqualTo(1); } @Test public void connectionReceiveCloseHeaderShouldNotReuseConnection() throws InterruptedException { server.return500OnFirstRequest = false; server.closeConnection = true; HttpTestUtils.sendGetRequest(server.port(), client).join(); Thread.sleep(1000); HttpTestUtils.sendGetRequest(server.port(), client).join(); assertThat(server.channels.size()).isEqualTo(2); } @Test public void headRequestResponsesHaveNoPayload() { byte[] responseData = HttpTestUtils.sendHeadRequest(server.port(), client).join(); // The SDK core differentiates between NO data and ZERO bytes of data. Core expects it to be NO data, not ZERO bytes of // data for head requests. assertThat(responseData).isNull(); } @Test public void naughtyHeaderCharactersDoNotGetToServer() { String naughtyHeader = "foo\r\nbar"; assertThatThrownBy(() -> HttpTestUtils.sendRequest(client, SdkHttpFullRequest.builder() .uri(URI.create("https://localhost:" + server.port())) .method(SdkHttpMethod.POST) .appendHeader("h", naughtyHeader) .build()) .join()) .hasCauseInstanceOf(Exception.class); } @Test public void connectionsArePooledByHostAndPort() throws InterruptedException { HttpTestUtils.sendRequest(client, SdkHttpFullRequest.builder() .uri(URI.create("https://127.0.0.1:" + server.port() + "/foo?foo")) .method(SdkHttpMethod.GET) .build()) .join(); Thread.sleep(1_000); HttpTestUtils.sendRequest(client, SdkHttpFullRequest.builder() .uri(URI.create("https://127.0.0.1:" + server.port() + "/bar?bar")) .method(SdkHttpMethod.GET) .build()) .join(); assertThat(server.channels.size()).isEqualTo(1); } private static class Server extends ChannelInitializer<Channel> { private static final byte[] CONTENT = "helloworld".getBytes(StandardCharsets.UTF_8); private ServerBootstrap bootstrap; private ServerSocketChannel serverSock; private List<Channel> channels = new ArrayList<>(); private final NioEventLoopGroup group = new NioEventLoopGroup(); private SslContext sslCtx; private boolean return500OnFirstRequest; private boolean closeConnection; private volatile HttpRequest lastRequestReceived; public void init() throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); bootstrap = new ServerBootstrap() .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)) .group(group) .childHandler(this); serverSock = (ServerSocketChannel) bootstrap.bind(0).sync().channel(); } public void shutdown() throws InterruptedException { group.shutdownGracefully().await(); serverSock.close(); } public int port() { return serverSock.localAddress().getPort(); } @Override protected void initChannel(Channel ch) { channels.add(ch); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(sslCtx.newHandler(ch.alloc())); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new BehaviorTestChannelHandler()); } private class BehaviorTestChannelHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { lastRequestReceived = (HttpRequest) msg; HttpResponseStatus status; if (ctx.channel().equals(channels.get(0)) && return500OnFirstRequest) { status = INTERNAL_SERVER_ERROR; } else { status = OK; } FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.wrappedBuffer(CONTENT)); response.headers() .set(CONTENT_TYPE, TEXT_PLAIN) .setInt(CONTENT_LENGTH, response.content().readableBytes()); if (closeConnection) { response.headers().set(CONNECTION, CLOSE); } ctx.writeAndFlush(response); } } } } }
2,741
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/RecordingNetworkTrafficListener.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; /** * Simple implementation of {@link WiremockNetworkTrafficListener} to record all requests received as a string for later * verification. */ public class RecordingNetworkTrafficListener implements WiremockNetworkTrafficListener { private final StringBuilder requests = new StringBuilder(); @Override public void opened(Socket socket) { } @Override public void incoming(Socket socket, ByteBuffer byteBuffer) { requests.append(StandardCharsets.UTF_8.decode(byteBuffer)); } @Override public void outgoing(Socket socket, ByteBuffer byteBuffer) { } @Override public void closed(Socket socket) { } public void reset() { requests.setLength(0); } public StringBuilder requests() { return requests; } }
2,742
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/HttpProxyTestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.net.URISyntaxException; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.http.proxy.ProxyConfigCommonTestData; import software.amazon.awssdk.http.proxy.TestProxySetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.StringUtils; public abstract class HttpProxyTestSuite { public static final String HTTP = "http"; public static final String HTTPS = "https"; private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); public static Stream<Arguments> proxyConfigurationSetting() { return ProxyConfigCommonTestData.proxyConfigurationSetting(); } static void setSystemProperties(List<Pair<String, String>> settingsPairs, String protocol) { settingsPairs.stream() .filter(p -> StringUtils.isNotBlank(p.left())) .forEach(settingsPair -> System.setProperty(String.format(settingsPair.left(), protocol), settingsPair.right())); } static void setEnvironmentProperties(List<Pair<String, String>> settingsPairs, String protocol) { settingsPairs.forEach(settingsPair -> ENVIRONMENT_VARIABLE_HELPER.set(String.format(settingsPair.left(), protocol), settingsPair.right())); } @BeforeEach void setUp() { Stream.of("http", "https") .forEach(protocol -> Stream.of("%s.proxyHost", "%s.proxyPort", "%s.nonProxyHosts", "%s.proxyUser", "%s.proxyPassword") .forEach(property -> System.clearProperty(String.format(property, protocol)))); ENVIRONMENT_VARIABLE_HELPER.reset(); } @ParameterizedTest(name = "{index} -{0} useSystemProperty {4} useEnvironmentVariable {5} userSetProxy {3} then expected " + "is {6}") @MethodSource("proxyConfigurationSetting") void givenLocalSettingForHttpThenCorrectProxyConfig(String testCaseName, List<Pair<String, String>> systemSettingsPair, List<Pair<String, String>> envSystemSetting, TestProxySetting userSetProxySettings, Boolean useSystemProperty, Boolean useEnvironmentVariable, TestProxySetting expectedProxySettings) throws URISyntaxException { setSystemProperties(systemSettingsPair, HTTP); setEnvironmentProperties(envSystemSetting, HTTP); assertProxyConfiguration(userSetProxySettings, expectedProxySettings, useSystemProperty, useEnvironmentVariable, HTTP); } @ParameterizedTest(name = "{index} -{0} useSystemProperty {4} useEnvironmentVariable {5} userSetProxy {3} then expected " + "is {6}") @MethodSource("proxyConfigurationSetting") void givenLocalSettingForHttpsThenCorrectProxyConfig( String testCaseName, List<Pair<String, String>> systemSettingsPair, List<Pair<String, String>> envSystemSetting, TestProxySetting userSetProxySettings, Boolean useSystemProperty, Boolean useEnvironmentVariable, TestProxySetting expectedProxySettings) throws URISyntaxException { setSystemProperties(systemSettingsPair, HTTPS); setEnvironmentProperties(envSystemSetting, HTTPS); assertProxyConfiguration(userSetProxySettings, expectedProxySettings, useSystemProperty, useEnvironmentVariable, HTTPS); } protected abstract void assertProxyConfiguration(TestProxySetting userSetProxySettings, TestProxySetting expectedProxySettings, Boolean useSystemProperty, Boolean useEnvironmentVariable, String protocol) throws URISyntaxException; }
2,743
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/SdkHttpClientTestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.absent; import static com.github.tomakehurst.wiremock.client.WireMock.any; 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.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; 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.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.common.FatalStartupException; import com.github.tomakehurst.wiremock.http.RequestMethod; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Random; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Logger; /** * A set of tests validating that the functionality implemented by a {@link SdkHttpClient}. * * This is used by an HTTP plugin implementation by extending this class and implementing the abstract methods to provide this * suite with a testable HTTP client implementation. */ @RunWith(MockitoJUnitRunner.class) public abstract class SdkHttpClientTestSuite { private static final Logger LOG = Logger.loggerFor(SdkHttpClientTestSuite.class); private static final ConnectionCountingTrafficListener CONNECTION_COUNTER = new ConnectionCountingTrafficListener(); @Rule public WireMockRule mockServer = createWireMockRule(); private final Random rng = new Random(); @Test public void supportsResponseCode200() throws Exception { testForResponseCode(HttpURLConnection.HTTP_OK); } @Test public void supportsResponseCode200Head() throws Exception { // HEAD is special due to closing of the connection immediately and streams are null testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN, SdkHttpMethod.HEAD); } @Test public void supportsResponseCode202() throws Exception { testForResponseCode(HttpURLConnection.HTTP_ACCEPTED); } @Test public void supportsResponseCode403() throws Exception { testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN); } @Test public void supportsResponseCode403Head() throws Exception { testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN, SdkHttpMethod.HEAD); } @Test public void supportsResponseCode301() throws Exception { testForResponseCode(HttpURLConnection.HTTP_MOVED_PERM); } @Test public void supportsResponseCode302() throws Exception { testForResponseCode(HttpURLConnection.HTTP_MOVED_TEMP); } @Test public void supportsResponseCode500() throws Exception { testForResponseCode(HttpURLConnection.HTTP_INTERNAL_ERROR); } @Test public void validatesHttpsCertificateIssuer() throws Exception { SdkHttpClient client = createSdkHttpClient(); SdkHttpFullRequest request = mockSdkRequest("https://localhost:" + mockServer.httpsPort(), SdkHttpMethod.POST); assertThatThrownBy(client.prepareRequest(HttpExecuteRequest.builder().request(request).build())::call) .isInstanceOf(SSLHandshakeException.class); } @Test public void connectionPoolingWorks() throws Exception { int initialOpenedConnections = CONNECTION_COUNTER.openedConnections(); SdkHttpClientOptions httpClientOptions = new SdkHttpClientOptions(); httpClientOptions.trustAll(true); SdkHttpClient client = createSdkHttpClient(httpClientOptions); stubForMockRequest(200); for (int i = 0; i < 5; i++) { SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), SdkHttpMethod.POST); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider().orElse(null)) .build()) .call(); response.responseBody().ifPresent(IoUtils::drainInputStream); } assertThat(CONNECTION_COUNTER.openedConnections()).isEqualTo(initialOpenedConnections + 1); } @Test public void connectionsAreNotReusedOn5xxErrors() throws Exception { int initialOpenedConnections = CONNECTION_COUNTER.openedConnections(); SdkHttpClientOptions httpClientOptions = new SdkHttpClientOptions(); httpClientOptions.trustAll(true); SdkHttpClient client = createSdkHttpClient(httpClientOptions); stubForMockRequest(503); for (int i = 0; i < 5; i++) { SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), SdkHttpMethod.POST); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider().orElse(null)) .build()) .call(); response.responseBody().ifPresent(IoUtils::drainInputStream); } assertThat(CONNECTION_COUNTER.openedConnections()).isEqualTo(initialOpenedConnections + 5); } @Test public void testCustomTlsTrustManager() throws Exception { WireMockServer selfSignedServer = HttpTestUtils.createSelfSignedServer(); TrustManagerFactory managerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); managerFactory.init(HttpTestUtils.getSelfSignedKeyStore()); SdkHttpClientOptions httpClientOptions = new SdkHttpClientOptions(); httpClientOptions.tlsTrustManagersProvider(managerFactory::getTrustManagers); selfSignedServer.start(); try { SdkHttpClient client = createSdkHttpClient(httpClientOptions); SdkHttpFullRequest request = mockSdkRequest("https://localhost:" + selfSignedServer.httpsPort(), SdkHttpMethod.POST); client.prepareRequest(HttpExecuteRequest.builder().request(request).build()).call(); } finally { selfSignedServer.stop(); } } @Test public void testTrustAllWorks() throws Exception { SdkHttpClientOptions httpClientOptions = new SdkHttpClientOptions(); httpClientOptions.trustAll(true); testForResponseCodeUsingHttps(createSdkHttpClient(httpClientOptions), HttpURLConnection.HTTP_OK); } @Test public void testCustomTlsTrustManagerAndTrustAllFails() throws Exception { SdkHttpClientOptions httpClientOptions = new SdkHttpClientOptions(); httpClientOptions.tlsTrustManagersProvider(() -> new TrustManager[0]); httpClientOptions.trustAll(true); assertThatThrownBy(() -> createSdkHttpClient(httpClientOptions)).isInstanceOf(IllegalArgumentException.class); } protected void testForResponseCode(int returnCode) throws Exception { testForResponseCode(returnCode, SdkHttpMethod.POST); } private void testForResponseCode(int returnCode, SdkHttpMethod method) throws Exception { SdkHttpClient client = createSdkHttpClient(); stubForMockRequest(returnCode); SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), method); HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider() .orElse(null)) .build()) .call(); validateResponse(rsp, returnCode, method); } protected void testForResponseCodeUsingHttps(SdkHttpClient client, int returnCode) throws Exception { SdkHttpMethod sdkHttpMethod = SdkHttpMethod.POST; stubForMockRequest(returnCode); SdkHttpFullRequest req = mockSdkRequest("https://localhost:" + mockServer.httpsPort(), sdkHttpMethod); HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider() .orElse(null)) .build()) .call(); validateResponse(rsp, returnCode, sdkHttpMethod); } protected void stubForMockRequest(int returnCode) { ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(returnCode) .withHeader("Some-Header", "With Value") .withBody("hello"); if (returnCode >= 300 && returnCode <= 399) { responseBuilder.withHeader("Location", "Some New Location"); } mockServer.stubFor(any(urlPathEqualTo("/")).willReturn(responseBuilder)); } private void validateResponse(HttpExecuteResponse response, int returnCode, SdkHttpMethod method) throws IOException { RequestMethod requestMethod = RequestMethod.fromString(method.name()); RequestPatternBuilder patternBuilder = RequestPatternBuilder.newRequestPattern(requestMethod, urlMatching("/")) .withHeader("Host", containing("localhost")) .withHeader("User-Agent", equalTo("hello-world!")); if (method == SdkHttpMethod.HEAD) { patternBuilder.withRequestBody(absent()); } else { patternBuilder.withRequestBody(equalTo("Body")); } mockServer.verify(1, patternBuilder); if (method == SdkHttpMethod.HEAD) { assertThat(response.responseBody()).isEmpty(); } else { assertThat(IoUtils.toUtf8String(response.responseBody().orElse(null))).isEqualTo("hello"); } assertThat(response.httpResponse().firstMatchingHeader("Some-Header")).contains("With Value"); assertThat(response.httpResponse().statusCode()).isEqualTo(returnCode); mockServer.resetMappings(); } protected SdkHttpFullRequest mockSdkRequest(String uriString, SdkHttpMethod method) { URI uri = URI.create(uriString); SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder() .uri(uri) .method(method) .putHeader("Host", uri.getHost()) .putHeader("User-Agent", "hello-world!"); if (method != SdkHttpMethod.HEAD) { requestBuilder.contentStreamProvider(() -> new ByteArrayInputStream("Body".getBytes(StandardCharsets.UTF_8))); } return requestBuilder.build(); } /** * {@link #createSdkHttpClient(SdkHttpClientOptions)} with default options. */ protected final SdkHttpClient createSdkHttpClient() { return createSdkHttpClient(new SdkHttpClientOptions()); } /** * Implemented by a child class to create an HTTP client to validate based on the provided options. */ protected abstract SdkHttpClient createSdkHttpClient(SdkHttpClientOptions options); /** * The options that should be considered when creating the client via {@link #createSdkHttpClient(SdkHttpClientOptions)}. */ protected static final class SdkHttpClientOptions { private TlsTrustManagersProvider tlsTrustManagersProvider = null; private boolean trustAll = false; public TlsTrustManagersProvider tlsTrustManagersProvider() { return tlsTrustManagersProvider; } public void tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) { this.tlsTrustManagersProvider = tlsTrustManagersProvider; } public boolean trustAll() { return trustAll; } public void trustAll(boolean trustAll) { this.trustAll = trustAll; } } private WireMockRule createWireMockRule() { int maxAttempts = 5; for (int i = 0; i < maxAttempts; ++i) { try { return new WireMockRule(wireMockConfig().dynamicPort() .dynamicHttpsPort() .networkTrafficListener(CONNECTION_COUNTER)); } catch (FatalStartupException e) { int attemptNum = i + 1; LOG.debug(() -> "Was not able to start WireMock server. Attempt " + attemptNum, e); if (attemptNum != maxAttempts) { try { long sleepMillis = 1_000L + rng.nextInt(1_000); Thread.sleep(sleepMillis); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException("Backoff interrupted", ie); } } } } throw new RuntimeException("Unable to setup WireMock rule"); } }
2,744
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/ConnectionCountingTrafficListener.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener; import java.io.ByteArrayOutputStream; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.utils.BinaryUtils; public class ConnectionCountingTrafficListener implements WiremockNetworkTrafficListener { private final Map<Socket, ByteArrayOutputStream> sockets = new ConcurrentHashMap<>(); @Override public void opened(Socket socket) { sockets.put(socket, new ByteArrayOutputStream()); } @Override public void incoming(Socket socket, ByteBuffer bytes) { invokeSafely(() -> sockets.get(socket).write(BinaryUtils.copyBytesFrom(bytes.asReadOnlyBuffer()))); } @Override public void outgoing(Socket socket, ByteBuffer bytes) { } @Override public void closed(Socket socket) { } public int openedConnections() { int count = 0; for (ByteArrayOutputStream data : sockets.values()) { byte[] bytes = data.toByteArray(); try { if (new String(bytes, StandardCharsets.UTF_8).startsWith("POST /__admin/mappings")) { // Admin-related stuff, don't count it continue; } // Not admin-related stuff, so count it ++count; } catch (RuntimeException e) { // Could not decode, so it's not admin-related stuff (which uses JSON and can always be decoded) ++count; } } return count; } }
2,745
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/SdkHttpClientDefaultTestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.absent; import static com.github.tomakehurst.wiremock.client.WireMock.any; 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.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.http.RequestMethod; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.nio.charset.StandardCharsets; import javax.net.ssl.SSLHandshakeException; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.utils.IoUtils; /** * A set of tests validating that the functionality implemented by a {@link SdkHttpClient}. * * This is used by an HTTP plugin implementation by extending this class and implementing the abstract methods to provide this * suite with a testable HTTP client implementation. */ @RunWith(MockitoJUnitRunner.class) public abstract class SdkHttpClientDefaultTestSuite { @Rule public WireMockRule mockServer = new WireMockRule(wireMockConfig().dynamicPort().dynamicHttpsPort()); @Test public void supportsResponseCode200() throws Exception { testForResponseCode(HttpURLConnection.HTTP_OK); } @Test public void supportsResponseCode200Head() throws Exception { // HEAD is special due to closing of the connection immediately and streams are null testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN, SdkHttpMethod.HEAD); } @Test public void supportsResponseCode202() throws Exception { testForResponseCode(HttpURLConnection.HTTP_ACCEPTED); } @Test public void supportsResponseCode403() throws Exception { testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN); } @Test public void supportsResponseCode403Head() throws Exception { testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN, SdkHttpMethod.HEAD); } @Test public void supportsResponseCode301() throws Exception { testForResponseCode(HttpURLConnection.HTTP_MOVED_PERM); } @Test public void supportsResponseCode302() throws Exception { testForResponseCode(HttpURLConnection.HTTP_MOVED_TEMP); } @Test public void supportsResponseCode500() throws Exception { testForResponseCode(HttpURLConnection.HTTP_INTERNAL_ERROR); } @Test public void validatesHttpsCertificateIssuer() throws Exception { SdkHttpClient client = createSdkHttpClient(); SdkHttpFullRequest request = mockSdkRequest("https://localhost:" + mockServer.httpsPort(), SdkHttpMethod.POST); assertThatThrownBy(client.prepareRequest(HttpExecuteRequest.builder().request(request).build())::call) .isInstanceOf(SSLHandshakeException.class); } private void testForResponseCode(int returnCode) throws Exception { testForResponseCode(returnCode, SdkHttpMethod.POST); } private void testForResponseCode(int returnCode, SdkHttpMethod method) throws Exception { SdkHttpClient client = createSdkHttpClient(); stubForMockRequest(returnCode); SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), method); HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider() .orElse(null)) .build()) .call(); validateResponse(rsp, returnCode, method); } protected void testForResponseCodeUsingHttps(SdkHttpClient client, int returnCode) throws Exception { SdkHttpMethod sdkHttpMethod = SdkHttpMethod.POST; stubForMockRequest(returnCode); SdkHttpFullRequest req = mockSdkRequest("https://localhost:" + mockServer.httpsPort(), sdkHttpMethod); HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider() .orElse(null)) .build()) .call(); validateResponse(rsp, returnCode, sdkHttpMethod); } private void stubForMockRequest(int returnCode) { ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(returnCode) .withHeader("Some-Header", "With Value") .withBody("hello"); if (returnCode >= 300 && returnCode <= 399) { responseBuilder.withHeader("Location", "Some New Location"); } mockServer.stubFor(any(urlPathEqualTo("/")).willReturn(responseBuilder)); } private void validateResponse(HttpExecuteResponse response, int returnCode, SdkHttpMethod method) throws IOException { RequestMethod requestMethod = RequestMethod.fromString(method.name()); RequestPatternBuilder patternBuilder = RequestPatternBuilder.newRequestPattern(requestMethod, urlMatching("/")) .withHeader("Host", containing("localhost")) .withHeader("User-Agent", equalTo("hello-world!")); if (method == SdkHttpMethod.HEAD) { patternBuilder.withRequestBody(absent()); } else { patternBuilder.withRequestBody(equalTo("Body")); } mockServer.verify(1, patternBuilder); if (method == SdkHttpMethod.HEAD) { assertThat(response.responseBody()).isEmpty(); } else { assertThat(IoUtils.toUtf8String(response.responseBody().orElse(null))).isEqualTo("hello"); } assertThat(response.httpResponse().firstMatchingHeader("Some-Header")).contains("With Value"); assertThat(response.httpResponse().statusCode()).isEqualTo(returnCode); mockServer.resetMappings(); } private SdkHttpFullRequest mockSdkRequest(String uriString, SdkHttpMethod method) { URI uri = URI.create(uriString); SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder() .uri(uri) .method(method) .putHeader("Host", uri.getHost()) .putHeader("User-Agent", "hello-world!"); if (method != SdkHttpMethod.HEAD) { requestBuilder.contentStreamProvider(() -> new ByteArrayInputStream("Body".getBytes(StandardCharsets.UTF_8))); } return requestBuilder.build(); } /** * Implemented by a child class to create an HTTP client to validate, without any extra options. */ protected abstract SdkHttpClient createSdkHttpClient(); }
2,746
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/HttpTestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static java.nio.charset.StandardCharsets.UTF_8; import static software.amazon.awssdk.utils.StringUtils.isBlank; import com.github.tomakehurst.wiremock.WireMockServer; import io.reactivex.Flowable; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import java.nio.ByteBuffer; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.utils.BinaryUtils; public class HttpTestUtils { private HttpTestUtils() { } public static WireMockServer createSelfSignedServer() { URL selfSignedJks = SdkHttpClientTestSuite.class.getResource("/selfSigned.jks"); return new WireMockServer(wireMockConfig() .dynamicHttpsPort() .keystorePath(selfSignedJks.toString()) .keystorePassword("changeit") .keyManagerPassword("changeit") .keystoreType("jks") ); } public static KeyStore getSelfSignedKeyStore() throws Exception { URL selfSignedJks = SdkHttpClientTestSuite.class.getResource("/selfSigned.jks"); KeyStore keyStore = KeyStore.getInstance("jks"); try (InputStream stream = selfSignedJks.openStream()) { keyStore.load(stream, "changeit".toCharArray()); } return keyStore; } public static CompletableFuture<byte[]> sendGetRequest(int serverPort, SdkAsyncHttpClient client) { return sendRequest(serverPort, client, SdkHttpMethod.GET); } public static CompletableFuture<byte[]> sendHeadRequest(int serverPort, SdkAsyncHttpClient client) { return sendRequest(serverPort, client, SdkHttpMethod.HEAD); } private static CompletableFuture<byte[]> sendRequest(int serverPort, SdkAsyncHttpClient client, SdkHttpMethod httpMethod) { SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(httpMethod) .protocol("https") .host("127.0.0.1") .port(serverPort) .build(); return sendRequest(client, request); } public static CompletableFuture<byte[]> sendRequest(SdkAsyncHttpClient client, SdkHttpFullRequest request) { ByteArrayOutputStream responsePayload = new ByteArrayOutputStream(); AtomicBoolean responsePayloadReceived = new AtomicBoolean(false); return client.execute(AsyncExecuteRequest.builder() .responseHandler(new SdkAsyncHttpResponseHandler() { @Override public void onHeaders(SdkHttpResponse headers) { } @Override public void onStream(Publisher<ByteBuffer> stream) { Flowable.fromPublisher(stream).forEach(b -> { responsePayloadReceived.set(true); responsePayload.write(BinaryUtils.copyAllBytesFrom(b)); }); } @Override public void onError(Throwable error) { } }) .request(request) .requestContentPublisher(new EmptyPublisher()) .build()) .thenApply(v -> responsePayloadReceived.get() ? responsePayload.toByteArray() : null); } public static SdkHttpContentPublisher createProvider(String body) { Stream<ByteBuffer> chunks = splitStringBySize(body).stream() .map(chunk -> ByteBuffer.wrap(chunk.getBytes(UTF_8))); return new SdkHttpContentPublisher() { @Override public Optional<Long> contentLength() { return Optional.of(Long.valueOf(body.length())); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { chunks.forEach(s::onNext); s.onComplete(); } @Override public void cancel() { } }); } }; } public static Collection<String> splitStringBySize(String str) { if (isBlank(str)) { return Collections.emptyList(); } ArrayList<String> split = new ArrayList<>(); for (int i = 0; i <= str.length() / 1000; i++) { split.add(str.substring(i * 1000, Math.min((i + 1) * 1000, str.length()))); } return split; } }
2,747
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/RecordingResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Publisher; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.http.async.SimpleSubscriber; import software.amazon.awssdk.metrics.MetricCollector; public final class RecordingResponseHandler implements SdkAsyncHttpResponseHandler { private final List<SdkHttpResponse> responses = new ArrayList<>(); private final StringBuilder bodyParts = new StringBuilder(); private final CompletableFuture<Void> completeFuture = new CompletableFuture<>(); private final MetricCollector collector = MetricCollector.create("test"); @Override public void onHeaders(SdkHttpResponse response) { responses.add(response); } @Override public void onStream(Publisher<ByteBuffer> publisher) { publisher.subscribe(new SimpleSubscriber(byteBuffer -> { byte[] b = new byte[byteBuffer.remaining()]; byteBuffer.duplicate().get(b); bodyParts.append(new String(b, StandardCharsets.UTF_8)); }) { @Override public void onError(Throwable t) { completeFuture.completeExceptionally(t); } @Override public void onComplete() { completeFuture.complete(null); } }); } @Override public void onError(Throwable error) { completeFuture.completeExceptionally(error); } public String fullResponseAsString() { return bodyParts.toString(); } public List<SdkHttpResponse> responses() { return responses; } public StringBuilder bodyParts() { return bodyParts; } public CompletableFuture<Void> completeFuture() { return completeFuture; } public MetricCollector collector() { return collector; } }
2,748
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/proxy/TestProxySetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.proxy; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public class TestProxySetting { private Integer port = 0; private String host; private String userName; private String password; private Set<String> nonProxyHosts = new HashSet<>(); @Override public String toString() { return "TestProxySetting{" + "port=" + port + ", host='" + host + '\'' + ", userName='" + userName + '\'' + ", password='" + password + '\'' + ", nonProxyHosts=" + nonProxyHosts + '}' ; } public Integer getPort() { return port; } public String getHost() { return host; } public String getUserName() { return userName; } public String getPassword() { return password; } public Set<String> getNonProxyHosts() { return Collections.unmodifiableSet(nonProxyHosts); } public TestProxySetting port(Integer port) { this.port = port; return this; } public TestProxySetting host(String host) { this.host = host; return this; } public TestProxySetting userName(String userName) { this.userName = userName; return this; } public TestProxySetting password(String password) { this.password = password; return this; } public TestProxySetting nonProxyHost(String... nonProxyHosts) { this.nonProxyHosts = nonProxyHosts != null ? Arrays.stream(nonProxyHosts) .collect(Collectors.toSet()) : new HashSet<>(); return this; } }
2,749
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/proxy/ProxyConfigCommonTestData.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.proxy; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.stream.Stream; import org.junit.jupiter.params.provider.Arguments; import software.amazon.awssdk.utils.Pair; public final class ProxyConfigCommonTestData { public static final String SYSTEM_PROPERTY_HOST = "systemProperty.com"; public static final String SYSTEM_PROPERTY_PORT_NUMBER = "2222"; public static final String SYSTEM_PROPERTY_NON_PROXY = "systemPropertyNonProxy.com".toLowerCase(Locale.US); public static final String SYSTEM_PROPERTY_USER = "systemPropertyUserOne"; public static final String SYSTEM_PROPERTY_PASSWORD = "systemPropertyPassword"; public static final String ENV_VARIABLE_USER = "envUserOne"; public static final String ENV_VARIABLE_PASSWORD = "envPassword"; public static final String ENVIRONMENT_HOST = "environmentVariable.com".toLowerCase(Locale.US); public static final String ENVIRONMENT_VARIABLE_PORT_NUMBER = "3333"; public static final String ENVIRONMENT_VARIABLE_NON_PROXY = "environmentVariableNonProxy".toLowerCase(Locale.US); public static final String USER_HOST_ON_BUILDER = "proxyBuilder.com"; public static final int USER_PORT_NUMBER_ON_BUILDER = 9999; public static final String USER_USERNAME_ON_BUILDER = "proxyBuilderUser"; public static final String USER_PASSWORD_ON_BUILDER = "proxyBuilderPassword"; public static final String USER_NONPROXY_ON_BUILDER = "proxyBuilderNonProxy.com".toLowerCase(Locale.US); private ProxyConfigCommonTestData() { } public static Stream<Arguments> proxyConfigurationSetting() { return Stream.of( Arguments.of( "Provided system and environment variable when configured default setting then uses System property", systemPropertySettings(), environmentSettings(), new TestProxySetting(), null, null, getSystemPropertyProxySettings()), Arguments.of( "Provided system and environment variable when Host and port used from Builder then resolved Poxy " + "config uses User password from System setting", systemPropertySettings(), environmentSettings(), new TestProxySetting().host("localhost").port(80), null, null, getSystemPropertyProxySettings().host("localhost" ).port(80)), Arguments.of( "Provided system and environment variable when configured user setting then uses User provider setting", systemPropertySettings(), environmentSettings(), getTestProxySettings(), null, null, getTestProxySettings()), Arguments.of( "Provided: System property settings and environment variables are set. " + "When: useEnvironmentVariable is set to \true. And: useSystemProperty is left at its default value. Then: The" + " proxy configuration gets resolved to " + "use system properties ", systemPropertySettings(), environmentSettings(), new TestProxySetting(), null, true, getSystemPropertyProxySettings()), Arguments.of( "Provided: System property settings and environment variables are set. " + "When: useEnvironmentVariable is set to true. And: useSystemProperty is set to false. Then: " + "The proxy configuration gets resolved to use environment variable values", systemPropertySettings(), environmentSettings(), new TestProxySetting(), false, true, getEnvironmentVariableProxySettings()), // No System Property only Environment variable set Arguments.of( "Provided with no system property and valid environment variables, " + "when using the default proxy builder, the proxy configuration is resolved to use environment variables.", Collections.singletonList(Pair.of("", "")), environmentSettings(), new TestProxySetting(), null, null, getEnvironmentVariableProxySettings()), Arguments.of( "Provided with no system property and valid environment variables, when using the host," + "port on builder , the proxy configuration is resolved to username and password of environment variables.", Collections.singletonList(Pair.of("", "")), environmentSettings(), new TestProxySetting().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER), null, true, getEnvironmentVariableProxySettings().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER)), Arguments.of( "Provided with no system property and valid environment variables, when using the host,port on builder" + " , the proxy configuration is resolved to Builder values.", Collections.singletonList(Pair.of("", "")), environmentSettings(), getTestProxySettings(), null, null, getTestProxySettings()), Arguments.of( "Provided environment variable and No System Property when default ProxyConfig then uses environment " + "variable ", Collections.singletonList(Pair.of("", "")), environmentSettings(), new TestProxySetting(), null, true, getEnvironmentVariableProxySettings()), Arguments.of( "Provided only environment variable when useSytemProperty set to true " + "then proxy resolved to environment", Collections.singletonList(Pair.of("", "")), environmentSettings(), null, true, null, getEnvironmentVariableProxySettings()), Arguments.of( "Provided only environment variable when useEnvironmentVariable set to false then proxy resolved " + "to null", Collections.singletonList(Pair.of("", "")), environmentSettings(), new TestProxySetting(), null, true, getEnvironmentVariableProxySettings()), // Only System Property and no Environment variable Arguments.of( "Provided system and no environment variable when default ProxyConfig then used System Proxy config", systemPropertySettings(), Collections.singletonList(Pair.of("", "")), null, null, null, getSystemPropertyProxySettings()), Arguments.of( "Provided system and no environment variable when host from builder then Host is resolved from builder", systemPropertySettings(), Collections.singletonList(Pair.of("", "")), new TestProxySetting().port(USER_PORT_NUMBER_ON_BUILDER).host(USER_HOST_ON_BUILDER), null, null, getSystemPropertyProxySettings().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER)), Arguments.of( "Provided system and no environment variable when user ProxyConfig on builder " + "then User Proxy resolved", systemPropertySettings(), Collections.singletonList(Pair.of("", "")), getTestProxySettings(), true, true, getTestProxySettings()), Arguments.of( "Provided system and no environment variable when useEnvironmentVariable then System property proxy resolved", systemPropertySettings(), Collections.singletonList(Pair.of("", "")), new TestProxySetting(), null, true, getSystemPropertyProxySettings()), Arguments.of( "Provided system and no environment variable " + "when useSystemProperty and useEnvironment set to false then resolved config is null ", systemPropertySettings(), Collections.singletonList(Pair.of("", "")), new TestProxySetting(), false, true, new TestProxySetting()), // when both system property and environment variable are null Arguments.of( "Provided no system property and no environment variable when default ProxyConfig " + "then no Proxy config resolved", Collections.singletonList(Pair.of("", "")), Collections.singletonList(Pair.of("", "")), new TestProxySetting(), null, null, new TestProxySetting()), Arguments.of( "Provided no system property and no environment variable when user ProxyConfig then user Proxy config resolved", Collections.singletonList(Pair.of("", "")), Collections.singletonList(Pair.of("", "")), new TestProxySetting().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER), null, null, new TestProxySetting().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER)), Arguments.of( "Provided no system property and no environment variable when user ProxyConfig " + "then user Proxy config resolved", Collections.singletonList(Pair.of("", "")), Collections.singletonList(Pair.of("", "")), getTestProxySettings(), null, null, getTestProxySettings()), Arguments.of( "Provided no system property and no environment variable when useSystemProperty and " + "useEnvironmentVariable set then resolved host is null ", Collections.singletonList(Pair.of("", "")), Collections.singletonList(Pair.of("", "")), null, true, true, new TestProxySetting()), // Incomplete Proxy setting in systemProperty and environment variable Arguments.of( "Given System property with No user name and Environment variable with user name " + "when Default proxy config then resolves proxy config with no user name same as System property", getSystemPropertiesWithNoUserName(), environmentSettingsWithNoPassword(), new TestProxySetting(), null, null, new TestProxySetting().host(SYSTEM_PROPERTY_HOST).port(Integer.parseInt(SYSTEM_PROPERTY_PORT_NUMBER)) .password(SYSTEM_PROPERTY_PASSWORD)), Arguments.of( "Given password in System property when Password present in system property " + "then proxy resolves to Builder password", getSystemPropertiesWithNoUserName(), environmentSettingsWithNoPassword(), new TestProxySetting().password("passwordFromBuilder"), null, null, getSystemPropertyProxySettings().password("passwordFromBuilder") .userName(null) .nonProxyHost(null)), Arguments.of( "Given partial System Property and partial Environment variables when Builder method with Host " + "and port only then Proxy config uses password from System property and no User name since System property" + " has none", getSystemPropertiesWithNoUserName(), environmentSettingsWithNoPassword(), new TestProxySetting().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER), null, null, getSystemPropertyProxySettings().host(USER_HOST_ON_BUILDER) .port(USER_PORT_NUMBER_ON_BUILDER) .userName(null) .nonProxyHost(null)), Arguments.of( "Given System Property and Environment variables when valid empty Proxy config on Builder then " + "Proxy config resolves to Proxy on builder.", systemPropertySettings(), environmentSettings(), getTestProxySettings(), null, null, getTestProxySettings()), Arguments.of( "Given partial system property and partial environment variable when User " + "set useEnvironmentVariable to true and default System property then default system property gets used.", getSystemPropertiesWithNoUserName(), environmentSettingsWithNoPassword(), new TestProxySetting(), null, true, getSystemPropertyProxySettings().nonProxyHost(null) .userName(null)), Arguments.of( "Given partial system property and partial environment variable when User " + "set useEnvironmentVariable and explicitly sets useSystemProperty to fals then only environment variable is " + "resolved", getSystemPropertiesWithNoUserName(), environmentSettingsWithNoPassword(), new TestProxySetting(), false, true, getEnvironmentVariableProxySettings().password(null)) ); } private static List<Pair<String, String>> getSystemPropertiesWithNoUserName() { return Arrays.asList( Pair.of("%s.proxyHost", SYSTEM_PROPERTY_HOST), Pair.of("%s.proxyPort", SYSTEM_PROPERTY_PORT_NUMBER), Pair.of("%s.proxyPassword", SYSTEM_PROPERTY_PASSWORD)); } private static TestProxySetting getTestProxySettings() { return new TestProxySetting().host(USER_HOST_ON_BUILDER) .port(USER_PORT_NUMBER_ON_BUILDER) .userName(USER_USERNAME_ON_BUILDER) .password(USER_PASSWORD_ON_BUILDER) .nonProxyHost(USER_NONPROXY_ON_BUILDER); } private static TestProxySetting getSystemPropertyProxySettings() { return new TestProxySetting().host(SYSTEM_PROPERTY_HOST) .port(Integer.parseInt(SYSTEM_PROPERTY_PORT_NUMBER)) .userName(SYSTEM_PROPERTY_USER) .password(SYSTEM_PROPERTY_PASSWORD) .nonProxyHost(SYSTEM_PROPERTY_NON_PROXY); } private static TestProxySetting getEnvironmentVariableProxySettings() { return new TestProxySetting().host(ENVIRONMENT_HOST) .port(Integer.parseInt(ENVIRONMENT_VARIABLE_PORT_NUMBER)) .userName(ENV_VARIABLE_USER) .password(ENV_VARIABLE_PASSWORD) .nonProxyHost(ENVIRONMENT_VARIABLE_NON_PROXY); } private static List<Pair<String, String>> environmentSettings() { return Arrays.asList( Pair.of("%s_proxy", "http://" + ENV_VARIABLE_USER + ":" + ENV_VARIABLE_PASSWORD + "@" + ENVIRONMENT_HOST + ":" + ENVIRONMENT_VARIABLE_PORT_NUMBER + "/"), Pair.of("no_proxy", ENVIRONMENT_VARIABLE_NON_PROXY) ); } private static List<Pair<String, String>> environmentSettingsWithNoPassword() { return Arrays.asList( Pair.of("%s_proxy", "http://" + ENV_VARIABLE_USER + "@" + ENVIRONMENT_HOST + ":" + ENVIRONMENT_VARIABLE_PORT_NUMBER + "/"), Pair.of("no_proxy", ENVIRONMENT_VARIABLE_NON_PROXY) ); } private static List<Pair<String, String>> systemPropertySettings() { return Arrays.asList( Pair.of("%s.proxyHost", SYSTEM_PROPERTY_HOST), Pair.of("%s.proxyPort", SYSTEM_PROPERTY_PORT_NUMBER), Pair.of("http.nonProxyHosts", SYSTEM_PROPERTY_NON_PROXY), Pair.of("%s.proxyUser", SYSTEM_PROPERTY_USER), Pair.of("%s.proxyPassword", SYSTEM_PROPERTY_PASSWORD)); } }
2,750
0
Create_ds/aws-sdk-java-v2/test/region-testing/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/region-testing/src/test/java/software/amazon/awssdk/regiontesting/EndpointVariantsTest.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.regiontesting; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.regions.EndpointTag.DUALSTACK; import static software.amazon.awssdk.regions.EndpointTag.FIPS; import java.net.URI; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.regions.EndpointTag; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceEndpointKey; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.utils.Validate; @RunWith(Parameterized.class) public class EndpointVariantsTest { @Parameterized.Parameter public TestCase testCase; @Test public void resolvesCorrectEndpoint() { if (testCase instanceof SuccessCase) { URI endpoint = ServiceMetadata.of(testCase.service).endpointFor(testCase.endpointKey); assertThat(endpoint).isEqualTo(((SuccessCase) testCase).endpoint); } else { FailureCase failureCase = Validate.isInstanceOf(FailureCase.class, testCase, "Unknown case type %s.", getClass()); assertThatThrownBy(() -> ServiceMetadata.of(testCase.service).endpointFor(testCase.endpointKey)) .hasMessageContaining(failureCase.exceptionMessage); } } @Parameterized.Parameters(name = "{0}") public static Iterable<TestCase> testCases() { return Arrays.asList(new SuccessCase("default-pattern-service", "us-west-2", "default-pattern-service.us-west-2.amazonaws.com"), new SuccessCase("default-pattern-service", "us-west-2", "default-pattern-service-fips.us-west-2.amazonaws.com", FIPS), new SuccessCase("default-pattern-service", "af-south-1", "default-pattern-service.af-south-1.amazonaws.com"), new SuccessCase("default-pattern-service", "af-south-1", "default-pattern-service-fips.af-south-1.amazonaws.com", FIPS), new SuccessCase("global-service", "aws-global", "global-service.amazonaws.com"), new SuccessCase("global-service", "aws-global", "global-service-fips.amazonaws.com", FIPS), new SuccessCase("override-variant-service", "us-west-2", "override-variant-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-service", "us-west-2", "fips.override-variant-service.us-west-2.new.dns.suffix", FIPS), new SuccessCase("override-variant-service", "af-south-1", "override-variant-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-service", "af-south-1", "fips.override-variant-service.af-south-1.new.dns.suffix", FIPS), new SuccessCase("override-variant-dns-suffix-service", "us-west-2", "override-variant-dns-suffix-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-dns-suffix-service", "us-west-2", "override-variant-dns-suffix-service-fips.us-west-2.new.dns.suffix", FIPS), new SuccessCase("override-variant-dns-suffix-service", "af-south-1", "override-variant-dns-suffix-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-dns-suffix-service", "af-south-1", "override-variant-dns-suffix-service-fips.af-south-1.new.dns.suffix", FIPS), new SuccessCase("override-variant-hostname-service", "us-west-2", "override-variant-hostname-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-hostname-service", "us-west-2", "fips.override-variant-hostname-service.us-west-2.amazonaws.com", FIPS), new SuccessCase("override-variant-hostname-service", "af-south-1", "override-variant-hostname-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-hostname-service", "af-south-1", "fips.override-variant-hostname-service.af-south-1.amazonaws.com", FIPS), new SuccessCase("override-endpoint-variant-service", "us-west-2", "override-endpoint-variant-service.us-west-2.amazonaws.com"), new SuccessCase("override-endpoint-variant-service", "us-west-2", "fips.override-endpoint-variant-service.us-west-2.amazonaws.com", FIPS), new SuccessCase("override-endpoint-variant-service", "af-south-1", "override-endpoint-variant-service.af-south-1.amazonaws.com"), new SuccessCase("override-endpoint-variant-service", "af-south-1", "override-endpoint-variant-service-fips.af-south-1.amazonaws.com", FIPS), new SuccessCase("default-pattern-service", "us-west-2", "default-pattern-service.us-west-2.amazonaws.com"), new SuccessCase("default-pattern-service", "us-west-2", "default-pattern-service.us-west-2.api.aws", DUALSTACK), new SuccessCase("default-pattern-service", "af-south-1", "default-pattern-service.af-south-1.amazonaws.com"), new SuccessCase("default-pattern-service", "af-south-1", "default-pattern-service.af-south-1.api.aws", DUALSTACK), new SuccessCase("global-service", "aws-global", "global-service.amazonaws.com"), new SuccessCase("global-service", "aws-global", "global-service.api.aws", DUALSTACK), new SuccessCase("override-variant-service", "us-west-2", "override-variant-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-service", "us-west-2", "override-variant-service.dualstack.us-west-2.new.dns.suffix", DUALSTACK), new SuccessCase("override-variant-service", "af-south-1", "override-variant-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-service", "af-south-1", "override-variant-service.dualstack.af-south-1.new.dns.suffix", DUALSTACK), new SuccessCase("override-variant-dns-suffix-service", "us-west-2", "override-variant-dns-suffix-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-dns-suffix-service", "us-west-2", "override-variant-dns-suffix-service.us-west-2.new.dns.suffix", DUALSTACK), new SuccessCase("override-variant-dns-suffix-service", "af-south-1", "override-variant-dns-suffix-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-dns-suffix-service", "af-south-1", "override-variant-dns-suffix-service.af-south-1.new.dns.suffix", DUALSTACK), new SuccessCase("override-variant-hostname-service", "us-west-2", "override-variant-hostname-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-hostname-service", "us-west-2", "override-variant-hostname-service.dualstack.us-west-2.api.aws", DUALSTACK), new SuccessCase("override-variant-hostname-service", "af-south-1", "override-variant-hostname-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-hostname-service", "af-south-1", "override-variant-hostname-service.dualstack.af-south-1.api.aws", DUALSTACK), new SuccessCase("override-endpoint-variant-service", "us-west-2", "override-endpoint-variant-service.us-west-2.amazonaws.com"), new SuccessCase("override-endpoint-variant-service", "us-west-2", "override-endpoint-variant-service.dualstack.us-west-2.amazonaws.com", DUALSTACK), new SuccessCase("override-endpoint-variant-service", "af-south-1", "override-endpoint-variant-service.af-south-1.amazonaws.com"), new SuccessCase("override-endpoint-variant-service", "af-south-1", "override-endpoint-variant-service.af-south-1.api.aws", DUALSTACK), new SuccessCase("multi-variant-service", "us-west-2", "multi-variant-service.us-west-2.amazonaws.com"), new SuccessCase("multi-variant-service", "us-west-2", "multi-variant-service.dualstack.us-west-2.api.aws", DUALSTACK), new SuccessCase("multi-variant-service", "us-west-2", "fips.multi-variant-service.us-west-2.amazonaws.com", FIPS), new SuccessCase("multi-variant-service", "us-west-2", "fips.multi-variant-service.dualstack.us-west-2.new.dns.suffix", FIPS, DUALSTACK), new SuccessCase("multi-variant-service", "af-south-1", "multi-variant-service.af-south-1.amazonaws.com"), new SuccessCase("multi-variant-service", "af-south-1", "multi-variant-service.dualstack.af-south-1.api.aws", DUALSTACK), new SuccessCase("multi-variant-service", "af-south-1", "fips.multi-variant-service.af-south-1.amazonaws.com", FIPS), new SuccessCase("multi-variant-service", "af-south-1", "fips.multi-variant-service.dualstack.af-south-1.new.dns.suffix", FIPS, DUALSTACK), new FailureCase("some-service", "us-iso-east-1", "No endpoint known for [dualstack] in us-iso-east-1", DUALSTACK), new FailureCase("some-service", "us-iso-east-1", "No endpoint known for [fips] in us-iso-east-1", FIPS), new FailureCase("some-service", "us-iso-east-1", "No endpoint known for [fips, dualstack] in us-iso-east-1", FIPS, DUALSTACK), // These test case outcomes deviate from the other SDKs, because we ignore "global" services when a // non-global region is specified. We might consider changing this behavior, since the storm of // global services becoming regionalized is dying down. new SuccessCase("global-service", "foo", "global-service.foo.amazonaws.com"), new SuccessCase("global-service", "foo", "global-service-fips.foo.amazonaws.com", FIPS), new SuccessCase("global-service", "foo", "global-service.foo.amazonaws.com"), new SuccessCase("global-service", "foo", "global-service.foo.api.aws", DUALSTACK)); } public static class TestCase { private final String service; private final ServiceEndpointKey endpointKey; public TestCase(String service, String region, EndpointTag... tags) { this.service = service; this.endpointKey = ServiceEndpointKey.builder().region(Region.of(region)).tags(tags).build(); } } public static class SuccessCase extends TestCase { private final URI endpoint; public SuccessCase(String service, String region, String endpoint, EndpointTag... tags) { super(service, region, tags); this.endpoint = URI.create(endpoint); } @Override public String toString() { return "Positive Case: " + endpoint.toString(); } } private static class FailureCase extends TestCase { private final String exceptionMessage; public FailureCase(String service, String region, String exceptionMessage, EndpointTag... tags) { super(service, region, tags); this.exceptionMessage = exceptionMessage; } @Override public String toString() { return "Negative Case: " + exceptionMessage; } } }
2,751
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/TestRunner.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.stability.tests; /** * The main method will be invoked when you execute the test jar generated from * "mvn package -P test-jar" * * You can add the tests in the main method. * eg: * try { * S3AsyncStabilityTest s3AsyncStabilityTest = new S3AsyncStabilityTest(); * S3AsyncStabilityTest.setup(); * s3AsyncStabilityTest.putObject_getObject(); * } finally { * S3AsyncStabilityTest.cleanup(); * } */ public class TestRunner { public static void main(String... args) { } }
2,752
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/ExceptionCounter.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.stability.tests; import java.util.concurrent.atomic.AtomicInteger; public class ExceptionCounter { private final AtomicInteger serviceExceptionCount = new AtomicInteger(0); private final AtomicInteger ioExceptionCount = new AtomicInteger(0); private final AtomicInteger clientExceptionCount = new AtomicInteger(0); private final AtomicInteger unknownExceptionCount = new AtomicInteger(0); public void addServiceException() { serviceExceptionCount.getAndAdd(1); } public void addClientException() { clientExceptionCount.getAndAdd(1); } public void addUnknownException() { unknownExceptionCount.getAndAdd(1); } public void addIoException() { ioExceptionCount.getAndAdd(1); } public int serviceExceptionCount() { return serviceExceptionCount.get(); } public int ioExceptionCount() { return ioExceptionCount.get(); } public int clientExceptionCount() { return clientExceptionCount.get(); } public int unknownExceptionCount() { return unknownExceptionCount.get(); } }
2,753
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/TestResult.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.stability.tests; /** * Model to store the test result */ public class TestResult { private final String testName; private final int totalRequestCount; private final int serviceExceptionCount; private final int ioExceptionCount; private final int clientExceptionCount; private final int unknownExceptionCount; private final int peakThreadCount; private final double heapMemoryAfterGCUsage; private TestResult(Builder builder) { this.testName = builder.testName; this.totalRequestCount = builder.totalRequestCount; this.serviceExceptionCount = builder.serviceExceptionCount; this.ioExceptionCount = builder.ioExceptionCount; this.clientExceptionCount = builder.clientExceptionCount; this.unknownExceptionCount = builder.unknownExceptionCount; this.heapMemoryAfterGCUsage = builder.heapMemoryAfterGCUsage; this.peakThreadCount = builder.peakThreadCount; } public static Builder builder() { return new Builder(); } public String testName() { return testName; } public int totalRequestCount() { return totalRequestCount; } public int serviceExceptionCount() { return serviceExceptionCount; } public int ioExceptionCount() { return ioExceptionCount; } public int clientExceptionCount() { return clientExceptionCount; } public int unknownExceptionCount() { return unknownExceptionCount; } public int peakThreadCount() { return peakThreadCount; } public double heapMemoryAfterGCUsage() { return heapMemoryAfterGCUsage; } @Override public String toString() { return "{" + "testName: '" + testName + '\'' + ", totalRequestCount: " + totalRequestCount + ", serviceExceptionCount: " + serviceExceptionCount + ", ioExceptionCount: " + ioExceptionCount + ", clientExceptionCount: " + clientExceptionCount + ", unknownExceptionCount: " + unknownExceptionCount + ", peakThreadCount: " + peakThreadCount + ", heapMemoryAfterGCUsage: " + heapMemoryAfterGCUsage + '}'; } public static class Builder { private String testName; private int totalRequestCount; private int serviceExceptionCount; private int ioExceptionCount; private int clientExceptionCount; private int unknownExceptionCount; private int peakThreadCount; private double heapMemoryAfterGCUsage; private Builder() { } public Builder testName(String testName) { this.testName = testName; return this; } public Builder totalRequestCount(int totalRequestCount) { this.totalRequestCount = totalRequestCount; return this; } public Builder serviceExceptionCount(int serviceExceptionCount) { this.serviceExceptionCount = serviceExceptionCount; return this; } public Builder ioExceptionCount(int ioExceptionCount) { this.ioExceptionCount = ioExceptionCount; return this; } public Builder clientExceptionCount(int clientExceptionCount) { this.clientExceptionCount = clientExceptionCount; return this; } public Builder unknownExceptionCount(int unknownExceptionCount) { this.unknownExceptionCount = unknownExceptionCount; return this; } public Builder peakThreadCount(int peakThreadCount) { this.peakThreadCount = peakThreadCount; return this; } public Builder heapMemoryAfterGCUsage(double heapMemoryAfterGCUsage) { this.heapMemoryAfterGCUsage = heapMemoryAfterGCUsage; return this; } public TestResult build() { return new TestResult(this); } } }
2,754
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/kinesis/KinesisStabilityTest.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.stability.tests.kinesis; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.function.IntFunction; import java.util.stream.Collectors; import org.apache.commons.lang3.RandomUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.kinesis.KinesisAsyncClient; import software.amazon.awssdk.services.kinesis.model.ConsumerStatus; import software.amazon.awssdk.services.kinesis.model.PutRecordRequest; import software.amazon.awssdk.services.kinesis.model.Record; import software.amazon.awssdk.services.kinesis.model.Shard; import software.amazon.awssdk.services.kinesis.model.ShardIteratorType; import software.amazon.awssdk.services.kinesis.model.StreamStatus; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEvent; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEventStream; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponse; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; import software.amazon.awssdk.stability.tests.utils.StabilityTestRunner; import software.amazon.awssdk.stability.tests.utils.TestEventStreamingResponseHandler; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.testutils.service.AwsTestBase; import software.amazon.awssdk.utils.Logger; /** * Stability Tests using Kinesis. * We can make one call to SubscribeToShard per second per registered consumer per shard * Limit: https://docs.aws.amazon.com/kinesis/latest/APIReference/API_SubscribeToShard.html */ public class KinesisStabilityTest extends AwsTestBase { private static final Logger log = Logger.loggerFor(KinesisStabilityTest.class.getSimpleName()); private static final int CONSUMER_COUNT = 4; private static final int SHARD_COUNT = 9; // one request per consumer/shard combination private static final int CONCURRENCY = CONSUMER_COUNT * SHARD_COUNT; private static final int MAX_CONCURRENCY = CONCURRENCY + 10; public static final String CONSUMER_PREFIX = "kinesisstabilitytestconsumer_"; private List<String> consumerArns; private List<String> shardIds; private List<SdkBytes> producedData; private KinesisAsyncClient asyncClient; private String streamName; private String streamARN; private ExecutorService waiterExecutorService; private ScheduledExecutorService producer; @BeforeEach public void setup() { streamName = "kinesisstabilitytest" + System.currentTimeMillis(); consumerArns = new ArrayList<>(CONSUMER_COUNT); shardIds = new ArrayList<>(SHARD_COUNT); producedData = new ArrayList<>(); asyncClient = KinesisAsyncClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .httpClientBuilder(NettyNioAsyncHttpClient.builder().maxConcurrency(MAX_CONCURRENCY)) .build(); asyncClient.createStream(r -> r.streamName(streamName) .shardCount(SHARD_COUNT)) .join(); waitForStreamToBeActive(); streamARN = asyncClient.describeStream(r -> r.streamName(streamName)).join() .streamDescription() .streamARN(); shardIds = asyncClient.listShards(r -> r.streamName(streamName)) .join() .shards().stream().map(Shard::shardId).collect(Collectors.toList()); waiterExecutorService = Executors.newFixedThreadPool(CONSUMER_COUNT); producer = Executors.newScheduledThreadPool(1); registerStreamConsumers(); waitForConsumersToBeActive(); } @AfterEach public void tearDown() { asyncClient.deleteStream(b -> b.streamName(streamName).enforceConsumerDeletion(true)).join(); waiterExecutorService.shutdown(); producer.shutdown(); asyncClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void putRecords_subscribeToShard() { putRecords(); subscribeToShard(); } /** * We only have one run of subscribeToShard tests because it takes 5 minutes. */ private void subscribeToShard() { log.info(() -> "starting to test subscribeToShard to stream: " + streamName); List<CompletableFuture<?>> completableFutures = generateSubscribeToShardFutures(); StabilityTestRunner.newRunner() .testName("KinesisStabilityTest.subscribeToShard") .futures(completableFutures) .run(); } private void registerStreamConsumers() { log.info(() -> "Starting to register stream consumer " + streamARN); IntFunction<CompletableFuture<?>> futureFunction = i -> asyncClient.registerStreamConsumer(r -> r.streamARN(streamARN) .consumerName(CONSUMER_PREFIX + i)) .thenApply(b -> consumerArns.add(b.consumer().consumerARN())); StabilityTestRunner.newRunner() .requestCountPerRun(CONSUMER_COUNT) .totalRuns(1) .testName("KinesisStabilityTest.registerStreamConsumers") .futureFactory(futureFunction) .run(); } private void putRecords() { log.info(() -> "Starting to test putRecord"); producedData = new ArrayList<>(); SdkBytes data = SdkBytes.fromByteArray(RandomUtils.nextBytes(20)); IntFunction<CompletableFuture<?>> futureFunction = i -> asyncClient.putRecord(PutRecordRequest.builder() .streamName(streamName) .data(data) .partitionKey(UUID.randomUUID().toString()) .build()) .thenApply(b -> producedData.add(data)); StabilityTestRunner.newRunner() .requestCountPerRun(CONCURRENCY) .testName("KinesisStabilityTest.putRecords") .futureFactory(futureFunction) .run(); } /** * Generate request per consumer/shard combination * @return a lit of completablefutures */ private List<CompletableFuture<?>> generateSubscribeToShardFutures() { List<CompletableFuture<?>> completableFutures = new ArrayList<>(); for (int i = 0; i < CONSUMER_COUNT; i++) { final int consumerIndex = i; for (int j = 0; j < SHARD_COUNT; j++) { final int shardIndex = j; TestSubscribeToShardResponseHandler responseHandler = new TestSubscribeToShardResponseHandler(consumerIndex, shardIndex); CompletableFuture<Void> completableFuture = asyncClient.subscribeToShard(b -> b.shardId(shardIds.get(shardIndex)) .consumerARN(consumerArns.get(consumerIndex)) .startingPosition(s -> s.type(ShardIteratorType.TRIM_HORIZON)), responseHandler) .thenAccept(b -> { // Only verify data if all events have been received and the received data is not empty. // It is possible the received data is empty because there is no record at the position // event with TRIM_HORIZON. if (responseHandler.allEventsReceived && !responseHandler.receivedData.isEmpty()) { assertThat(producedData).as(responseHandler.id + " has not received all events" + ".").containsSequence(responseHandler.receivedData); } }); completableFutures.add(completableFuture); } } return completableFutures; } private void waitForStreamToBeActive() { Waiter.run(() -> asyncClient.describeStream(r -> r.streamName(streamName)) .join()) .until(b -> b.streamDescription().streamStatus().equals(StreamStatus.ACTIVE)) .orFailAfter(Duration.ofMinutes(5)); } private void waitForConsumersToBeActive() { CompletableFuture<?>[] completableFutures = consumerArns.stream() .map(a -> CompletableFuture.supplyAsync(() -> Waiter.run(() -> asyncClient.describeStreamConsumer(b -> b.consumerARN(a)) .join()) .until(b -> b.consumerDescription().consumerStatus().equals(ConsumerStatus.ACTIVE)) .orFailAfter(Duration.ofMinutes(5)), waiterExecutorService)) .toArray(CompletableFuture[]::new); CompletableFuture.allOf(completableFutures).join(); } private static class TestSubscribeToShardResponseHandler extends TestEventStreamingResponseHandler<SubscribeToShardResponse , SubscribeToShardEventStream> implements SubscribeToShardResponseHandler { private final List<SdkBytes> receivedData = new ArrayList<>(); private final String id; private volatile boolean allEventsReceived = false; TestSubscribeToShardResponseHandler(int consumerIndex, int shardIndex) { id = "consumer_" + consumerIndex + "_shard_" + shardIndex; } @Override public void onEventStream(SdkPublisher<SubscribeToShardEventStream> publisher) { publisher.filter(SubscribeToShardEvent.class) .subscribe(b -> { log.debug(() -> "sequenceNumber " + b.records() + "_" + id); receivedData.addAll(b.records().stream().map(Record::data).collect(Collectors.toList())); }); } @Override public void exceptionOccurred(Throwable throwable) { log.error(() -> "An exception was thrown from " + id, throwable); } @Override public void complete() { allEventsReceived = true; log.info(() -> "All events stream successfully " + id); } } }
2,755
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/cloudwatch/CloudWatchCrtAsyncStabilityTest.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.stability.tests.cloudwatch; import java.time.Duration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.crt.io.EventLoopGroup; import software.amazon.awssdk.crt.io.HostResolver; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient; import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; public class CloudWatchCrtAsyncStabilityTest extends CloudWatchBaseStabilityTest { private static String namespace; private static CloudWatchAsyncClient cloudWatchAsyncClient; @Override protected CloudWatchAsyncClient getTestClient() { return cloudWatchAsyncClient; } @Override protected String getNamespace() { return namespace; } @BeforeAll public static void setup() { namespace = "CloudWatchCrtAsyncStabilityTest" + System.currentTimeMillis(); SdkAsyncHttpClient.Builder crtClientBuilder = AwsCrtAsyncHttpClient.builder() .connectionMaxIdleTime(Duration.ofSeconds(5)); cloudWatchAsyncClient = CloudWatchAsyncClient.builder() .httpClientBuilder(crtClientBuilder) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(10)) // Retry at test level .retryPolicy(RetryPolicy.none())) .build(); } @AfterAll public static void tearDown() { cloudWatchAsyncClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void putMetrics_lowTpsLongInterval() { putMetrics(); } }
2,756
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/cloudwatch/CloudWatchNettyAsyncStabilityTest.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.stability.tests.cloudwatch; import java.time.Duration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; public class CloudWatchNettyAsyncStabilityTest extends CloudWatchBaseStabilityTest { private static String namespace; private static CloudWatchAsyncClient cloudWatchAsyncClient; @Override protected CloudWatchAsyncClient getTestClient() { return cloudWatchAsyncClient; } @Override protected String getNamespace() { return namespace; } @BeforeAll public static void setup() { namespace = "CloudWatchNettyAsyncStabilityTest" + System.currentTimeMillis(); cloudWatchAsyncClient = CloudWatchAsyncClient.builder() .httpClientBuilder(NettyNioAsyncHttpClient.builder().maxConcurrency(CONCURRENCY)) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b // Retry at test level .retryPolicy(RetryPolicy.none()) .apiCallTimeout(Duration.ofMinutes(1))) .build(); } @AfterAll public static void tearDown() { cloudWatchAsyncClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void putMetrics_lowTpsLongInterval() { putMetrics(); } }
2,757
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/cloudwatch/CloudWatchBaseStabilityTest.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.stability.tests.cloudwatch; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; import org.apache.commons.lang3.RandomUtils; import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient; import software.amazon.awssdk.services.cloudwatch.model.MetricDatum; import software.amazon.awssdk.stability.tests.utils.StabilityTestRunner; import software.amazon.awssdk.testutils.service.AwsTestBase; public abstract class CloudWatchBaseStabilityTest extends AwsTestBase { protected static final int CONCURRENCY = 50; protected static final int TOTAL_RUNS = 3; protected abstract CloudWatchAsyncClient getTestClient(); protected abstract String getNamespace(); protected void putMetrics() { List<MetricDatum> metrics = new ArrayList<>(); for (int i = 0; i < 20 ; i++) { metrics.add(MetricDatum.builder() .metricName("test") .values(RandomUtils.nextDouble(1d, 1000d)) .build()); } IntFunction<CompletableFuture<?>> futureIntFunction = i -> getTestClient().putMetricData(b -> b.namespace(getNamespace()) .metricData(metrics)); runCloudWatchTest("putMetrics_lowTpsLongInterval", futureIntFunction); } private void runCloudWatchTest(String testName, IntFunction<CompletableFuture<?>> futureIntFunction) { StabilityTestRunner.newRunner() .testName("CloudWatchAsyncStabilityTest." + testName) .futureFactory(futureIntFunction) .totalRuns(TOTAL_RUNS) .requestCountPerRun(CONCURRENCY) .delaysBetweenEachRun(Duration.ofSeconds(6)) .run(); } }
2,758
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/s3/S3NettyAsyncStabilityTest.java
package software.amazon.awssdk.stability.tests.s3; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; import java.time.Duration; public class S3NettyAsyncStabilityTest extends S3BaseStabilityTest { private static String bucketName = "s3nettyasyncstabilitytests" + System.currentTimeMillis(); private static S3AsyncClient s3NettyClient; static { s3NettyClient = S3AsyncClient.builder() .httpClientBuilder(NettyNioAsyncHttpClient.builder() .maxConcurrency(CONCURRENCY)) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(10)) // Retry at test level .retryPolicy(RetryPolicy.none())) .build(); } public S3NettyAsyncStabilityTest() { super(s3NettyClient); } @BeforeAll public static void setup() { s3NettyClient.createBucket(b -> b.bucket(bucketName)).join(); } @AfterAll public static void cleanup() { deleteBucketAndAllContents(s3NettyClient, bucketName); s3NettyClient.close(); } @Override protected String getTestBucketName() { return bucketName; } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void getBucketAcl_lowTpsLongInterval_Netty() { doGetBucketAcl_lowTpsLongInterval(); } }
2,759
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/s3/S3WithCrtAsyncHttpClientStabilityTest.java
package software.amazon.awssdk.stability.tests.s3; import java.time.Duration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; /** * Stability tests for {@link S3AsyncClient} using {@link AwsCrtAsyncHttpClient} */ public class S3WithCrtAsyncHttpClientStabilityTest extends S3BaseStabilityTest { private static String bucketName = "s3withcrtasyncclientstabilitytests" + System.currentTimeMillis(); private static S3AsyncClient s3CrtClient; static { int numThreads = Runtime.getRuntime().availableProcessors(); SdkAsyncHttpClient.Builder httpClientBuilder = AwsCrtAsyncHttpClient.builder() .connectionMaxIdleTime(Duration.ofSeconds(5)); s3CrtClient = S3AsyncClient.builder() .httpClientBuilder(httpClientBuilder) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(10)) // Retry at test level .retryPolicy(RetryPolicy.none())) .build(); } public S3WithCrtAsyncHttpClientStabilityTest() { super(s3CrtClient); } @BeforeAll public static void setup() { s3CrtClient.createBucket(b -> b.bucket(bucketName)).join(); } @AfterAll public static void cleanup() { deleteBucketAndAllContents(s3CrtClient, bucketName); s3CrtClient.close(); } @Override protected String getTestBucketName() { return bucketName; } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void getBucketAcl_lowTpsLongInterval_Crt() { doGetBucketAcl_lowTpsLongInterval(); } }
2,760
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/s3/S3BaseStabilityTest.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.stability.tests.s3; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; import org.apache.commons.lang3.RandomStringUtils; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; import software.amazon.awssdk.services.s3.model.NoSuchBucketException; import software.amazon.awssdk.services.s3.model.NoSuchKeyException; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; import software.amazon.awssdk.stability.tests.utils.StabilityTestRunner; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.testutils.service.AwsTestBase; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Md5Utils; public abstract class S3BaseStabilityTest extends AwsTestBase { private static final Logger log = Logger.loggerFor(S3BaseStabilityTest.class); protected static final int CONCURRENCY = 100; protected static final int TOTAL_RUNS = 50; protected static final String LARGE_KEY_NAME = "2GB"; protected static S3Client s3ApacheClient; private final S3AsyncClient testClient; static { s3ApacheClient = S3Client.builder() .httpClientBuilder(ApacheHttpClient.builder() .maxConnections(CONCURRENCY)) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(10))) .build(); } public S3BaseStabilityTest(S3AsyncClient testClient) { this.testClient = testClient; } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void largeObject_put_get_usingFile() { String md5Upload = uploadLargeObjectFromFile(); String md5Download = downloadLargeObjectToFile(); assertThat(md5Upload).isEqualTo(md5Download); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void putObject_getObject_highConcurrency() { putObject(); getObject(); } protected String computeKeyName(int i) { return "key_" + i; } protected abstract String getTestBucketName(); protected void doGetBucketAcl_lowTpsLongInterval() { IntFunction<CompletableFuture<?>> future = i -> testClient.getBucketAcl(b -> b.bucket(getTestBucketName())); String className = this.getClass().getSimpleName(); StabilityTestRunner.newRunner() .testName(className + ".getBucketAcl_lowTpsLongInterval") .futureFactory(future) .requestCountPerRun(10) .totalRuns(3) .delaysBetweenEachRun(Duration.ofSeconds(6)) .run(); } protected String downloadLargeObjectToFile() { File randomTempFile = RandomTempFile.randomUncreatedFile(); StabilityTestRunner.newRunner() .testName("S3AsyncStabilityTest.downloadLargeObjectToFile") .futures(testClient.getObject(b -> b.bucket(getTestBucketName()).key(LARGE_KEY_NAME), AsyncResponseTransformer.toFile(randomTempFile))) .run(); try { return Md5Utils.md5AsBase64(randomTempFile); } catch (IOException e) { throw new RuntimeException(e); } finally { randomTempFile.delete(); } } protected String uploadLargeObjectFromFile() { RandomTempFile file = null; try { file = new RandomTempFile((long) 2e+9); String md5 = Md5Utils.md5AsBase64(file); StabilityTestRunner.newRunner() .testName("S3AsyncStabilityTest.uploadLargeObjectFromFile") .futures(testClient.putObject(b -> b.bucket(getTestBucketName()).key(LARGE_KEY_NAME), AsyncRequestBody.fromFile(file))) .run(); return md5; } catch (IOException e) { throw new RuntimeException("fail to create test file", e); } finally { if (file != null) { file.delete(); } } } protected void putObject() { byte[] bytes = RandomStringUtils.randomAlphanumeric(10_000).getBytes(); IntFunction<CompletableFuture<?>> future = i -> { String keyName = computeKeyName(i); return testClient.putObject(b -> b.bucket(getTestBucketName()).key(keyName), AsyncRequestBody.fromBytes(bytes)); }; StabilityTestRunner.newRunner() .testName("S3AsyncStabilityTest.putObject") .futureFactory(future) .requestCountPerRun(CONCURRENCY) .totalRuns(TOTAL_RUNS) .delaysBetweenEachRun(Duration.ofMillis(100)) .run(); } protected void getObject() { IntFunction<CompletableFuture<?>> future = i -> { String keyName = computeKeyName(i); Path path = RandomTempFile.randomUncreatedFile().toPath(); return testClient.getObject(b -> b.bucket(getTestBucketName()).key(keyName), AsyncResponseTransformer.toFile(path)); }; StabilityTestRunner.newRunner() .testName("S3AsyncStabilityTest.getObject") .futureFactory(future) .requestCountPerRun(CONCURRENCY) .totalRuns(TOTAL_RUNS) .delaysBetweenEachRun(Duration.ofMillis(100)) .run(); } protected static void deleteBucketAndAllContents(S3AsyncClient client, String bucketName) { try { List<CompletableFuture<?>> futures = new ArrayList<>(); client.listObjectsV2Paginator(b -> b.bucket(bucketName)) .subscribe(r -> r.contents().forEach(s -> futures.add(client.deleteObject(o -> o.bucket(bucketName).key(s.key()))))) .join(); CompletableFuture<?>[] futureArray = futures.toArray(new CompletableFuture<?>[0]); CompletableFuture.allOf(futureArray).join(); client.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build()).join(); } catch (Exception e) { log.error(() -> "Failed to delete bucket: " +bucketName); } } protected void verifyObjectExist(String bucketName, String keyName, long size) throws IOException { try { s3ApacheClient.headBucket(b -> b.bucket(bucketName)); } catch (NoSuchBucketException e) { log.info(() -> "NoSuchBucketException was thrown, staring to create the bucket"); s3ApacheClient.createBucket(b -> b.bucket(bucketName)); } try { s3ApacheClient.headObject(b -> b.key(keyName).bucket(bucketName)); } catch (NoSuchKeyException e) { log.info(() -> "NoSuchKeyException was thrown, starting to upload the object"); RandomTempFile file = new RandomTempFile(size); s3ApacheClient.putObject(b -> b.bucket(bucketName).key(keyName), RequestBody.fromFile(file)); file.delete(); } } }
2,761
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/s3/S3CrtAsyncClientStabilityTest.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.stability.tests.s3; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient; /** * Stability tests for {@link S3CrtAsyncClient} */ public class S3CrtAsyncClientStabilityTest extends S3BaseStabilityTest { private static final String BUCKET_NAME = "s3crtasyncclinetstabilitytests" + System.currentTimeMillis(); private static S3AsyncClient s3CrtAsyncClient; static { s3CrtAsyncClient = S3CrtAsyncClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); } public S3CrtAsyncClientStabilityTest() { super(s3CrtAsyncClient); } @BeforeAll public static void setup() { System.setProperty("aws.crt.debugnative", "true"); s3ApacheClient.createBucket(b -> b.bucket(BUCKET_NAME)); } @AfterAll public static void cleanup() { try (S3AsyncClient s3NettyClient = S3AsyncClient.builder() .httpClientBuilder(NettyNioAsyncHttpClient.builder() .maxConcurrency(CONCURRENCY)) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build()) { deleteBucketAndAllContents(s3NettyClient, BUCKET_NAME); } s3CrtAsyncClient.close(); s3ApacheClient.close(); CrtResource.waitForNoResources(); } @Override protected String getTestBucketName() { return BUCKET_NAME; } }
2,762
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/RetryableTestExtension.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.stability.tests.utils; import static java.util.Spliterator.ORDERED; import static java.util.Spliterators.spliteratorUnknownSize; import static java.util.stream.StreamSupport.stream; import static org.junit.platform.commons.util.AnnotationUtils.findAnnotation; import static org.junit.platform.commons.util.AnnotationUtils.isAnnotated; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext.Namespace; import org.junit.jupiter.api.extension.ExtensionContextException; import org.junit.jupiter.api.extension.TestExecutionExceptionHandler; import org.junit.jupiter.api.extension.TestTemplateInvocationContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; import org.opentest4j.TestAbortedException; public class RetryableTestExtension implements TestTemplateInvocationContextProvider, TestExecutionExceptionHandler { private static final Namespace NAMESPACE = Namespace.create(RetryableTestExtension.class); @Override public boolean supportsTestTemplate(ExtensionContext extensionContext) { Method testMethod = extensionContext.getRequiredTestMethod(); return isAnnotated(testMethod, RetryableTest.class); } @Override public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext context) { RetryExecutor executor = retryExecutor(context); return stream(spliteratorUnknownSize(executor, ORDERED), false); } @Override public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { if (!isRetryableException(context, throwable)) { throw throwable; } RetryExecutor retryExecutor = retryExecutor(context); retryExecutor.exceptionOccurred(throwable); } private RetryExecutor retryExecutor(ExtensionContext context) { Method method = context.getRequiredTestMethod(); ExtensionContext templateContext = context.getParent() .orElseThrow(() -> new IllegalStateException( "Extension context \"" + context + "\" should have a parent context.")); int maxRetries = maxRetries(context); return templateContext.getStore(NAMESPACE).getOrComputeIfAbsent(method.toString(), __ -> new RetryExecutor(maxRetries), RetryExecutor.class); } private boolean isRetryableException(ExtensionContext context, Throwable throwable) { return retryableException(context).isAssignableFrom(throwable.getClass()) || throwable instanceof TestAbortedException; } private int maxRetries(ExtensionContext context) { return retrieveAnnotation(context).maxRetries(); } private Class<? extends Throwable> retryableException(ExtensionContext context) { return retrieveAnnotation(context).retryableException(); } private RetryableTest retrieveAnnotation(ExtensionContext context) { return findAnnotation(context.getRequiredTestMethod(), RetryableTest.class) .orElseThrow(() -> new ExtensionContextException("@RetryableTest Annotation not found on method")); } private static final class RetryableTestsTemplateInvocationContext implements TestTemplateInvocationContext { private int maxRetries; private int numAttempt; RetryableTestsTemplateInvocationContext(int numAttempt, int maxRetries) { this.numAttempt = numAttempt; this.maxRetries = maxRetries; } } private static final class RetryExecutor implements Iterator<RetryableTestsTemplateInvocationContext> { private final int maxRetries; private int totalAttempts; private List<Throwable> throwables = new ArrayList<>(); RetryExecutor(int maxRetries) { this.maxRetries = maxRetries; } private void exceptionOccurred(Throwable throwable) { throwables.add(throwable); if (throwables.size() == maxRetries) { throw new AssertionError("All attempts failed. Last exception: ", throwable); } else { throw new TestAbortedException(String.format("Attempt %s failed of the retryable exception, going to retry the test", totalAttempts), throwable); } } @Override public boolean hasNext() { if (totalAttempts == 0) { return true; } boolean previousFailed = totalAttempts == throwables.size(); if (previousFailed && totalAttempts <= maxRetries - 1) { return true; } return false; } @Override public RetryableTestsTemplateInvocationContext next() { totalAttempts++; return new RetryableTestsTemplateInvocationContext(totalAttempts, maxRetries); } } }
2,763
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/TestTranscribeStreamingSubscription.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.stability.tests.utils; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.transcribestreaming.model.AudioEvent; import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; public class TestTranscribeStreamingSubscription implements Subscription { private static final int CHUNK_SIZE_IN_BYTES = 1024; private ExecutorService executor = Executors.newFixedThreadPool(1); private AtomicLong demand = new AtomicLong(0); private final Subscriber<? super AudioStream> subscriber; private final InputStream inputStream; private volatile boolean done = false; public TestTranscribeStreamingSubscription(Subscriber<? super AudioStream> subscriber, InputStream inputStream) { this.subscriber = subscriber; this.inputStream = inputStream; } @Override public void request(long n) { if (done) { return; } if (n <= 0) { signalOnError(new IllegalArgumentException("Demand must be positive")); return; } demand.getAndAdd(n); executor.submit(() -> { try { do { ByteBuffer audioBuffer = getNextEvent(); if (audioBuffer.remaining() > 0) { AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); subscriber.onNext(audioEvent); } else { subscriber.onComplete(); done = true; break; } } while (demand.decrementAndGet() > 0 && !done); } catch (Exception e) { signalOnError(e); } }); } @Override public void cancel() { executor.shutdown(); } private ByteBuffer getNextEvent() { ByteBuffer audioBuffer; byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; int len; try { len = inputStream.read(audioBytes); if (len <= 0) { audioBuffer = ByteBuffer.allocate(0); } else { audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); } } catch (IOException e) { throw new UncheckedIOException(e); } return audioBuffer; } private AudioEvent audioEventFromBuffer(ByteBuffer bb) { return AudioEvent.builder() .audioChunk(SdkBytes.fromByteBuffer(bb)) .build(); } private void signalOnError(Throwable t) { if (!done) { subscriber.onError(t); done = true; } } }
2,764
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/StabilityTestRunner.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.stability.tests.utils; import static java.lang.management.MemoryType.HEAP; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.IntFunction; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.stability.tests.ExceptionCounter; import software.amazon.awssdk.stability.tests.TestResult; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * Stability tests runner. * * There are two ways to run the tests: * * - providing futureFactories requestCountPerRun and totalRuns. eg: * * StabilityTestRunner.newRunner() * .futureFactory(i -> CompletableFuture.runAsync(() -> LOGGER.info(() -> * "hello world " + i), executors)) * .testName("test") * .requestCountPerRun(10) * .delaysBetweenEachRun(Duration.ofMillis(1000)) * .totalRuns(5) * .run(); * * The tests runner will create futures from the factories and run the 10 requests per run for 5 runs with 1s delay between * each run. * * - providing futures, eg: * * StabilityTestRunner.newRunner() * .futures(futures) * .testName("test") * .run(); * The tests runner will run the given futures in one run. */ public class StabilityTestRunner { private static final Logger log = Logger.loggerFor(StabilityTestRunner.class); private static final double ALLOWED_FAILURE_RATIO = 0.05; private static final int TESTS_TIMEOUT_IN_MINUTES = 60; // The peak thread count might be different depending on the machine the tests are currently running on. // because of the internal thread pool used in AsynchronousFileChannel private static final int ALLOWED_PEAK_THREAD_COUNT = 90; private ThreadMXBean threadMXBean; private IntFunction<CompletableFuture<?>> futureFactory; private List<CompletableFuture<?>> futures; private String testName; private Duration delay = Duration.ZERO; private Integer requestCountPerRun; private Integer totalRuns = 1; private StabilityTestRunner() { threadMXBean = ManagementFactory.getThreadMXBean(); // Reset peak thread count for every test threadMXBean.resetPeakThreadCount(); } /** * Create a new test runner * * @return a new test runner */ public static StabilityTestRunner newRunner() { return new StabilityTestRunner(); } public StabilityTestRunner futureFactory(IntFunction<CompletableFuture<?>> futureFactory) { this.futureFactory = futureFactory; return this; } public StabilityTestRunner futures(List<CompletableFuture<?>> futures) { this.futures = futures; return this; } public StabilityTestRunner futures(CompletableFuture<?>... futures) { this.futures = Arrays.asList(futures); return this; } /** * The test name to generate the test report. * * @param testName the name of the report * @return StabilityTestRunner */ public StabilityTestRunner testName(String testName) { this.testName = testName; return this; } /** * @param delay delay between each run * @return StabilityTestRunner */ public StabilityTestRunner delaysBetweenEachRun(Duration delay) { this.delay = delay; return this; } /** * @param runs total runs * @return StabilityTestRunner */ public StabilityTestRunner totalRuns(Integer runs) { this.totalRuns = runs; return this; } /** * @param requestCountPerRun the number of request per run * @return StabilityTestRunner */ public StabilityTestRunner requestCountPerRun(Integer requestCountPerRun) { this.requestCountPerRun = requestCountPerRun; return this; } /** * Run the tests based on the parameters provided */ public void run() { validateParameters(); TestResult result; if (futureFactory != null) { result = runTestsFromFutureFunction(); } else { result = runTestsFromFutures(); } processResult(result); } private TestResult runTestsFromFutureFunction() { Validate.notNull(requestCountPerRun, "requestCountPerRun cannot be null"); Validate.notNull(totalRuns, "totalRuns cannot be null"); ExceptionCounter exceptionCounter = new ExceptionCounter(); int totalRequestNumber = requestCountPerRun * totalRuns; CompletableFuture[] completableFutures = new CompletableFuture[totalRequestNumber]; int runNumber = 0; while (runNumber < totalRequestNumber) { for (int i = runNumber; i < runNumber + requestCountPerRun; i++) { CompletableFuture<?> future = futureFactory.apply(i); completableFutures[i] = handleException(future, exceptionCounter); } int finalRunNumber = runNumber; log.debug(() -> "Finishing one run " + finalRunNumber); runNumber += requestCountPerRun; addDelayIfNeeded(); } return generateTestResult(totalRequestNumber, testName, exceptionCounter, completableFutures); } private double calculateHeapMemoryAfterGCUsage() { List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans(); long used = 0, max = 0; for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) { String name = memoryPoolMXBean.getName(); if (!name.contains("Eden")) { if (memoryPoolMXBean.getType().equals(HEAP)) { MemoryUsage memoryUsage = memoryPoolMXBean.getCollectionUsage(); used += memoryUsage.getUsed(); max += memoryUsage.getMax() == -1 ? 0 : memoryUsage.getMax(); } } } return used / (double) max; } private TestResult runTestsFromFutures() { ExceptionCounter exceptionCounter = new ExceptionCounter(); CompletableFuture[] completableFutures = futures.stream().map(b -> handleException(b, exceptionCounter)).toArray(CompletableFuture[]::new); return generateTestResult(futures.size(), testName, exceptionCounter, completableFutures); } private void validateParameters() { Validate.notNull(testName, "testName cannot be null"); Validate.isTrue(futureFactory == null || futures == null, "futureFactory and futures cannot be both configured"); } private void addDelayIfNeeded() { log.debug(() -> "Sleeping for " + delay.toMillis()); if (!delay.isZero()) { try { Thread.sleep(delay.toMillis()); } catch (InterruptedException e) { // Ignoring exception } } } /** * Handle the exceptions of executing the futures. * * @param future the future to be executed * @param exceptionCounter the exception counter * @return the completable future */ private static CompletableFuture<?> handleException(CompletableFuture<?> future, ExceptionCounter exceptionCounter) { return future.exceptionally(t -> { Throwable cause = t.getCause(); log.error(() -> "An exception was thrown ", t); if (cause instanceof SdkServiceException) { exceptionCounter.addServiceException(); } else if (isIOExceptionOrHasIOCause(cause)) { exceptionCounter.addIoException(); } else if (cause instanceof SdkClientException) { if (isIOExceptionOrHasIOCause(cause.getCause())) { exceptionCounter.addIoException(); } else { exceptionCounter.addClientException(); } } else { exceptionCounter.addUnknownException(); } return null; }); } private static boolean isIOExceptionOrHasIOCause(Throwable throwable) { if (throwable == null) { return false; } return throwable instanceof IOException || throwable.getCause() instanceof IOException; } private TestResult generateTestResult(int totalRequestNumber, String testName, ExceptionCounter exceptionCounter, CompletableFuture[] completableFutures) { try { CompletableFuture.allOf(completableFutures).get(TESTS_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Error occurred running the tests: " + testName, e); } catch (TimeoutException e) { throw new RuntimeException(String.format("Tests (%s) did not finish within %s minutes", testName, TESTS_TIMEOUT_IN_MINUTES)); } return TestResult.builder() .testName(testName) .clientExceptionCount(exceptionCounter.clientExceptionCount()) .serviceExceptionCount(exceptionCounter.serviceExceptionCount()) .ioExceptionCount(exceptionCounter.ioExceptionCount()) .totalRequestCount(totalRequestNumber) .unknownExceptionCount(exceptionCounter.unknownExceptionCount()) .peakThreadCount(threadMXBean.getPeakThreadCount()) .heapMemoryAfterGCUsage(calculateHeapMemoryAfterGCUsage()) .build(); } /** * Process the result. Throws exception if SdkClientExceptions were thrown or 5% requests failed of * SdkServiceException or IOException. * * @param testResult the result to process. */ private void processResult(TestResult testResult) { log.info(() -> "TestResult: " + testResult); int clientExceptionCount = testResult.clientExceptionCount(); int expectedExceptionCount = testResult.ioExceptionCount() + testResult.serviceExceptionCount(); int unknownExceptionCount = testResult.unknownExceptionCount(); double ratio = expectedExceptionCount / (double) testResult.totalRequestCount(); if (clientExceptionCount > 0) { String errorMessage = String.format("%s SdkClientExceptions were thrown, failing the tests", clientExceptionCount); log.error(() -> errorMessage); throw new AssertionError(errorMessage); } if (testResult.unknownExceptionCount() > 0) { String errorMessage = String.format("%s unknown exceptions were thrown, failing the tests", unknownExceptionCount); log.error(() -> errorMessage); throw new AssertionError(errorMessage); } if (ratio > ALLOWED_FAILURE_RATIO) { String errorMessage = String.format("More than %s percent requests (%s percent) failed of SdkServiceException " + "or IOException, failing the tests", ALLOWED_FAILURE_RATIO * 100, ratio * 100); throw new StabilityTestsRetryableException(errorMessage); } if (testResult.peakThreadCount() > ALLOWED_PEAK_THREAD_COUNT) { String errorMessage = String.format("The number of peak thread exceeds the allowed peakThread threshold %s", ALLOWED_PEAK_THREAD_COUNT); threadDump(testResult.testName()); throw new AssertionError(errorMessage); } } private void threadDump(String testName) { StringBuilder threadDump = new StringBuilder("\n============").append(testName) .append(" Thread Dump:=============\n"); ThreadInfo[] threadInfoList = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); for (ThreadInfo threadInfo : threadInfoList) { threadDump.append('"'); threadDump.append(threadInfo.getThreadName()); threadDump.append("\":"); threadDump.append(threadInfo.getThreadState()); threadDump.append("\n"); } threadDump.append("=================================="); log.info(threadDump::toString); } }
2,765
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/TestEventStreamingResponseHandler.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.stability.tests.utils; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.eventstream.EventStreamResponseHandler; import software.amazon.awssdk.utils.Logger; public abstract class TestEventStreamingResponseHandler<ResponseT extends AwsResponse, EventT> implements EventStreamResponseHandler<ResponseT, EventT> { private static final Logger log = Logger.loggerFor(TestEventStreamingResponseHandler.class.getSimpleName()); @Override public void responseReceived(ResponseT response) { String requestId = response.responseMetadata().requestId(); log.info(() -> "Received Initial response: " + requestId); } @Override public void complete() { log.info(() -> "All events stream successfully"); } @Override public void exceptionOccurred(Throwable throwable) { log.error(() -> "An exception was thrown " + throwable.getMessage(), throwable); } }
2,766
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/StabilityTestsRunnerTest.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.stability.tests.utils; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.utils.Logger; /** * Tests of the tests */ public class StabilityTestsRunnerTest { private static final Logger LOGGER = Logger.loggerFor("RunnerTest"); private static ExecutorService executors; @BeforeAll public static void setUp() { executors = Executors.newFixedThreadPool(10); } @AfterAll public static void tearDown() { executors.shutdown(); } @Test public void testUsingFutureFactory() { StabilityTestRunner.newRunner() .futureFactory(i -> CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world " + i), executors)) .testName("test") .requestCountPerRun(10) .delaysBetweenEachRun(Duration.ofMillis(500)) .totalRuns(5) .run(); } @Test public void testUsingFutures() { List<CompletableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { int finalI = i; futures.add(CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world " + finalI), executors)); } StabilityTestRunner.newRunner() .futures(futures) .testName("test") .run(); } @Test public void unexpectedExceptionThrown_shouldFailTests() { List<CompletableFuture<?>> futures = new ArrayList<>(); futures.add(CompletableFuture.runAsync(() -> { throw new RuntimeException("boom"); }, executors)); futures.add(CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world "), executors)); assertThatThrownBy(() -> StabilityTestRunner.newRunner() .futures(futures) .testName("test") .run()).hasMessageContaining("unknown exceptions were thrown"); } @Test public void expectedExceptionThrownExceedsThreshold_shouldFailTests() { List<CompletableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { int finalI = i; if (i < 3) { futures.add(CompletableFuture.runAsync(() -> { throw SdkServiceException.builder().message("boom").build(); }, executors)); } else { futures.add(CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world " + finalI), executors)); } } assertThatThrownBy(() -> StabilityTestRunner.newRunner() .futures(futures) .testName("test") .run()) .hasMessageContaining("failed of SdkServiceException or IOException"); } @Test public void expectedExceptionThrownNotExceedsThreshold_shouldSucceed() { List<CompletableFuture<?>> futures = new ArrayList<>(); futures.add(CompletableFuture.runAsync(() -> { throw SdkServiceException.builder().message("boom").build(); }, executors)); for (int i = 1; i < 20; i++) { futures.add(CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world "), executors)); } StabilityTestRunner.newRunner() .futures(futures) .testName("test") .run(); } @Test public void sdkClientExceptionsThrown_shouldFail() { List<CompletableFuture<?>> futures = new ArrayList<>(); futures.add(CompletableFuture.runAsync(() -> { throw SdkClientException.builder().message("boom").build(); }, executors)); futures.add(CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world "), executors)); assertThatThrownBy(() -> StabilityTestRunner.newRunner() .futures(futures) .testName("test") .run()).hasMessageContaining("SdkClientExceptions were thrown"); } }
2,767
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/RetryableTest.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.stability.tests.utils; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.ExtendWith; /** * Denotes that a method is a test template for a retryable test. */ @Target( {ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @TestTemplate @ExtendWith(RetryableTestExtension.class) public @interface RetryableTest { /** * Exception to retry * * @return Exception that handled */ Class<? extends Throwable> retryableException() default Throwable.class; /** * The maximum number of retries. * * @return the number of retries; must be greater than zero */ int maxRetries(); }
2,768
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/exceptions/StabilityTestsRetryableException.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.stability.tests.exceptions; /** * Indicating the tests failure can be retried */ public class StabilityTestsRetryableException extends RuntimeException { public StabilityTestsRetryableException(String message) { super(message); } }
2,769
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/sqs/SqsCrtAsyncStabilityTest.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.stability.tests.sqs; import java.time.Duration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.crt.io.EventLoopGroup; import software.amazon.awssdk.crt.io.HostResolver; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient; import software.amazon.awssdk.services.sqs.SqsAsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; public class SqsCrtAsyncStabilityTest extends SqsBaseStabilityTest { private static String queueName; private static String queueUrl; private static SqsAsyncClient sqsAsyncClient; @Override protected SqsAsyncClient getTestClient() { return sqsAsyncClient; } @Override protected String getQueueUrl() { return queueUrl; } @Override protected String getQueueName() { return queueName; } @BeforeAll public static void setup() { SdkAsyncHttpClient.Builder crtClientBuilder = AwsCrtAsyncHttpClient.builder() .connectionMaxIdleTime(Duration.ofSeconds(5)); sqsAsyncClient = SqsAsyncClient.builder() .httpClientBuilder(crtClientBuilder) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(10)) // Retry at test level .retryPolicy(RetryPolicy.none())) .build(); queueName = "sqscrtasyncstabilitytests" + System.currentTimeMillis(); queueUrl = setup(sqsAsyncClient, queueName); } @AfterAll public static void tearDown() { tearDown(sqsAsyncClient, queueUrl); sqsAsyncClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void sendMessage_receiveMessage() { sendMessage(); receiveMessage(); } }
2,770
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/sqs/SqsBaseStabilityTest.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.stability.tests.sqs; import java.time.Duration; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; import java.util.stream.Collectors; import org.apache.commons.lang3.RandomStringUtils; import software.amazon.awssdk.services.sqs.SqsAsyncClient; import software.amazon.awssdk.services.sqs.model.CreateQueueResponse; import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequestEntry; import software.amazon.awssdk.stability.tests.utils.StabilityTestRunner; import software.amazon.awssdk.testutils.service.AwsTestBase; import software.amazon.awssdk.utils.Logger; public abstract class SqsBaseStabilityTest extends AwsTestBase { private static final Logger log = Logger.loggerFor(SqsNettyAsyncStabilityTest.class); protected static final int CONCURRENCY = 100; protected static final int TOTAL_RUNS = 50; protected abstract SqsAsyncClient getTestClient(); protected abstract String getQueueUrl(); protected abstract String getQueueName(); protected static String setup(SqsAsyncClient client, String queueName) { CreateQueueResponse createQueueResponse = client.createQueue(b -> b.queueName(queueName)).join(); return createQueueResponse.queueUrl(); } protected static void tearDown(SqsAsyncClient client, String queueUrl) { if (queueUrl != null) { client.deleteQueue(b -> b.queueUrl(queueUrl)); } } protected void sendMessage() { log.info(() -> String.format("Starting testing sending messages to queue %s with queueUrl %s", getQueueName(), getQueueUrl())); String messageBody = RandomStringUtils.randomAscii(1000); IntFunction<CompletableFuture<?>> futureIntFunction = i -> getTestClient().sendMessage(b -> b.queueUrl(getQueueUrl()).messageBody(messageBody)); runSqsTests("sendMessage", futureIntFunction); } protected void receiveMessage() { log.info(() -> String.format("Starting testing receiving messages from queue %s with queueUrl %s", getQueueName(), getQueueUrl())); IntFunction<CompletableFuture<?>> futureIntFunction = i -> getTestClient().receiveMessage(b -> b.queueUrl(getQueueUrl())) .thenApply( r -> { List<DeleteMessageBatchRequestEntry> batchRequestEntries = r.messages().stream().map(m -> DeleteMessageBatchRequestEntry.builder().id(m.messageId()).receiptHandle(m.receiptHandle()).build()) .collect(Collectors.toList()); return getTestClient().deleteMessageBatch(b -> b.queueUrl(getQueueUrl()).entries(batchRequestEntries)); }); runSqsTests("receiveMessage", futureIntFunction); } private void runSqsTests(String testName, IntFunction<CompletableFuture<?>> futureIntFunction) { StabilityTestRunner.newRunner() .testName("SqsAsyncStabilityTest." + testName) .futureFactory(futureIntFunction) .totalRuns(TOTAL_RUNS) .requestCountPerRun(CONCURRENCY) .delaysBetweenEachRun(Duration.ofMillis(100)) .run(); } }
2,771
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/sqs/SqsNettyAsyncStabilityTest.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.stability.tests.sqs; import java.time.Duration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.sqs.SqsAsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; public class SqsNettyAsyncStabilityTest extends SqsBaseStabilityTest { private static String queueName; private static String queueUrl; private static SqsAsyncClient sqsAsyncClient; @Override protected SqsAsyncClient getTestClient() { return sqsAsyncClient; } @Override protected String getQueueUrl() { return queueUrl; } @Override protected String getQueueName() { return queueName; } @BeforeAll public static void setup() { sqsAsyncClient = SqsAsyncClient.builder() .httpClientBuilder(NettyNioAsyncHttpClient.builder().maxConcurrency(CONCURRENCY)) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(1))) .build(); queueName = "sqsnettyasyncstabilitytests" + System.currentTimeMillis(); queueUrl = setup(sqsAsyncClient, queueName); } @AfterAll public static void tearDown() { tearDown(sqsAsyncClient, queueUrl); sqsAsyncClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void sendMessage_receiveMessage() { sendMessage(); receiveMessage(); } }
2,772
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/transcribestreaming/TranscribeStreamingStabilityTest.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.stability.tests.transcribestreaming; import java.io.InputStream; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode; import software.amazon.awssdk.services.transcribestreaming.model.MediaEncoding; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponse; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; import software.amazon.awssdk.stability.tests.utils.StabilityTestRunner; import software.amazon.awssdk.stability.tests.utils.TestEventStreamingResponseHandler; import software.amazon.awssdk.stability.tests.utils.TestTranscribeStreamingSubscription; import software.amazon.awssdk.testutils.service.AwsTestBase; import software.amazon.awssdk.utils.Logger; public class TranscribeStreamingStabilityTest extends AwsTestBase { private static final Logger log = Logger.loggerFor(TranscribeStreamingStabilityTest.class.getSimpleName()); public static final int CONCURRENCY = 2; public static final int TOTAL_RUNS = 1; private static TranscribeStreamingAsyncClient transcribeStreamingClient; private static InputStream audioFileInputStream; @BeforeAll public static void setup() { transcribeStreamingClient = TranscribeStreamingAsyncClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .httpClientBuilder(NettyNioAsyncHttpClient.builder() .connectionAcquisitionTimeout(Duration.ofSeconds(30)) .maxConcurrency(CONCURRENCY)) .build(); audioFileInputStream = getInputStream(); if (audioFileInputStream == null) { throw new RuntimeException("fail to get the audio input stream"); } } @AfterAll public static void tearDown() { transcribeStreamingClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void startTranscription() { IntFunction<CompletableFuture<?>> futureIntFunction = i -> transcribeStreamingClient.startStreamTranscription(b -> b.mediaSampleRateHertz(8_000) .languageCode(LanguageCode.EN_US) .mediaEncoding(MediaEncoding.PCM), new AudioStreamPublisher(), new TestStartStreamTranscriptionResponseHandler()); StabilityTestRunner.newRunner() .futureFactory(futureIntFunction) .totalRuns(TOTAL_RUNS) .requestCountPerRun(CONCURRENCY) .testName("TranscribeStreamingStabilityTest.startTranscription") .run(); } private static InputStream getInputStream() { return TranscribeStreamingStabilityTest.class.getResourceAsStream("silence_8kHz.wav"); } private class AudioStreamPublisher implements Publisher<AudioStream> { @Override public void subscribe(Subscriber<? super AudioStream> s) { s.onSubscribe(new TestTranscribeStreamingSubscription(s, audioFileInputStream)); } } private static class TestStartStreamTranscriptionResponseHandler extends TestEventStreamingResponseHandler<StartStreamTranscriptionResponse, TranscriptResultStream> implements StartStreamTranscriptionResponseHandler { @Override public void onEventStream(SdkPublisher<TranscriptResultStream> publisher) { publisher .filter(TranscriptEvent.class) .subscribe(result -> log.debug(() -> "Record Batch - " + result.transcript().results())); } } }
2,773
0
Create_ds/aws-sdk-java-v2/codegen-maven-plugin/src/main/java/software/amazon/awssdk/codegen/maven
Create_ds/aws-sdk-java-v2/codegen-maven-plugin/src/main/java/software/amazon/awssdk/codegen/maven/plugin/GenerationMojo.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.codegen.maven.plugin; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.Optional; import java.util.stream.Stream; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.CodeGenerator; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.rules.endpoints.EndpointTestSuiteModel; import software.amazon.awssdk.codegen.model.service.EndpointRuleSetModel; import software.amazon.awssdk.codegen.model.service.Paginators; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Waiters; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; /** * The Maven mojo to generate Java client code using software.amazon.awssdk:codegen module. */ @Mojo(name = "generate") public class GenerationMojo extends AbstractMojo { private static final String MODEL_FILE = "service-2.json"; private static final String CUSTOMIZATION_CONFIG_FILE = "customization.config"; private static final String WAITERS_FILE = "waiters-2.json"; private static final String PAGINATORS_FILE = "paginators-1.json"; private static final String ENDPOINT_RULE_SET_FILE = "endpoint-rule-set.json"; private static final String ENDPOINT_TESTS_FILE = "endpoint-tests.json"; @Parameter(property = "codeGenResources", defaultValue = "${basedir}/src/main/resources/codegen-resources/") private File codeGenResources; @Parameter(property = "outputDirectory", defaultValue = "${project.build.directory}") private String outputDirectory; @Parameter(defaultValue = "false") private boolean writeIntermediateModel; @Parameter(defaultValue = "${project}", readonly = true) private MavenProject project; private Path sourcesDirectory; private Path resourcesDirectory; private Path testsDirectory; @Override public void execute() throws MojoExecutionException { this.sourcesDirectory = Paths.get(outputDirectory).resolve("generated-sources").resolve("sdk"); this.resourcesDirectory = Paths.get(outputDirectory).resolve("generated-resources").resolve("sdk-resources"); this.testsDirectory = Paths.get(outputDirectory).resolve("generated-test-sources").resolve("sdk-tests"); findModelRoots().forEach(p -> { Path modelRootPath = p.modelRoot; getLog().info("Loading from: " + modelRootPath.toString()); generateCode(C2jModels.builder() .customizationConfig(p.customizationConfig) .serviceModel(loadServiceModel(modelRootPath)) .waitersModel(loadWaiterModel(modelRootPath)) .paginatorsModel(loadPaginatorModel(modelRootPath)) .endpointRuleSetModel(loadEndpointRuleSetModel(modelRootPath)) .endpointTestSuiteModel(loadEndpointTestSuiteModel(modelRootPath)) .build()); }); project.addCompileSourceRoot(sourcesDirectory.toFile().getAbsolutePath()); project.addTestCompileSourceRoot(testsDirectory.toFile().getAbsolutePath()); } private Stream<ModelRoot> findModelRoots() throws MojoExecutionException { try { return Files.find(codeGenResources.toPath(), 10, this::isModelFile) .map(Path::getParent) .map(p -> new ModelRoot(p, loadCustomizationConfig(p))) .sorted(this::modelSharersLast); } catch (IOException e) { throw new MojoExecutionException("Failed to find '" + MODEL_FILE + "' files in " + codeGenResources, e); } } private int modelSharersLast(ModelRoot lhs, ModelRoot rhs) { return lhs.customizationConfig.getShareModelConfig() == null ? -1 : 1; } private boolean isModelFile(Path p, BasicFileAttributes a) { return p.toString().endsWith(MODEL_FILE); } private void generateCode(C2jModels models) { CodeGenerator.builder() .models(models) .sourcesDirectory(sourcesDirectory.toFile().getAbsolutePath()) .resourcesDirectory(resourcesDirectory.toFile().getAbsolutePath()) .testsDirectory(testsDirectory.toFile().getAbsolutePath()) .intermediateModelFileNamePrefix(intermediateModelFileNamePrefix(models)) .build() .execute(); } private String intermediateModelFileNamePrefix(C2jModels models) { return writeIntermediateModel ? Utils.getFileNamePrefix(models.serviceModel()) : null; } private CustomizationConfig loadCustomizationConfig(Path root) { return ModelLoaderUtils.loadOptionalModel(CustomizationConfig.class, root.resolve(CUSTOMIZATION_CONFIG_FILE).toFile(), true) .orElse(CustomizationConfig.create()); } private ServiceModel loadServiceModel(Path root) { return loadRequiredModel(ServiceModel.class, root.resolve(MODEL_FILE)); } private Waiters loadWaiterModel(Path root) { return loadOptionalModel(Waiters.class, root.resolve(WAITERS_FILE)).orElse(Waiters.none()); } private Paginators loadPaginatorModel(Path root) { return loadOptionalModel(Paginators.class, root.resolve(PAGINATORS_FILE)).orElse(Paginators.none()); } private EndpointRuleSetModel loadEndpointRuleSetModel(Path root) { return loadOptionalModel(EndpointRuleSetModel.class, root.resolve(ENDPOINT_RULE_SET_FILE)).orElse(null); } private EndpointTestSuiteModel loadEndpointTestSuiteModel(Path root) { return loadOptionalModel(EndpointTestSuiteModel.class, root.resolve(ENDPOINT_TESTS_FILE)).orElse(null); } /** * Load required model from the project resources. */ private <T> T loadRequiredModel(Class<T> clzz, Path location) { return ModelLoaderUtils.loadModel(clzz, location.toFile()); } /** * Load an optional model from the project resources. * * @return Model or empty optional if not present. */ private <T> Optional<T> loadOptionalModel(Class<T> clzz, Path location) { return ModelLoaderUtils.loadOptionalModel(clzz, location.toFile()); } private static class ModelRoot { private final Path modelRoot; private final CustomizationConfig customizationConfig; private ModelRoot(Path modelRoot, CustomizationConfig customizationConfig) { this.modelRoot = modelRoot; this.customizationConfig = customizationConfig; } } }
2,774
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/SdkHttpRequestResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; 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.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import java.util.AbstractMap; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; import org.junit.jupiter.api.Test; /** * Verify that {@link DefaultSdkHttpFullRequest} and {@link DefaultSdkHttpFullResponse} properly fulfill the contracts in their * interfaces. */ public class SdkHttpRequestResponseTest { @Test public void optionalValuesAreOptional() { assertThat(validRequest().contentStreamProvider()).isNotPresent(); assertThat(validResponse().content()).isNotPresent(); assertThat(validResponse().statusText()).isNotPresent(); } @Test public void requestHeaderMapsAreCopiedWhenModified() { assertRequestHeaderMapsAreCopied(b -> b.putHeader("foo", "bar")); assertRequestHeaderMapsAreCopied(b -> b.putHeader("foo", singletonList("bar"))); assertRequestHeaderMapsAreCopied(b -> b.appendHeader("foo", "bar")); assertRequestHeaderMapsAreCopied(b -> b.headers(emptyMap())); assertRequestHeaderMapsAreCopied(b -> b.clearHeaders()); assertRequestHeaderMapsAreCopied(b -> b.removeHeader("Accept")); } @Test public void requestQueryStringMapsAreCopiedWhenModified() { assertRequestQueryStringMapsAreCopied(b -> b.putRawQueryParameter("foo", "bar")); assertRequestQueryStringMapsAreCopied(b -> b.putRawQueryParameter("foo", singletonList("bar"))); assertRequestQueryStringMapsAreCopied(b -> b.appendRawQueryParameter("foo", "bar")); assertRequestQueryStringMapsAreCopied(b -> b.rawQueryParameters(emptyMap())); assertRequestQueryStringMapsAreCopied(b -> b.clearQueryParameters()); assertRequestQueryStringMapsAreCopied(b -> b.removeQueryParameter("Accept")); } @Test public void responseHeaderMapsAreCopiedWhenModified() { assertResponseHeaderMapsAreCopied(b -> b.putHeader("foo", "bar")); assertResponseHeaderMapsAreCopied(b -> b.putHeader("foo", singletonList("bar"))); assertResponseHeaderMapsAreCopied(b -> b.appendHeader("foo", "bar")); assertResponseHeaderMapsAreCopied(b -> b.headers(emptyMap())); assertResponseHeaderMapsAreCopied(b -> b.clearHeaders()); assertResponseHeaderMapsAreCopied(b -> b.removeHeader("Accept")); } private void assertRequestHeaderMapsAreCopied(Consumer<SdkHttpRequest.Builder> mutation) { SdkHttpFullRequest request = validRequestWithMaps(); Map<String, List<String>> originalQuery = new LinkedHashMap<>(request.headers()); SdkHttpFullRequest.Builder builder = request.toBuilder(); assertThat(request.headers()).isEqualTo(builder.headers()); builder.applyMutation(mutation); SdkHttpFullRequest request2 = builder.build(); assertThat(request.headers()).isEqualTo(originalQuery); assertThat(request.headers()).isNotEqualTo(request2.headers()); } private void assertRequestQueryStringMapsAreCopied(Consumer<SdkHttpRequest.Builder> mutation) { SdkHttpFullRequest request = validRequestWithMaps(); Map<String, List<String>> originalQuery = new LinkedHashMap<>(request.rawQueryParameters()); SdkHttpFullRequest.Builder builder = request.toBuilder(); assertThat(request.rawQueryParameters()).isEqualTo(builder.rawQueryParameters()); builder.applyMutation(mutation); SdkHttpFullRequest request2 = builder.build(); assertThat(request.rawQueryParameters()).isEqualTo(originalQuery); assertThat(request.rawQueryParameters()).isNotEqualTo(request2.rawQueryParameters()); } private void assertResponseHeaderMapsAreCopied(Consumer<SdkHttpResponse.Builder> mutation) { SdkHttpResponse response = validResponseWithMaps(); Map<String, List<String>> originalQuery = new LinkedHashMap<>(response.headers()); SdkHttpResponse.Builder builder = response.toBuilder(); assertThat(response.headers()).isEqualTo(builder.headers()); builder.applyMutation(mutation); SdkHttpResponse response2 = builder.build(); assertThat(response.headers()).isEqualTo(originalQuery); assertThat(response.headers()).isNotEqualTo(response2.headers()); } @Test public void headersAreUnmodifiable() { assertThatThrownBy(() -> validRequest().headers().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validResponse().headers().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validRequest().toBuilder().headers().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validResponse().toBuilder().headers().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validRequest().toBuilder().build().headers().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validResponse().toBuilder().build().headers().clear()).isInstanceOf(UnsupportedOperationException.class); } @Test public void queryStringsAreUnmodifiable() { assertThatThrownBy(() -> validRequest().rawQueryParameters().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validRequest().toBuilder().rawQueryParameters().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validRequest().toBuilder().build().rawQueryParameters().clear()).isInstanceOf(UnsupportedOperationException.class); } @Test public void uriConversionIsCorrect() { assertThat(normalizedUri(b -> b.protocol("http").host("localhost"))).isEqualTo("http://localhost"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80))).isEqualTo("http://localhost"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(8080))).isEqualTo("http://localhost:8080"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(443))).isEqualTo("http://localhost:443"); assertThat(normalizedUri(b -> b.protocol("https").host("localhost").port(443))).isEqualTo("https://localhost"); assertThat(normalizedUri(b -> b.protocol("https").host("localhost").port(8443))).isEqualTo("https://localhost:8443"); assertThat(normalizedUri(b -> b.protocol("https").host("localhost").port(80))).isEqualTo("https://localhost:80"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("foo"))) .isEqualTo("http://localhost/foo"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("/foo"))) .isEqualTo("http://localhost/foo"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("foo/"))) .isEqualTo("http://localhost/foo/"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("/foo/"))) .isEqualTo("http://localhost/foo/"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).putRawQueryParameter("foo", "bar "))) .isEqualTo("http://localhost?foo=bar%20"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("/foo").putRawQueryParameter("foo", "bar"))) .isEqualTo("http://localhost/foo?foo=bar"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("foo/").putRawQueryParameter("foo", "bar"))) .isEqualTo("http://localhost/foo/?foo=bar"); } private String normalizedUri(Consumer<SdkHttpRequest.Builder> builderMutator) { return validRequestBuilder().applyMutation(builderMutator).build().getUri().toString(); } @Test public void protocolNormalizationIsCorrect() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> normalizedProtocol(null)); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> normalizedProtocol("foo")); assertThat(normalizedProtocol("http")).isEqualTo("http"); assertThat(normalizedProtocol("https")).isEqualTo("https"); assertThat(normalizedProtocol("HtTp")).isEqualTo("http"); assertThat(normalizedProtocol("HtTpS")).isEqualTo("https"); } private String normalizedProtocol(String protocol) { return validRequestBuilder().protocol(protocol).build().protocol(); } @Test public void hostNormalizationIsCorrect() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> normalizedHost(null)); assertThat(normalizedHost("foo")).isEqualTo("foo"); } private String normalizedHost(String host) { return validRequestBuilder().host(host).build().host(); } @Test public void portNormalizationIsCorrect() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> normalizedPort("http", -2)); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> normalizedPort("https", -2)); assertThat(normalizedPort("http", -1)).isEqualTo(80); assertThat(normalizedPort("http", null)).isEqualTo(80); assertThat(normalizedPort("https", -1)).isEqualTo(443); assertThat(normalizedPort("https", null)).isEqualTo(443); assertThat(normalizedPort("http", 8080)).isEqualTo(8080); assertThat(normalizedPort("https", 8443)).isEqualTo(8443); } private int normalizedPort(String protocol, Integer port) { return validRequestBuilder().protocol(protocol).port(port).build().port(); } @Test public void requestPathNormalizationIsCorrect() { assertThat(normalizedPath(null)).isEqualTo(""); assertThat(normalizedPath("/")).isEqualTo("/"); assertThat(normalizedPath(" ")).isEqualTo("/ "); assertThat(normalizedPath(" /")).isEqualTo("/ /"); assertThat(normalizedPath("/ ")).isEqualTo("/ "); assertThat(normalizedPath("/ /")).isEqualTo("/ /"); assertThat(normalizedPath(" / ")).isEqualTo("/ / "); assertThat(normalizedPath("/Foo/")).isEqualTo("/Foo/"); assertThat(normalizedPath("Foo/")).isEqualTo("/Foo/"); assertThat(normalizedPath("Foo")).isEqualTo("/Foo"); assertThat(normalizedPath("/Foo/bar/")).isEqualTo("/Foo/bar/"); assertThat(normalizedPath("Foo/bar/")).isEqualTo("/Foo/bar/"); assertThat(normalizedPath("/Foo/bar")).isEqualTo("/Foo/bar"); assertThat(normalizedPath("Foo/bar")).isEqualTo("/Foo/bar"); assertThat(normalizedPath("%2F")).isEqualTo("/%2F"); } private String normalizedPath(String path) { return validRequestBuilder().encodedPath(path).build().encodedPath(); } @Test public void requestMethodNormalizationIsCorrect() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> normalizedMethod(null)); assertThat(normalizedMethod(SdkHttpMethod.POST)).isEqualTo(SdkHttpMethod.POST); } private SdkHttpMethod normalizedMethod(SdkHttpMethod method) { return validRequestBuilder().method(method).build().method(); } @Test public void requestQueryParamNormalizationIsCorrect() { headerOrQueryStringNormalizationIsCorrect(() -> new BuilderProxy() { private final SdkHttpRequest.Builder builder = validRequestBuilder(); @Override public BuilderProxy setValue(String key, String value) { builder.putRawQueryParameter(key, value); return this; } @Override public BuilderProxy appendValue(String key, String value) { builder.appendRawQueryParameter(key, value); return this; } @Override public BuilderProxy setValues(String key, List<String> values) { builder.putRawQueryParameter(key, values); return this; } @Override public BuilderProxy removeValue(String key) { builder.removeQueryParameter(key); return this; } @Override public BuilderProxy clearValues() { builder.clearQueryParameters(); return this; } @Override public BuilderProxy setMap(Map<String, List<String>> map) { builder.rawQueryParameters(map); return this; } @Override public Map<String, List<String>> getMap() { return builder.build().rawQueryParameters(); } }); } @Test public void requestHeaderNormalizationIsCorrect() { headerOrQueryStringNormalizationIsCorrect(() -> new BuilderProxy() { private final SdkHttpRequest.Builder builder = validRequestBuilder(); @Override public BuilderProxy setValue(String key, String value) { builder.putHeader(key, value); return this; } @Override public BuilderProxy appendValue(String key, String value) { builder.appendHeader(key, value); return this; } @Override public BuilderProxy setValues(String key, List<String> values) { builder.putHeader(key, values); return this; } @Override public BuilderProxy removeValue(String key) { builder.removeHeader(key); return this; } @Override public BuilderProxy clearValues() { builder.clearHeaders(); return this; } @Override public BuilderProxy setMap(Map<String, List<String>> map) { builder.headers(map); return this; } @Override public Map<String, List<String>> getMap() { return builder.build().headers(); } }); } @Test public void responseStatusCodeNormalizationIsCorrect() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> normalizedStatusCode(-1)); assertThat(normalizedStatusCode(200)).isEqualTo(200); } private int normalizedStatusCode(int statusCode) { return validResponseBuilder().statusCode(statusCode).build().statusCode(); } @Test public void responseHeaderNormalizationIsCorrect() { headerOrQueryStringNormalizationIsCorrect(() -> new BuilderProxy() { private final SdkHttpFullResponse.Builder builder = validResponseBuilder(); @Override public BuilderProxy setValue(String key, String value) { builder.putHeader(key, value); return this; } @Override public BuilderProxy appendValue(String key, String value) { builder.appendHeader(key, value); return this; } @Override public BuilderProxy setValues(String key, List<String> values) { builder.putHeader(key, values); return this; } @Override public BuilderProxy removeValue(String key) { builder.removeHeader(key); return this; } @Override public BuilderProxy clearValues() { builder.clearHeaders(); return this; } @Override public BuilderProxy setMap(Map<String, List<String>> map) { builder.headers(map); return this; } @Override public Map<String, List<String>> getMap() { return builder.build().headers(); } }); } @Test public void testSdkHttpFullRequestBuilderNoQueryParams() { URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034"); final SdkHttpFullRequest sdkHttpFullRequest = SdkHttpFullRequest.builder().method(SdkHttpMethod.POST).uri(uri).build(); assertThat(sdkHttpFullRequest.getUri().getQuery()).isNullOrEmpty(); } @Test public void testSdkHttpFullRequestBuilderUriWithQueryParams() { URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034?reqParam=1234&oParam=3456%26reqParam%3D5678"); final SdkHttpFullRequest sdkHttpFullRequest = SdkHttpFullRequest.builder().method(SdkHttpMethod.POST).uri(uri).build(); assertThat(sdkHttpFullRequest.getUri().getQuery()).contains("reqParam=1234", "oParam=3456&reqParam=5678"); } @Test public void testSdkHttpFullRequestBuilderUriWithQueryParamWithoutValue() { final String expected = "https://github.com/aws/aws-sdk-for-java-v2?foo"; URI myUri = URI.create(expected); SdkHttpFullRequest actual = SdkHttpFullRequest.builder().method(SdkHttpMethod.POST).uri(myUri).build(); assertThat(actual.getUri()).hasToString(expected); } @Test public void testSdkHttpRequestBuilderNoQueryParams() { URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034"); final SdkHttpRequest sdkHttpRequest = SdkHttpRequest.builder().method(SdkHttpMethod.POST).uri(uri).build(); assertThat(sdkHttpRequest.getUri().getQuery()).isNullOrEmpty(); } @Test public void testSdkHttpRequestBuilderUriWithQueryParams() { URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034?reqParam=1234&oParam=3456%26reqParam%3D5678"); final SdkHttpRequest sdkHttpRequest = SdkHttpRequest.builder().method(SdkHttpMethod.POST).uri(uri).build(); assertThat(sdkHttpRequest.getUri().getQuery()).contains("reqParam=1234", "oParam=3456&reqParam=5678"); } @Test public void testSdkHttpRequestBuilderUriWithQueryParamsIgnoreOtherQueryParams() { URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034?reqParam=1234&oParam=3456%26reqParam%3D5678"); final SdkHttpRequest sdkHttpRequest = SdkHttpRequest.builder().method(SdkHttpMethod.POST).appendRawQueryParameter("clean", "up").uri(uri).build(); assertThat(sdkHttpRequest.getUri().getQuery()).contains("reqParam=1234", "oParam=3456&reqParam=5678") .doesNotContain("clean"); } @Test public void testSdkHttpRequestBuilderUriWithQueryParamWithoutValue() { final String expected = "https://github.com/aws/aws-sdk-for-java-v2?foo"; URI myUri = URI.create(expected); SdkHttpRequest actual = SdkHttpRequest.builder().method(SdkHttpMethod.POST).uri(myUri).build(); assertThat(actual.getUri()).hasToString(expected); } private interface BuilderProxy { BuilderProxy setValue(String key, String value); BuilderProxy appendValue(String key, String value); BuilderProxy setValues(String key, List<String> values); BuilderProxy removeValue(String key); BuilderProxy clearValues(); BuilderProxy setMap(Map<String, List<String>> map); Map<String, List<String>> getMap(); } private void headerOrQueryStringNormalizationIsCorrect(Supplier<BuilderProxy> builderFactory) { assertMapIsInitiallyEmpty(builderFactory); setValue_SetsSingleValueCorrectly(builderFactory); setValue_SettingMultipleKeysAppendsToMap(builderFactory); setValue_OverwritesExistingValue(builderFactory); setValues_SetsAllValuesCorrectly(builderFactory); setValue_OverwritesAllExistingValues(builderFactory); removeValue_OnlyRemovesThatKey(builderFactory); clearValues_RemovesAllExistingValues(builderFactory); setMap_OverwritesAllExistingValues(builderFactory); appendWithExistingValues_AddsValueToList(builderFactory); appendWithNoValues_AddsSingleElementToList(builderFactory); } private void assertMapIsInitiallyEmpty(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setMap(emptyMap()).getMap()).isEmpty(); } private void setValue_SetsSingleValueCorrectly(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValue("Foo", "Bar").getMap()).satisfies(params -> { assertThat(params).containsOnlyKeys("Foo"); assertThat(params.get("Foo")).containsExactly("Bar"); }); } private void setValue_SettingMultipleKeysAppendsToMap(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValue("Foo", "Bar").setValue("Foo2", "Bar2").getMap()).satisfies(params -> { assertThat(params).containsOnlyKeys("Foo", "Foo2"); assertThat(params.get("Foo")).containsExactly("Bar"); assertThat(params.get("Foo2")).containsExactly("Bar2"); }); } private void setValue_OverwritesExistingValue(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValue("Foo", "Bar").setValue("Foo", "Bar2").getMap()).satisfies(params -> { assertThat(params).containsOnlyKeys("Foo"); assertThat(params.get("Foo")).containsExactly("Bar2"); }); } private void setValues_SetsAllValuesCorrectly(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Foo", Arrays.asList("Bar", "Baz")).getMap()).satisfies(params -> { assertThat(params).containsOnlyKeys("Foo"); assertThat(params.get("Foo")).containsExactly("Bar", "Baz"); }); } private void setValue_OverwritesAllExistingValues(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Foo", Arrays.asList("Bar", "Baz")).setValue("Foo", "Bar").getMap()) .satisfies(params -> { assertThat(params).containsOnlyKeys("Foo"); assertThat(params.get("Foo")).containsExactly("Bar"); }); } private void removeValue_OnlyRemovesThatKey(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Foo", Arrays.asList("Bar", "Baz")) .setValues("Foo2", Arrays.asList("Bar", "Baz")) .removeValue("Foo").getMap()) .satisfies(params -> { assertThat(params).doesNotContainKeys("Foo"); assertThat(params.get("Foo2")).containsExactly("Bar", "Baz"); }); } private void clearValues_RemovesAllExistingValues(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Foo", Arrays.asList("Bar", "Baz")).clearValues().getMap()) .doesNotContainKeys("Foo"); } private void setMap_OverwritesAllExistingValues(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Foo", Arrays.asList("Bar", "Baz")) .setMap(singletonMap("Foo2", singletonList("Baz2"))).getMap()) .satisfies(params -> { assertThat(params).containsOnlyKeys("Foo2"); assertThat(params.get("Foo2")).containsExactly("Baz2"); }); } private void appendWithExistingValues_AddsValueToList(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Key", Arrays.asList("Foo", "Bar")) .appendValue("Key", "Baz").getMap()) .satisfies(params -> { assertThat(params).containsOnly(new AbstractMap.SimpleEntry<>("Key", Arrays.asList("Foo", "Bar", "Baz"))); }); } private void appendWithNoValues_AddsSingleElementToList(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().appendValue("AppendNotExists", "Baz").getMap()) .satisfies(params -> { assertThat(params).containsOnly(new AbstractMap.SimpleEntry<>("AppendNotExists", Arrays.asList("Baz"))); }); } private SdkHttpFullRequest validRequestWithMaps() { return validRequestWithMapsBuilder().build(); } private SdkHttpFullRequest.Builder validRequestWithMapsBuilder() { return validRequestBuilder().putHeader("Accept", "*/*") .putRawQueryParameter("Accept", "*/*"); } private SdkHttpFullRequest validRequest() { return validRequestBuilder().build(); } private SdkHttpFullRequest.Builder validRequestBuilder() { return SdkHttpFullRequest.builder() .protocol("http") .host("localhost") .method(SdkHttpMethod.GET); } private SdkHttpResponse validResponseWithMaps() { return validResponseWithMapsBuilder().build(); } private SdkHttpResponse.Builder validResponseWithMapsBuilder() { return validResponseBuilder().putHeader("Accept", "*/*"); } private SdkHttpFullResponse validResponse() { return validResponseBuilder().build(); } private SdkHttpFullResponse.Builder validResponseBuilder() { return SdkHttpFullResponse.builder().statusCode(500); } }
2,775
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/TlsKeyManagersProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class TlsKeyManagersProviderTest { @Test public void noneProvider_returnsProviderThatReturnsNull() { assertThat(TlsKeyManagersProvider.noneProvider().keyManagers()).isNull(); } }
2,776
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/HttpStatusFamilyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class HttpStatusFamilyTest { @Test public void statusFamiliesAreMappedCorrectly() { assertThat(HttpStatusFamily.of(-1)).isEqualTo(HttpStatusFamily.OTHER); assertThat(HttpStatusFamily.of(HttpStatusCode.CONTINUE)).isEqualTo(HttpStatusFamily.INFORMATIONAL); assertThat(HttpStatusFamily.of(HttpStatusCode.OK)).isEqualTo(HttpStatusFamily.SUCCESSFUL); assertThat(HttpStatusFamily.of(HttpStatusCode.MOVED_PERMANENTLY)).isEqualTo(HttpStatusFamily.REDIRECTION); assertThat(HttpStatusFamily.of(HttpStatusCode.NOT_FOUND)).isEqualTo(HttpStatusFamily.CLIENT_ERROR); assertThat(HttpStatusFamily.of(HttpStatusCode.INTERNAL_SERVER_ERROR)).isEqualTo(HttpStatusFamily.SERVER_ERROR); } @Test public void matchingIsCorrect() { assertThat(HttpStatusFamily.SUCCESSFUL.isOneOf()).isFalse(); assertThat(HttpStatusFamily.SUCCESSFUL.isOneOf(null)).isFalse(); assertThat(HttpStatusFamily.SUCCESSFUL.isOneOf(HttpStatusFamily.CLIENT_ERROR)).isFalse(); assertThat(HttpStatusFamily.SUCCESSFUL.isOneOf(HttpStatusFamily.CLIENT_ERROR, HttpStatusFamily.SUCCESSFUL)).isTrue(); assertThat(HttpStatusFamily.SUCCESSFUL.isOneOf(HttpStatusFamily.SUCCESSFUL, HttpStatusFamily.CLIENT_ERROR)).isTrue(); assertThat(HttpStatusFamily.OTHER.isOneOf(HttpStatusFamily.values())).isTrue(); } }
2,777
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/SdkHttpExecutionAttributesTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.AttributeMap; class SdkHttpExecutionAttributesTest { @Test void equalsAndHashcode() { AttributeMap one = AttributeMap.empty(); AttributeMap two = AttributeMap.builder().put(TestExecutionAttribute.TEST_KEY_FOO, "test").build(); EqualsVerifier.forClass(SdkHttpExecutionAttributes.class) .withNonnullFields("attributes") .withPrefabValues(AttributeMap.class, one, two) .verify(); } @Test void getAttribute_shouldReturnCorrectValue() { SdkHttpExecutionAttributes attributes = SdkHttpExecutionAttributes.builder() .put(TestExecutionAttribute.TEST_KEY_FOO, "test") .build(); assertThat(attributes.getAttribute(TestExecutionAttribute.TEST_KEY_FOO)).isEqualTo("test"); } private static final class TestExecutionAttribute<T> extends SdkHttpExecutionAttribute<T> { private static final TestExecutionAttribute<String> TEST_KEY_FOO = new TestExecutionAttribute<>(String.class); private TestExecutionAttribute(Class valueType) { super(valueType); } } }
2,778
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/ClientTlsAuthTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; abstract class ClientTlsAuthTestBase { protected static final String STORE_PASSWORD = "password"; protected static final String CLIENT_STORE_TYPE = "pkcs12"; protected static final String TEST_KEY_STORE = "/software/amazon/awssdk/http/server-keystore"; protected static final String CLIENT_KEY_STORE = "/software/amazon/awssdk/http/client1.p12"; protected static Path tempDir; protected static Path serverKeyStore; protected static Path clientKeyStore; @BeforeAll public static void setUp() throws IOException { tempDir = Files.createTempDirectory(ClientTlsAuthTestBase.class.getSimpleName()); copyCertsToTmpDir(); } @AfterAll public static void teardown() throws IOException { Files.deleteIfExists(serverKeyStore); Files.deleteIfExists(clientKeyStore); Files.deleteIfExists(tempDir); } private static void copyCertsToTmpDir() throws IOException { InputStream sksStream = ClientTlsAuthTestBase.class.getResourceAsStream(TEST_KEY_STORE); Path sks = copyToTmpDir(sksStream, "server-keystore"); InputStream cksStream = ClientTlsAuthTestBase.class.getResourceAsStream(CLIENT_KEY_STORE); Path cks = copyToTmpDir(cksStream, "client1.p12"); serverKeyStore = sks; clientKeyStore = cks; } private static Path copyToTmpDir(InputStream srcStream, String name) throws IOException { Path dst = tempDir.resolve(name); Files.copy(srcStream, dst); return dst; } }
2,779
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/FileStoreTlsKeyManagersProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.nio.file.Paths; import java.security.Security; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class FileStoreTlsKeyManagersProviderTest extends ClientTlsAuthTestBase { @BeforeClass public static void setUp() throws IOException { ClientTlsAuthTestBase.setUp(); } @AfterClass public static void teardown() throws IOException { ClientTlsAuthTestBase.teardown(); } @Test(expected = NullPointerException.class) public void storePathNull_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(null, CLIENT_STORE_TYPE, STORE_PASSWORD); } @Test(expected = NullPointerException.class) public void storeTypeNull_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, null, STORE_PASSWORD); } @Test(expected = IllegalArgumentException.class) public void storeTypeEmpty_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, "", STORE_PASSWORD); } @Test public void passwordNotGiven_doesNotThrowValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, null); } @Test public void paramsValid_createsKeyManager() { FileStoreTlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, STORE_PASSWORD); assertThat(provider.keyManagers()).hasSize(1); } @Test public void storeDoesNotExist_returnsNull() { FileStoreTlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(Paths.get("does", "not", "exist"), CLIENT_STORE_TYPE, STORE_PASSWORD); assertThat(provider.keyManagers()).isNull(); } @Test public void invalidStoreType_returnsNull() { FileStoreTlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, "invalid", STORE_PASSWORD); assertThat(provider.keyManagers()).isNull(); } @Test public void passwordIncorrect_returnsNull() { FileStoreTlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, "not correct password"); assertThat(provider.keyManagers()).isNull(); } @Test public void customKmfAlgorithmSetInProperty_usesAlgorithm() { FileStoreTlsKeyManagersProvider beforePropSetProvider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, STORE_PASSWORD); assertThat(beforePropSetProvider.keyManagers()).isNotNull(); String property = "ssl.KeyManagerFactory.algorithm"; String previousValue = Security.getProperty(property); Security.setProperty(property, "some-bogus-value"); try { FileStoreTlsKeyManagersProvider afterPropSetProvider = FileStoreTlsKeyManagersProvider.create( clientKeyStore, CLIENT_STORE_TYPE, STORE_PASSWORD); // This would otherwise be non-null if using the right algorithm, // i.e. not setting the algorithm property will cause the assertion // to fail assertThat(afterPropSetProvider.keyManagers()).isNull(); } finally { Security.setProperty(property, previousValue); } } }
2,780
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/SystemPropertyTlsKeyManagersProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_PASSWORD; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_TYPE; import java.io.IOException; import java.nio.file.Paths; import java.security.Security; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class SystemPropertyTlsKeyManagersProviderTest extends ClientTlsAuthTestBase { private static final SystemPropertyTlsKeyManagersProvider PROVIDER = SystemPropertyTlsKeyManagersProvider.create(); @BeforeAll public static void setUp() throws IOException { ClientTlsAuthTestBase.setUp(); } @AfterEach public void methodTeardown() { System.clearProperty(SSL_KEY_STORE.property()); System.clearProperty(SSL_KEY_STORE_TYPE.property()); System.clearProperty(SSL_KEY_STORE_PASSWORD.property()); } @AfterAll public static void teardown() throws IOException { ClientTlsAuthTestBase.teardown(); } @Test public void propertiesNotSet_returnsNull() { assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void propertiesSet_createsKeyManager() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).hasSize(1); } @Test public void storeDoesNotExist_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), Paths.get("does", "not", "exist").toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void invalidStoreType_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), "invalid"); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void passwordIncorrect_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), "not correct password"); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void customKmfAlgorithmSetInProperty_usesAlgorithm() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNotNull(); String property = "ssl.KeyManagerFactory.algorithm"; String previousValue = Security.getProperty(property); Security.setProperty(property, "some-bogus-value"); try { // This would otherwise be non-null if using the right algorithm, // i.e. not setting the algorithm property will cause the assertion // to fail assertThat(PROVIDER.keyManagers()).isNull(); } finally { Security.setProperty(property, previousValue); } } }
2,781
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/software/amazon/awssdk/internal
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/software/amazon/awssdk/internal/http/NoneTlsKeyManagersProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.software.amazon.awssdk.internal.http; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.internal.http.NoneTlsKeyManagersProvider; public class NoneTlsKeyManagersProviderTest { @Test public void getInstance_returnsNonNull() { assertThat(NoneTlsKeyManagersProvider.getInstance()).isNotNull(); } @Test public void keyManagers_returnsNull() { assertThat(NoneTlsKeyManagersProvider.getInstance().keyManagers()).isNull(); } @Test public void getInstance_returnsSingletonInstance() { NoneTlsKeyManagersProvider provider1 = NoneTlsKeyManagersProvider.getInstance(); NoneTlsKeyManagersProvider provider2 = NoneTlsKeyManagersProvider.getInstance(); assertThat(provider1 == provider2).isTrue(); } }
2,782
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal/http/NoneTlsKeyManagersProvider.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.internal.http; import javax.net.ssl.KeyManager; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.TlsKeyManagersProvider; /** * Simple implementation of {@link TlsKeyManagersProvider} that return a null array. * <p> * Use this provider if you don't want the client to present any certificates to the remote TLS host. */ @SdkInternalApi public final class NoneTlsKeyManagersProvider implements TlsKeyManagersProvider { private static final NoneTlsKeyManagersProvider INSTANCE = new NoneTlsKeyManagersProvider(); private NoneTlsKeyManagersProvider() { } @Override public KeyManager[] keyManagers() { return null; } public static NoneTlsKeyManagersProvider getInstance() { return INSTANCE; } }
2,783
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal/http/AbstractFileStoreTlsKeyManagersProvider.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.internal.http; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.TlsKeyManagersProvider; /** * Abstract {@link TlsKeyManagersProvider} that loads the key store from a * a given file path. * <p> * This uses {@link KeyManagerFactory#getDefaultAlgorithm()} to determine the * {@code KeyManagerFactory} algorithm to use. */ @SdkInternalApi public abstract class AbstractFileStoreTlsKeyManagersProvider implements TlsKeyManagersProvider { protected final KeyManager[] createKeyManagers(Path storePath, String storeType, char[] password) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, UnrecoverableKeyException { KeyStore ks = createKeyStore(storePath, storeType, password); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password); return kmf.getKeyManagers(); } private KeyStore createKeyStore(Path storePath, String storeType, char[] password) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { KeyStore ks = KeyStore.getInstance(storeType); try (InputStream storeIs = Files.newInputStream(storePath)) { ks.load(storeIs, password); return ks; } } }
2,784
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal/http/LowCopyListMap.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.internal.http; import static software.amazon.awssdk.utils.CollectionUtils.deepCopyMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.function.Supplier; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.Lazy; /** * A {@code Map<String, List<String>>} for headers and query strings in {@link SdkHttpRequest} and {@link SdkHttpResponse} that * avoids copying data during conversion between builders and buildables, unless data is modified. * * This is created via {@link #emptyHeaders()} or {@link #emptyQueryParameters()}. */ @SdkInternalApi public final class LowCopyListMap { private LowCopyListMap() { } /** * Create an empty {@link LowCopyListMap.ForBuilder} for header storage. */ public static LowCopyListMap.ForBuilder emptyHeaders() { return new LowCopyListMap.ForBuilder(() -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); } /** * Create an empty {@link LowCopyListMap.ForBuilder} for query parameter storage. */ public static LowCopyListMap.ForBuilder emptyQueryParameters() { return new LowCopyListMap.ForBuilder(LinkedHashMap::new); } @NotThreadSafe public static final class ForBuilder { /** * The constructor that can be used to create new, empty maps. */ private final Supplier<Map<String, List<String>>> mapConstructor; /** * Whether {@link #map} has been shared with a {@link ForBuildable}. If this is true, we need to make sure to copy the * map before we mutate it. */ private boolean mapIsShared = false; /** * The data stored in this low-copy list-map. */ private Map<String, List<String>> map; /** * Created from {@link LowCopyListMap#emptyHeaders()} or {@link LowCopyListMap#emptyQueryParameters()}. */ private ForBuilder(Supplier<Map<String, List<String>>> mapConstructor) { this.mapConstructor = mapConstructor; this.map = mapConstructor.get(); } /** * Created from {@link LowCopyListMap.ForBuildable#forBuilder()}. */ private ForBuilder(ForBuildable forBuildable) { this.mapConstructor = forBuildable.mapConstructor; this.map = forBuildable.map; this.mapIsShared = true; } public void clear() { this.map = mapConstructor.get(); this.mapIsShared = false; } public void setFromExternal(Map<String, List<String>> map) { this.map = deepCopyMap(map, mapConstructor); this.mapIsShared = false; } public Map<String, List<String>> forInternalWrite() { if (mapIsShared) { this.map = deepCopyMap(map, mapConstructor); this.mapIsShared = false; } return this.map; } public Map<String, List<String>> forInternalRead() { return this.map; } public ForBuildable forBuildable() { this.mapIsShared = true; return new ForBuildable(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ForBuilder that = (ForBuilder) o; return map.equals(that.map); } @Override public int hashCode() { return map.hashCode(); } } @ThreadSafe public static final class ForBuildable { /** * The constructor that can be used to create new, empty maps. */ private final Supplier<Map<String, List<String>>> mapConstructor; /** * An unmodifiable copy of {@link #map}, which is lazily initialized only when it is needed. */ private final Lazy<Map<String, List<String>>> deeplyUnmodifiableMap; /** * The data stored in this low-copy list-map. */ private final Map<String, List<String>> map; private ForBuildable(ForBuilder forBuilder) { this.mapConstructor = forBuilder.mapConstructor; this.map = forBuilder.map; this.deeplyUnmodifiableMap = new Lazy<>(() -> CollectionUtils.deepUnmodifiableMap(this.map, this.mapConstructor)); } public Map<String, List<String>> forExternalRead() { return deeplyUnmodifiableMap.getValue(); } public Map<String, List<String>> forInternalRead() { return map; } public ForBuilder forBuilder() { return new ForBuilder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ForBuildable that = (ForBuildable) o; return map.equals(that.map); } @Override public int hashCode() { return map.hashCode(); } } }
2,785
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/FileStoreTlsKeyManagersProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.nio.file.Path; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.internal.http.AbstractFileStoreTlsKeyManagersProvider; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * Implementation of {@link FileStoreTlsKeyManagersProvider} that loads a the * key store from a file. * <p> * This uses {@link KeyManagerFactory#getDefaultAlgorithm()} to determine the * {@code KeyManagerFactory} algorithm to use. */ @SdkPublicApi public final class FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { private static final Logger log = Logger.loggerFor(FileStoreTlsKeyManagersProvider.class); private final Path storePath; private final String storeType; private final char[] password; private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password) { this.storePath = Validate.paramNotNull(storePath, "storePath"); this.storeType = Validate.paramNotBlank(storeType, "storeType"); this.password = password; } @Override public KeyManager[] keyManagers() { try { return createKeyManagers(storePath, storeType, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from file %s", storePath), e); return null; } } public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } }
2,786
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpExecutionAttributes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An immutable collection of {@link SdkHttpExecutionAttribute}s that can be configured on an {@link AsyncExecuteRequest} via * {@link AsyncExecuteRequest.Builder#httpExecutionAttributes(SdkHttpExecutionAttributes)} */ @SdkPublicApi public final class SdkHttpExecutionAttributes implements ToCopyableBuilder<SdkHttpExecutionAttributes.Builder, SdkHttpExecutionAttributes> { private final AttributeMap attributes; private SdkHttpExecutionAttributes(Builder builder) { this.attributes = builder.sdkHttpExecutionAttributes.build(); } /** * Retrieve the current value of the provided attribute in this collection of attributes. This will return null if the value * is not set. */ public <T> T getAttribute(SdkHttpExecutionAttribute<T> attribute) { return attributes.get(attribute); } public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return new Builder(attributes); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SdkHttpExecutionAttributes that = (SdkHttpExecutionAttributes) o; return Objects.equals(attributes, that.attributes); } @Override public int hashCode() { return attributes.hashCode(); } public static final class Builder implements CopyableBuilder<SdkHttpExecutionAttributes.Builder, SdkHttpExecutionAttributes> { private AttributeMap.Builder sdkHttpExecutionAttributes = AttributeMap.builder(); private Builder(AttributeMap attributes) { sdkHttpExecutionAttributes = attributes.toBuilder(); } private Builder() { } /** * Add a mapping between the provided key and value. */ public <T> SdkHttpExecutionAttributes.Builder put(SdkHttpExecutionAttribute<T> key, T value) { Validate.notNull(key, "Key to set must not be null."); sdkHttpExecutionAttributes.put(key, value); return this; } /** * Adds all the attributes from the map provided. */ public SdkHttpExecutionAttributes.Builder putAll(Map<? extends SdkHttpExecutionAttribute<?>, ?> attributes) { sdkHttpExecutionAttributes.putAll(attributes); return this; } @Override public SdkHttpExecutionAttributes build() { return new SdkHttpExecutionAttributes(this); } } }
2,787
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/TlsTrustManagersProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import javax.net.ssl.TrustManager; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Provider for the {@link TrustManager trust managers} to be used by the SDK when * creating the SSL context. Trust managers are used when the client is checking * if the remote host can be trusted. */ @SdkPublicApi @FunctionalInterface public interface TlsTrustManagersProvider { /** * @return The {@link TrustManager}s, or {@code null}. */ TrustManager[] trustManagers(); }
2,788
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SystemPropertyTlsKeyManagersProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_PASSWORD; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_TYPE; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.util.Optional; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.internal.http.AbstractFileStoreTlsKeyManagersProvider; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.internal.SystemSettingUtils; /** * Implementation of {@link TlsKeyManagersProvider} that gets the information * about the KeyStore to load from the system properties. * <p> * This provider checks the standard {@code javax.net.ssl.keyStore}, * {@code javax.net.ssl.keyStorePassword}, and * {@code javax.net.ssl.keyStoreType} properties defined by the * <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html">JSSE</a>. * <p> * This uses {@link KeyManagerFactory#getDefaultAlgorithm()} to determine the * {@code KeyManagerFactory} algorithm to use. */ @SdkPublicApi public final class SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { private static final Logger log = Logger.loggerFor(SystemPropertyTlsKeyManagersProvider.class); private SystemPropertyTlsKeyManagersProvider() { } @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } public static SystemPropertyTlsKeyManagersProvider create() { return new SystemPropertyTlsKeyManagersProvider(); } private static Optional<String> getKeyStore() { return SystemSettingUtils.resolveSetting(SSL_KEY_STORE); } private static String getKeyStoreType() { return SystemSettingUtils.resolveSetting(SSL_KEY_STORE_TYPE) .orElseGet(KeyStore::getDefaultType); } private static Optional<String> getKeyStorePassword() { return SystemSettingUtils.resolveSetting(SSL_KEY_STORE_PASSWORD); } }
2,789
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/HttpExecuteResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.io.InputStream; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; @SdkPublicApi public class HttpExecuteResponse { private final SdkHttpResponse response; private final Optional<AbortableInputStream> responseBody; private HttpExecuteResponse(BuilderImpl builder) { this.response = builder.response; this.responseBody = builder.responseBody; } /** * @return The HTTP response. */ public SdkHttpResponse httpResponse() { return response; } /** * /** Get the {@link AbortableInputStream} associated with this response. * * <p>Always close the "responseBody" input stream to release the underlying HTTP connection. * Even for error responses, the SDK creates an input stream for reading error data. It is essential to close the input stream * in the "responseBody" attribute for both success and error cases. * * @return An {@link Optional} containing the {@link AbortableInputStream} if available. */ public Optional<AbortableInputStream> responseBody() { return responseBody; } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * Set the HTTP response to be executed by the client. * * @param response The response. * @return This builder for method chaining. */ Builder response(SdkHttpResponse response); /** * Set the {@link InputStream} to be returned by the client. * @param inputStream The {@link InputStream} * @return This builder for method chaining */ Builder responseBody(AbortableInputStream inputStream); HttpExecuteResponse build(); } private static class BuilderImpl implements Builder { private SdkHttpResponse response; private Optional<AbortableInputStream> responseBody = Optional.empty(); @Override public Builder response(SdkHttpResponse response) { this.response = response; return this; } @Override public Builder responseBody(AbortableInputStream responseBody) { this.responseBody = Optional.ofNullable(responseBody); return this; } @Override public HttpExecuteResponse build() { return new HttpExecuteResponse(this); } } }
2,790
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/Http2Metric.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.metrics.MetricCategory; import software.amazon.awssdk.metrics.MetricLevel; import software.amazon.awssdk.metrics.SdkMetric; /** * Metrics collected by HTTP clients for HTTP/2 operations. See {@link HttpMetric} for metrics that are available on both HTTP/1 * and HTTP/2 operations. */ @SdkPublicApi public final class Http2Metric { /** * The local HTTP/2 window size in bytes for the stream that this request was executed on. * * <p>See https://http2.github.io/http2-spec/#FlowControl for more information on HTTP/2 window sizes. */ public static final SdkMetric<Integer> LOCAL_STREAM_WINDOW_SIZE_IN_BYTES = metric("LocalStreamWindowSize", Integer.class, MetricLevel.TRACE); /** * The remote HTTP/2 window size in bytes for the stream that this request was executed on. * * <p>See https://http2.github.io/http2-spec/#FlowControl for more information on HTTP/2 window sizes. */ public static final SdkMetric<Integer> REMOTE_STREAM_WINDOW_SIZE_IN_BYTES = metric("RemoteStreamWindowSize", Integer.class, MetricLevel.TRACE); private Http2Metric() { } private static <T> SdkMetric<T> metric(String name, Class<T> clzz, MetricLevel level) { return SdkMetric.create(name, clzz, level, MetricCategory.CORE, MetricCategory.HTTP_CLIENT); } }
2,791
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/DefaultSdkHttpFullRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.internal.http.LowCopyListMap; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * Internal implementation of {@link SdkHttpFullRequest}, buildable via {@link SdkHttpFullRequest#builder()}. Provided to HTTP * implementation to execute a request. */ @SdkInternalApi @Immutable final class DefaultSdkHttpFullRequest implements SdkHttpFullRequest { private final String protocol; private final String host; private final Integer port; private final String path; private final LowCopyListMap.ForBuildable queryParameters; private final LowCopyListMap.ForBuildable headers; private final SdkHttpMethod httpMethod; private final ContentStreamProvider contentStreamProvider; private DefaultSdkHttpFullRequest(Builder builder) { this.protocol = standardizeProtocol(builder.protocol); this.host = Validate.paramNotNull(builder.host, "host"); this.port = standardizePort(builder.port); this.path = standardizePath(builder.path); this.httpMethod = Validate.paramNotNull(builder.httpMethod, "method"); this.contentStreamProvider = builder.contentStreamProvider; this.queryParameters = builder.queryParameters.forBuildable(); this.headers = builder.headers.forBuildable(); } private String standardizeProtocol(String protocol) { Validate.paramNotNull(protocol, "protocol"); String standardizedProtocol = StringUtils.lowerCase(protocol); Validate.isTrue(standardizedProtocol.equals("http") || standardizedProtocol.equals("https"), "Protocol must be 'http' or 'https', but was %s", protocol); return standardizedProtocol; } private String standardizePath(String path) { if (StringUtils.isEmpty(path)) { return ""; } StringBuilder standardizedPath = new StringBuilder(); // Path must always start with '/' if (!path.startsWith("/")) { standardizedPath.append('/'); } standardizedPath.append(path); return standardizedPath.toString(); } private Integer standardizePort(Integer port) { Validate.isTrue(port == null || port >= -1, "Port must be positive (or null/-1 to indicate no port), but was '%s'", port); if (port != null && port == -1) { return null; } return port; } @Override public String protocol() { return protocol; } @Override public String host() { return host; } @Override public int port() { return Optional.ofNullable(port).orElseGet(() -> SdkHttpUtils.standardPort(protocol())); } @Override public Map<String, List<String>> headers() { return headers.forExternalRead(); } @Override public List<String> matchingHeaders(String header) { return unmodifiableList(headers.forInternalRead().getOrDefault(header, emptyList())); } @Override public Optional<String> firstMatchingHeader(String headerName) { List<String> headers = this.headers.forInternalRead().get(headerName); if (headers == null || headers.isEmpty()) { return Optional.empty(); } String header = headers.get(0); if (StringUtils.isEmpty(header)) { return Optional.empty(); } return Optional.of(header); } @Override public Optional<String> firstMatchingHeader(Collection<String> headersToFind) { for (String headerName : headersToFind) { Optional<String> header = firstMatchingHeader(headerName); if (header.isPresent()) { return header; } } return Optional.empty(); } @Override public void forEachHeader(BiConsumer<? super String, ? super List<String>> consumer) { headers.forInternalRead().forEach((k, v) -> consumer.accept(k, Collections.unmodifiableList(v))); } @Override public void forEachRawQueryParameter(BiConsumer<? super String, ? super List<String>> consumer) { queryParameters.forInternalRead().forEach((k, v) -> consumer.accept(k, Collections.unmodifiableList(v))); } @Override public int numHeaders() { return headers.forInternalRead().size(); } @Override public int numRawQueryParameters() { return queryParameters.forInternalRead().size(); } @Override public Optional<String> encodedQueryParameters() { return SdkHttpUtils.encodeAndFlattenQueryParameters(queryParameters.forInternalRead()); } @Override public Optional<String> encodedQueryParametersAsFormData() { return SdkHttpUtils.encodeAndFlattenFormData(queryParameters.forInternalRead()); } @Override public String encodedPath() { return path; } @Override public Map<String, List<String>> rawQueryParameters() { return queryParameters.forExternalRead(); } @Override public Optional<String> firstMatchingRawQueryParameter(String key) { List<String> values = queryParameters.forInternalRead().get(key); return values == null ? Optional.empty() : values.stream().findFirst(); } @Override public Optional<String> firstMatchingRawQueryParameter(Collection<String> keys) { for (String key : keys) { Optional<String> result = firstMatchingRawQueryParameter(key); if (result.isPresent()) { return result; } } return Optional.empty(); } @Override public List<String> firstMatchingRawQueryParameters(String key) { List<String> values = queryParameters.forInternalRead().get(key); return values == null ? emptyList() : unmodifiableList(values); } @Override public SdkHttpMethod method() { return httpMethod; } @Override public Optional<ContentStreamProvider> contentStreamProvider() { return Optional.ofNullable(contentStreamProvider); } @Override public SdkHttpFullRequest.Builder toBuilder() { return new Builder(this); } @Override public String toString() { return ToString.builder("DefaultSdkHttpFullRequest") .add("httpMethod", httpMethod) .add("protocol", protocol) .add("host", host) .add("port", port) .add("encodedPath", path) .add("headers", headers.forInternalRead().keySet()) .add("queryParameters", queryParameters.forInternalRead().keySet()) .build(); } /** * Builder for a {@link DefaultSdkHttpFullRequest}. */ static final class Builder implements SdkHttpFullRequest.Builder { private String protocol; private String host; private Integer port; private String path; private LowCopyListMap.ForBuilder queryParameters; private LowCopyListMap.ForBuilder headers; private SdkHttpMethod httpMethod; private ContentStreamProvider contentStreamProvider; Builder() { queryParameters = LowCopyListMap.emptyQueryParameters(); headers = LowCopyListMap.emptyHeaders(); } Builder(DefaultSdkHttpFullRequest request) { queryParameters = request.queryParameters.forBuilder(); headers = request.headers.forBuilder(); protocol = request.protocol; host = request.host; port = request.port; path = request.path; httpMethod = request.httpMethod; contentStreamProvider = request.contentStreamProvider; } @Override public String protocol() { return protocol; } @Override public SdkHttpFullRequest.Builder protocol(String protocol) { this.protocol = protocol; return this; } @Override public String host() { return host; } @Override public SdkHttpFullRequest.Builder host(String host) { this.host = host; return this; } @Override public Integer port() { return port; } @Override public SdkHttpFullRequest.Builder port(Integer port) { this.port = port; return this; } @Override public DefaultSdkHttpFullRequest.Builder encodedPath(String path) { this.path = path; return this; } @Override public String encodedPath() { return path; } @Override public DefaultSdkHttpFullRequest.Builder putRawQueryParameter(String paramName, List<String> paramValues) { this.queryParameters.forInternalWrite().put(paramName, new ArrayList<>(paramValues)); return this; } @Override public SdkHttpFullRequest.Builder appendRawQueryParameter(String paramName, String paramValue) { this.queryParameters.forInternalWrite().computeIfAbsent(paramName, k -> new ArrayList<>()).add(paramValue); return this; } @Override public DefaultSdkHttpFullRequest.Builder rawQueryParameters(Map<String, List<String>> queryParameters) { this.queryParameters.setFromExternal(queryParameters); return this; } @Override public Builder removeQueryParameter(String paramName) { this.queryParameters.forInternalWrite().remove(paramName); return this; } @Override public Builder clearQueryParameters() { this.queryParameters.forInternalWrite().clear(); return this; } @Override public Map<String, List<String>> rawQueryParameters() { return CollectionUtils.unmodifiableMapOfLists(queryParameters.forInternalRead()); } @Override public DefaultSdkHttpFullRequest.Builder method(SdkHttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } @Override public SdkHttpMethod method() { return httpMethod; } @Override public DefaultSdkHttpFullRequest.Builder putHeader(String headerName, List<String> headerValues) { this.headers.forInternalWrite().put(headerName, new ArrayList<>(headerValues)); return this; } @Override public SdkHttpFullRequest.Builder appendHeader(String headerName, String headerValue) { this.headers.forInternalWrite().computeIfAbsent(headerName, k -> new ArrayList<>()).add(headerValue); return this; } @Override public DefaultSdkHttpFullRequest.Builder headers(Map<String, List<String>> headers) { this.headers.setFromExternal(headers); return this; } @Override public SdkHttpFullRequest.Builder removeHeader(String headerName) { this.headers.forInternalWrite().remove(headerName); return this; } @Override public SdkHttpFullRequest.Builder clearHeaders() { this.headers.clear(); return this; } @Override public Map<String, List<String>> headers() { return CollectionUtils.unmodifiableMapOfLists(this.headers.forInternalRead()); } @Override public List<String> matchingHeaders(String header) { return unmodifiableList(headers.forInternalRead().getOrDefault(header, emptyList())); } @Override public Optional<String> firstMatchingHeader(String headerName) { List<String> headers = this.headers.forInternalRead().get(headerName); if (headers == null || headers.isEmpty()) { return Optional.empty(); } String header = headers.get(0); if (StringUtils.isEmpty(header)) { return Optional.empty(); } return Optional.of(header); } @Override public Optional<String> firstMatchingHeader(Collection<String> headersToFind) { for (String headerName : headersToFind) { Optional<String> header = firstMatchingHeader(headerName); if (header.isPresent()) { return header; } } return Optional.empty(); } @Override public void forEachHeader(BiConsumer<? super String, ? super List<String>> consumer) { headers.forInternalRead().forEach((k, v) -> consumer.accept(k, unmodifiableList(v))); } @Override public void forEachRawQueryParameter(BiConsumer<? super String, ? super List<String>> consumer) { queryParameters.forInternalRead().forEach((k, v) -> consumer.accept(k, unmodifiableList(v))); } @Override public int numHeaders() { return headers.forInternalRead().size(); } @Override public int numRawQueryParameters() { return queryParameters.forInternalRead().size(); } @Override public Optional<String> encodedQueryParameters() { return SdkHttpUtils.encodeAndFlattenQueryParameters(queryParameters.forInternalRead()); } @Override public DefaultSdkHttpFullRequest.Builder contentStreamProvider(ContentStreamProvider contentStreamProvider) { this.contentStreamProvider = contentStreamProvider; return this; } @Override public ContentStreamProvider contentStreamProvider() { return contentStreamProvider; } @Override public SdkHttpFullRequest.Builder copy() { return build().toBuilder(); } @Override public SdkHttpFullRequest.Builder applyMutation(Consumer<SdkHttpRequest.Builder> mutator) { mutator.accept(this); return this; } @Override public DefaultSdkHttpFullRequest build() { return new DefaultSdkHttpFullRequest(this); } } }
2,792
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpHeaders.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * An immutable set of HTTP headers. {@link SdkHttpRequest} should be used for requests, and {@link SdkHttpResponse} should be * used for responses. */ @SdkPublicApi @Immutable public interface SdkHttpHeaders { /** * Returns a map of all HTTP headers in this message, sorted in case-insensitive order by their header name. * * <p>This will never be null. If there are no headers an empty map is returned.</p> * * @return An unmodifiable map of all headers in this message. */ Map<String, List<String>> headers(); /** * Perform a case-insensitive search for a particular header in this request, returning the first matching header, if one is * found. * * <p>This is useful for headers like 'Content-Type' or 'Content-Length' of which there is expected to be only one value * present.</p> * * <p>This is equivalent to invoking {@link SdkHttpUtils#firstMatchingHeader(Map, String)}</p>. * * @param header The header to search for (case insensitively). * @return The first header that matched the requested one, or empty if one was not found. */ default Optional<String> firstMatchingHeader(String header) { return SdkHttpUtils.firstMatchingHeader(headers(), header); } default Optional<String> firstMatchingHeader(Collection<String> headersToFind) { return SdkHttpUtils.firstMatchingHeaderFromCollection(headers(), headersToFind); } default List<String> matchingHeaders(String header) { return SdkHttpUtils.allMatchingHeaders(headers(), header).collect(Collectors.toList()); } default void forEachHeader(BiConsumer<? super String, ? super List<String>> consumer) { headers().forEach(consumer); } default int numHeaders() { return headers().size(); } }
2,793
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/Protocol.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; public enum Protocol { HTTP1_1, HTTP2 }
2,794
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpFullRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static java.util.Collections.singletonList; import java.net.URI; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * An immutable HTTP request with a possible HTTP body. * * <p>All implementations of this interface MUST be immutable. Instead of implementing this interface, consider using * {@link #builder()} to create an instance.</p> */ @SdkPublicApi @Immutable public interface SdkHttpFullRequest extends SdkHttpRequest { /** * @return Builder instance to construct a {@link DefaultSdkHttpFullRequest}. */ static SdkHttpFullRequest.Builder builder() { return new DefaultSdkHttpFullRequest.Builder(); } @Override SdkHttpFullRequest.Builder toBuilder(); /** * @return The optional {@link ContentStreamProvider} for this request. */ Optional<ContentStreamProvider> contentStreamProvider(); /** * A mutable builder for {@link SdkHttpFullRequest}. An instance of this can be created using * {@link SdkHttpFullRequest#builder()}. */ interface Builder extends SdkHttpRequest.Builder { /** * Convenience method to set the {@link #protocol()}, {@link #host()}, {@link #port()}, * {@link #encodedPath()} and extracts query parameters from a {@link URI} object. * * @param uri URI containing protocol, host, port and path. * @return This builder for method chaining. */ @Override default Builder uri(URI uri) { Builder builder = this.protocol(uri.getScheme()) .host(uri.getHost()) .port(uri.getPort()) .encodedPath(SdkHttpUtils.appendUri(uri.getRawPath(), encodedPath())); if (uri.getRawQuery() != null) { builder.clearQueryParameters(); SdkHttpUtils.uriParams(uri) .forEach(this::putRawQueryParameter); } return builder; } /** * The protocol, exactly as it was configured with {@link #protocol(String)}. */ @Override String protocol(); /** * Configure a {@link SdkHttpRequest#protocol()} to be used in the created HTTP request. This is not validated until the * http request is created. */ @Override Builder protocol(String protocol); /** * The host, exactly as it was configured with {@link #host(String)}. */ @Override String host(); /** * Configure a {@link SdkHttpRequest#host()} to be used in the created HTTP request. This is not validated until the * http request is created. */ @Override Builder host(String host); /** * The port, exactly as it was configured with {@link #port(Integer)}. */ @Override Integer port(); /** * Configure a {@link SdkHttpRequest#port()} to be used in the created HTTP request. This is not validated until the * http request is created. In order to simplify mapping from a {@link URI}, "-1" will be treated as "null" when the http * request is created. */ @Override Builder port(Integer port); /** * The path, exactly as it was configured with {@link #encodedPath(String)}. */ @Override String encodedPath(); /** * Configure an {@link SdkHttpRequest#encodedPath()} to be used in the created HTTP request. This is not validated * until the http request is created. This path MUST be URL encoded. * * <p>Justification of requirements: The path must be encoded when it is configured, because there is no way for the HTTP * implementation to distinguish a "/" that is part of a resource name that should be encoded as "%2F" from a "/" that is * part of the actual path.</p> */ @Override Builder encodedPath(String path); /** * The query parameters, exactly as they were configured with {@link #rawQueryParameters(Map)}, * {@link #putRawQueryParameter(String, String)} and {@link #putRawQueryParameter(String, List)}. */ @Override Map<String, List<String>> rawQueryParameters(); /** * Add a single un-encoded query parameter to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this parameter name in the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValue The un-encoded value for the query parameter. */ @Override default Builder putRawQueryParameter(String paramName, String paramValue) { return putRawQueryParameter(paramName, singletonList(paramValue)); } /** * Add a single un-encoded query parameter to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this parameter name in * the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValue The un-encoded value for the query parameter. */ @Override Builder appendRawQueryParameter(String paramName, String paramValue); /** * Add a single un-encoded query parameter with multiple values to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this parameter name in the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValues The un-encoded values for the query parameter. */ @Override Builder putRawQueryParameter(String paramName, List<String> paramValues); /** * Configure an {@link SdkHttpRequest#rawQueryParameters()} to be used in the created HTTP request. This is not validated * until the http request is created. This overrides any values currently configured in the builder. The query parameters * MUST NOT be URL encoded. * * <p>Justification of requirements: The query parameters must not be encoded when they are configured because some HTTP * implementations perform this encoding automatically.</p> */ @Override Builder rawQueryParameters(Map<String, List<String>> queryParameters); /** * Remove all values for the requested query parameter from this builder. */ @Override Builder removeQueryParameter(String paramName); /** * Removes all query parameters from this builder. */ @Override Builder clearQueryParameters(); /** * The path, exactly as it was configured with {@link #method(SdkHttpMethod)}. */ @Override SdkHttpMethod method(); /** * Configure an {@link SdkHttpRequest#method()} to be used in the created HTTP request. This is not validated * until the http request is created. */ @Override Builder method(SdkHttpMethod httpMethod); /** * The query parameters, exactly as they were configured with {@link #headers(Map)}, * {@link #putHeader(String, String)} and {@link #putHeader(String, List)}. */ @Override Map<String, List<String>> headers(); /** * Add a single header to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add (eg. "Host") * @param headerValue The value for the header */ @Override default Builder putHeader(String headerName, String headerValue) { return putHeader(headerName, singletonList(headerValue)); } /** * Add a single header with multiple values to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add * @param headerValues The values for the header */ @Override Builder putHeader(String headerName, List<String> headerValues); /** * Add a single header to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this header name in * the builder.</p> * * @param headerName The name of the header to add * @param headerValue The value for the header */ @Override Builder appendHeader(String headerName, String headerValue); /** * Configure an {@link SdkHttpRequest#headers()} to be used in the created HTTP request. This is not validated * until the http request is created. This overrides any values currently configured in the builder. */ @Override Builder headers(Map<String, List<String>> headers); /** * Remove all values for the requested header from this builder. */ @Override Builder removeHeader(String headerName); /** * Removes all headers from this builder. */ @Override Builder clearHeaders(); /** * Set the {@link ContentStreamProvider} for this request. * * @param contentStreamProvider The ContentStreamProvider. * @return This object for method chaining. */ Builder contentStreamProvider(ContentStreamProvider contentStreamProvider); /** * @return The {@link ContentStreamProvider} for this request. */ ContentStreamProvider contentStreamProvider(); @Override SdkHttpFullRequest.Builder copy(); @Override SdkHttpFullRequest.Builder applyMutation(Consumer<SdkHttpRequest.Builder> mutator); @Override SdkHttpFullRequest build(); } }
2,795
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Interface to take a representation of an HTTP request, make an HTTP call, and return a representation of an HTTP response. * * <p>Implementations MUST be thread safe.</p> */ @Immutable @ThreadSafe @SdkPublicApi public interface SdkHttpClient extends SdkAutoCloseable { /** * Create a {@link ExecutableHttpRequest} that can be used to execute the HTTP request. * * @param request Representation of an HTTP request. * @return Task that can execute an HTTP request and can be aborted. */ ExecutableHttpRequest prepareRequest(HttpExecuteRequest request); /** * Each HTTP client implementation should return a well-formed client name * that allows requests to be identifiable back to the client that made the request. * The client name should include the backing implementation as well as the Sync or Async * to identify the transmission type of the request. Client names should only include * alphanumeric characters. Examples of well formed client names include, ApacheSync, for * requests using Apache's synchronous http client or NettyNioAsync for Netty's asynchronous * http client. * * @return String containing the name of the client */ default String clientName() { return "UNKNOWN"; } /** * Interface for creating an {@link SdkHttpClient} with service specific defaults applied. */ @FunctionalInterface interface Builder<T extends SdkHttpClient.Builder<T>> extends SdkBuilder<T, SdkHttpClient> { /** * Create a {@link SdkHttpClient} with global defaults applied. This is useful for reusing an HTTP client across multiple * services. */ @Override default SdkHttpClient build() { return buildWithDefaults(AttributeMap.empty()); } /** * Create an {@link SdkHttpClient} with service specific defaults and defaults from {@code DefaultsMode} applied. * Applying service defaults is optional and some options may not be supported by a particular implementation. * * @param serviceDefaults Service specific defaults. Keys will be one of the constants defined in * {@link SdkHttpConfigurationOption}. * @return Created client */ SdkHttpClient buildWithDefaults(AttributeMap serviceDefaults); } }
2,796
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/AbortableInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static software.amazon.awssdk.utils.Validate.paramNotNull; import java.io.ByteArrayInputStream; import java.io.FilterInputStream; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; /** * Input stream that can be aborted. Abort typically means to destroy underlying HTTP connection * without reading more data. This may be desirable when the cost of reading the rest of the data * exceeds that of establishing a new connection. */ @SdkProtectedApi public final class AbortableInputStream extends FilterInputStream implements Abortable { private final Abortable abortable; private AbortableInputStream(InputStream delegate, Abortable abortable) { super(paramNotNull(delegate, "delegate")); this.abortable = paramNotNull(abortable, "abortable"); } /** * Creates an instance of {@link AbortableInputStream}. * * @param delegate the delegated input stream * @param abortable the abortable * @return a new instance of AbortableInputStream */ public static AbortableInputStream create(InputStream delegate, Abortable abortable) { return new AbortableInputStream(delegate, abortable); } /** * Creates an instance of {@link AbortableInputStream} that ignores abort. * * @param delegate the delegated input stream * @return a new instance of AbortableInputStream */ public static AbortableInputStream create(InputStream delegate) { if (delegate instanceof Abortable) { return new AbortableInputStream(delegate, (Abortable) delegate); } return new AbortableInputStream(delegate, () -> { }); } public static AbortableInputStream createEmpty() { return create(new ByteArrayInputStream(new byte[0])); } @Override public void abort() { abortable.abort(); } /** * Access the underlying delegate stream, for testing purposes. */ @SdkTestInternalApi public InputStream delegate() { return in; } }
2,797
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpMethod.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.util.Locale; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Enum for available HTTP methods. */ @SdkProtectedApi public enum SdkHttpMethod { GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS,; /** * @param value Raw string representing value of enum * @return HttpMethodName enum or null if value is not present. * @throws IllegalArgumentException If value does not represent a known enum value. */ public static SdkHttpMethod fromValue(String value) { if (value == null || value.isEmpty()) { return null; } String upperCaseValue = value.toUpperCase(Locale.ENGLISH); return Stream.of(values()) .filter(h -> h.name().equals(upperCaseValue)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Unsupported HTTP method name " + value)); } }
2,798
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/ContentStreamProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Provides the content stream of a request. * <p> * Each call to to the {@link #newStream()} method must result in a stream whose position is at the beginning of the content. * Implementations may return a new stream or the same stream for each call. If returning a new stream, the implementation * must ensure to {@code close()} and free any resources acquired by the previous stream. The last stream returned by {@link * #newStream()}} will be closed by the SDK. * */ @SdkPublicApi @FunctionalInterface public interface ContentStreamProvider { /** * @return The content stream. */ InputStream newStream(); }
2,799