index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/document/VoidDocumentVisitorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.document;
import org.testng.annotations.Test;
import software.amazon.awssdk.core.SdkNumber;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
public class VoidDocumentVisitorTest {
@Test
public void voidDocumentVisitor() {
VoidDocumentVisitCount voidDocumentVisitor = new VoidDocumentVisitCount();
// Constructing a Document for CustomClass
final Document build = getCustomDocument();
build.accept(voidDocumentVisitor);
assertThat(voidDocumentVisitor.booleanVisitsVisits).isEqualTo(2);
assertThat(voidDocumentVisitor.mapVisits).isEqualTo(2);
assertThat(voidDocumentVisitor.nullVisits).isEqualTo(1);
assertThat(voidDocumentVisitor.listVisits).isEqualTo(1);
assertThat(voidDocumentVisitor.numberVisits).isEqualTo(4);
assertThat(voidDocumentVisitor.stringVisits).isEqualTo(2);
// Expected CustomClass
}
public Document getCustomDocument() {
final Document build = Document.mapBuilder()
.putDocument("customClassFromMap",
Document.mapBuilder().putString("innerStringField", "innerValue")
.putNumber("innerIntField", SdkNumber.fromLong(1)).build())
.putString("outerStringField", "outerValue")
.putNull("nullKey")
.putBoolean("boolOne", true)
.putBoolean("boolTwo", false)
.putList("listKey", listBuilder -> listBuilder.addNumber(SdkNumber.fromLong(2)).addNumber(SdkNumber.fromLong(3)))
.putNumber("outerLongField", SdkNumber.fromDouble(4)).build();
return build;
}
private static class VoidDocumentVisitCount implements VoidDocumentVisitor {
private int nullVisits = 0;
private int mapVisits = 0;
private int listVisits = 0;
private int stringVisits = 0;
private int numberVisits = 0;
private int booleanVisitsVisits = 0;
public int getNullVisits() {
return nullVisits;
}
public int getMapVisits() {
return mapVisits;
}
public int getListVisits() {
return listVisits;
}
public int getStringVisits() {
return stringVisits;
}
public int getNumberVisits() {
return numberVisits;
}
public int getBooleanVisitsVisits() {
return booleanVisitsVisits;
}
@Override
public void visitNull() {
nullVisits++;
}
@Override
public void visitBoolean(Boolean document) {
booleanVisitsVisits++;
}
@Override
public void visitString(String document) {
stringVisits++;
}
@Override
public void visitNumber(SdkNumber document) {
numberVisits++;
}
@Override
public void visitMap(Map<String, Document> documentMap) {
mapVisits++;
documentMap.values().stream().forEach(val -> val.accept(this));
}
@Override
public void visitList(List<Document> documentList) {
listVisits++;
documentList.forEach(item -> item.accept(this));
}
}
@Test
public void defaultVoidDocumentVisitor() {
VoidDocumentVisitor voidDocumentVisitor = new VoidDocumentVisitor() {
};
Document.fromNull().accept(voidDocumentVisitor);
Document.fromNumber(2).accept(voidDocumentVisitor);
Document.fromString("testString").accept(voidDocumentVisitor);
Document.fromBoolean(true).accept(voidDocumentVisitor);
Document.listBuilder().addNumber(4).build().accept(voidDocumentVisitor);
Document.mapBuilder().putNumber("key", 4).build().accept(voidDocumentVisitor);
}
}
| 2,000 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/document/DocumentVisitorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.document;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.testng.annotations.Test;
import software.amazon.awssdk.core.SdkNumber;
import static org.assertj.core.api.Assertions.assertThat;
public class DocumentVisitorTest {
@Test
public void testACustomDocumentVisitor() {
// Constructing a Document for CustomClass
final Document build = Document.mapBuilder()
.putDocument("customClassFromMap",
Document.mapBuilder().putString("innerStringField", "innerValue")
.putNumber("innerIntField", SdkNumber.fromLong(99)).build())
.putString("outerStringField", "outerValue")
.putNumber("outerLongField", SdkNumber.fromDouble(1)).build();
final CustomClass customClassExtracted = build.accept(new CustomDocumentVisitor());
// Expected CustomClass
final CustomClassFromMap innerMap = new CustomClassFromMap();
innerMap.setInnerIntField(99);
innerMap.setInnerStringField("innerValue");
CustomClass expectedCustomClass = new CustomClass();
expectedCustomClass.setOuterLongField(1L);
expectedCustomClass.setOuterStringField("outerValue");
expectedCustomClass.setCustomClassFromMap(innerMap);
assertThat(customClassExtracted).isEqualTo(expectedCustomClass);
}
@Test
public void testDocumentVisitorWhenMethodNotImplemented(){
DocumentVisitor<Object> documentVisitor = new DocumentVisitor<Object>() {
@Override
public Object visitNull() { return null; }
@Override
public Object visitBoolean(Boolean document) { return null; }
@Override
public Object visitString(String document) { return null; }
@Override
public Object visitNumber(SdkNumber document) { return null; }
@Override
public Object visitMap(Map<String, Document> documentMap) { return null; }
@Override
public Object visitList(List<Document> documentList) { return null; }
};
assertThat(Document.fromNumber(2).accept(documentVisitor)).isNull();
assertThat(Document.fromString("2").accept(documentVisitor)).isNull();
assertThat(Document.fromNull().accept(documentVisitor)).isNull();
assertThat(Document.fromBoolean(true).accept(documentVisitor)).isNull();
assertThat(Document.fromMap(new LinkedHashMap<>()).accept(documentVisitor)).isNull();
assertThat(Document.fromList(new ArrayList<>()).accept(documentVisitor)).isNull();
}
/*
Below are auxiliary classes to test Custom class visitors.
*/
private static class CustomClassFromMap {
String innerStringField;
Integer innerIntField;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CustomClassFromMap)) return false;
CustomClassFromMap that = (CustomClassFromMap) o;
return Objects.equals(innerStringField, that.innerStringField) &&
Objects.equals(innerIntField, that.innerIntField);
}
@Override
public int hashCode() {
return Objects.hash(innerStringField, innerIntField);
}
public void setInnerStringField(String innerStringField) {
this.innerStringField = innerStringField;
}
public void setInnerIntField(Integer innerIntField) {
this.innerIntField = innerIntField;
}
}
private static class CustomClass implements Serializable {
String outerStringField;
Long outerLongField;
CustomClassFromMap customClassFromMap;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CustomClass)) return false;
CustomClass that = (CustomClass) o;
return Objects.equals(outerStringField, that.outerStringField) &&
Objects.equals(outerLongField, that.outerLongField) &&
Objects.equals(customClassFromMap, that.customClassFromMap);
}
public void setOuterStringField(String outerStringField) {
this.outerStringField = outerStringField;
}
public void setOuterLongField(Long outerLongField) {
this.outerLongField = outerLongField;
}
public void setCustomClassFromMap(CustomClassFromMap customClassFromMap) {
this.customClassFromMap = customClassFromMap;
}
}
/**
* Visitor to fetch attribute values for CustomClassFromMap.
*/
private static class CustomMapDocumentVisitor implements DocumentVisitor<CustomClassFromMap> {
@Override
public CustomClassFromMap visitNull() { return null; }
@Override
public CustomClassFromMap visitBoolean(Boolean document) { return null; }
@Override
public CustomClassFromMap visitString(String document) { return null; }
@Override
public CustomClassFromMap visitNumber(SdkNumber document) { return null; }
@Override
public CustomClassFromMap visitMap(Map<String, Document> documentMap) {
CustomClassFromMap customClassFromMap = new CustomClassFromMap();
documentMap.entrySet().stream().forEach(stringDocumentEntry -> {
if ("innerStringField".equals(stringDocumentEntry.getKey())) {
customClassFromMap.setInnerStringField(stringDocumentEntry.getValue().accept(new StringDocumentVisitor()));
} else if ("innerIntField".equals(stringDocumentEntry.getKey())) {
customClassFromMap.setInnerIntField(stringDocumentEntry.getValue().accept(new NumberDocumentVisitor()).intValue());
}
});
return customClassFromMap;
}
@Override
public CustomClassFromMap visitList(List<Document> documentList) {
return null;
}
}
/**
* Visitor to fetch attribute values for CustomClass.
*/
private static class CustomDocumentVisitor implements DocumentVisitor<CustomClass> {
private final CustomClass customClass = new CustomClass();
@Override
public CustomClass visitNull() {
return null;
}
@Override
public CustomClass visitBoolean(Boolean document) {
return null;
}
@Override
public CustomClass visitString(String document) {
return null;
}
@Override
public CustomClass visitNumber(SdkNumber document) {
return null;
}
@Override
public CustomClass visitMap(Map<String, Document> documentMap) {
documentMap.entrySet().stream().forEach(stringDocumentEntry -> {
if ("customClassFromMap".equals(stringDocumentEntry.getKey())) {
final CustomMapDocumentVisitor customMapDocumentVisitor = new CustomMapDocumentVisitor();
customClass.setCustomClassFromMap(stringDocumentEntry.getValue().accept(customMapDocumentVisitor));
} else if ("outerStringField".equals(stringDocumentEntry.getKey())) {
customClass.setOuterStringField(
stringDocumentEntry.getValue().accept(new StringDocumentVisitor()));
} else if ("outerLongField".equals(stringDocumentEntry.getKey())) {
customClass.setOuterLongField(stringDocumentEntry.getValue().accept(new NumberDocumentVisitor()).longValue());
}
});
return customClass;
}
@Override
public CustomClass visitList(List<Document> documentList) {
return null;
}
}
private static class StringDocumentVisitor implements DocumentVisitor<String> {
@Override
public String visitNull() { return null; }
@Override
public String visitBoolean(Boolean document) { return null; }
@Override
public String visitString(String document) { return document; }
@Override
public String visitNumber(SdkNumber document) { return null; }
@Override
public String visitMap(Map<String, Document> documentMap) { return null; }
@Override
public String visitList(List<Document> documentList) { return null; }
}
private static class NumberDocumentVisitor implements DocumentVisitor<SdkNumber> {
@Override
public SdkNumber visitNull() { return null; }
@Override
public SdkNumber visitBoolean(Boolean document) { return null; }
@Override
public SdkNumber visitString(String document) { return null; }
@Override
public SdkNumber visitNumber(SdkNumber document) { return document; }
@Override
public SdkNumber visitMap(Map<String, Document> documentMap) { return null; }
@Override
public SdkNumber visitList(List<Document> documentList) { return null; }
}
}
| 2,001 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/document/UnwrapDocumentTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.document;
import org.testng.annotations.Test;
import software.amazon.awssdk.core.SdkNumber;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
public class UnwrapDocumentTest {
@Test
public void testMapDocumentUnwrap() {
final Document mapDocument = Document.mapBuilder().putString("key", "stringValue")
.putDocument("documentKey", Document.fromString("documentValue"))
.build();
final Object unwrappedMapObject = mapDocument.unwrap();
final long unwrappedMapCountAsString = ((Map<?, ?>) unwrappedMapObject).entrySet().stream()
.filter(k -> k.getKey() instanceof String && k.getValue() instanceof String).count();
final long unwrappedMapCountAsDocument = ((Map<?, ?>) unwrappedMapObject).entrySet().stream()
.filter(k -> k.getKey() instanceof String && k.getValue() instanceof Document).count();
assertThat(unwrappedMapCountAsString).isEqualTo(2);
assertThat(unwrappedMapCountAsDocument).isZero();
}
@Test
public void testListDocumentUnwrap() {
final Document documentList = Document.fromList(Arrays.asList(Document.fromNumber(SdkNumber.fromLong(1)), Document.fromNumber(SdkNumber.fromLong(2))));
final Object documentListAsObjects = documentList.unwrap();
final Optional strippedAsSDKNumber = ((List) documentListAsObjects)
.stream().filter(e -> e instanceof String).findAny();
final Optional strippedAsDocuments = ((List) documentListAsObjects)
.stream().filter(e -> e instanceof Document).findAny();
assertThat(strippedAsSDKNumber).isPresent();
assertThat(strippedAsDocuments).isNotPresent();
}
@Test
public void testStringDocumentUnwrap() {
final Document testDocument = Document.fromString("testDocument");
assertThat(testDocument.unwrap()).isEqualTo("testDocument");
}
@Test
public void testNumberDocumentUnwrap() {
final Document testDocument = Document.fromNumber(SdkNumber.fromLong(2));
assertThat(testDocument.unwrap()).isEqualTo(SdkNumber.fromLong(2).stringValue());
}
@Test
public void testBoolanDocumentUnwrap() {
final Document testDocument = Document.fromBoolean(true);
assertThat(testDocument.unwrap()).isEqualTo(true);
}
@Test
public void testNullDocumentUnwrap() {
final Document testDocument = Document.fromNull();
assertThat(testDocument.unwrap()).isNull();
}
}
| 2,002 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/document/DocumentTypeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.document;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkNumber;
import software.amazon.awssdk.core.document.internal.ListDocument;
public class DocumentTypeTest {
final static String TEST_STRING_VALUE = "testString";
final static Long TEST_LONG_VALUE = 99L;
@Test
public void nullDocument() {
Document nullDocument = Document.fromNull();
assertThat(nullDocument.isNull()).isTrue();
assertThat(nullDocument.isString()).isFalse();
assertThat(nullDocument.isBoolean()).isFalse();
assertThat(nullDocument.isNumber()).isFalse();
assertThat(nullDocument.isMap()).isFalse();
assertThat(nullDocument.isList()).isFalse();
assertThat(nullDocument.toString()).hasToString("null");
assertThat(nullDocument).isEqualTo(Document.fromNull());
assertThat(nullDocument.equals(nullDocument)).isTrue();
assertThat(nullDocument.hashCode()).isEqualTo(Document.fromNull().hashCode());
assertThat(nullDocument).isNotEqualTo(Document.fromString("null"));
assertThatThrownBy(() -> nullDocument.asBoolean()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> nullDocument.asList()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> nullDocument.asMap()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> nullDocument.asNumber()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> nullDocument.asMap()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> nullDocument.asString()).isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void stringDocumentTest() {
final Document testDocumentString = Document.fromString(TEST_STRING_VALUE);
assertThat(testDocumentString.asString()).isEqualTo(TEST_STRING_VALUE);
assertThat(testDocumentString.isString()).isTrue();
assertThat(testDocumentString.isBoolean()).isFalse();
assertThat(testDocumentString.isNumber()).isFalse();
assertThat(testDocumentString.isMap()).isFalse();
assertThat(testDocumentString.isNull()).isFalse();
assertThat(testDocumentString.isList()).isFalse();
assertThat(Document.fromString(TEST_STRING_VALUE).hashCode()).isEqualTo(testDocumentString.hashCode());
assertThat(testDocumentString.equals(testDocumentString)).isTrue();
assertThat(Document.fromString("2").equals(SdkNumber.fromInteger(2))).isFalse();
assertThatThrownBy(() -> testDocumentString.asBoolean()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> testDocumentString.asList()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> testDocumentString.asMap()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> testDocumentString.asNumber()).isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void booleanDocumentTest() {
final Document testDocumentBoolean = Document.fromBoolean(true);
assertThat(testDocumentBoolean.asBoolean()).isTrue();
assertThat(testDocumentBoolean.hashCode()).isEqualTo(Document.fromBoolean(true).hashCode());
assertThat(testDocumentBoolean).isNotEqualTo(Document.fromString("true"));
assertThat(testDocumentBoolean).hasToString(Document.fromString("true").unwrap().toString());
assertThat(testDocumentBoolean.isString()).isFalse();
assertThat(testDocumentBoolean.isBoolean()).isTrue();
assertThat(testDocumentBoolean.isNumber()).isFalse();
assertThat(testDocumentBoolean.isMap()).isFalse();
assertThat(testDocumentBoolean.isNull()).isFalse();
assertThat(testDocumentBoolean.isList()).isFalse();
assertThatThrownBy(() -> testDocumentBoolean.asString()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> testDocumentBoolean.asList()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> testDocumentBoolean.asMap()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> testDocumentBoolean.asNumber()).isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void numberDocumentTest() {
final Document documentNumber = Document.fromNumber(SdkNumber.fromLong(TEST_LONG_VALUE));
assertThat(documentNumber.asNumber().longValue()).isEqualTo(TEST_LONG_VALUE);
assertThat(documentNumber.asNumber()).isEqualTo(SdkNumber.fromLong(TEST_LONG_VALUE));
assertThat(documentNumber.isString()).isFalse();
assertThat(documentNumber.isBoolean()).isFalse();
assertThat(documentNumber.isNumber()).isTrue();
assertThat(documentNumber.isMap()).isFalse();
assertThat(documentNumber.isNull()).isFalse();
assertThat(documentNumber.isList()).isFalse();
assertThat(documentNumber.hashCode()).isEqualTo(Objects.hashCode(SdkNumber.fromLong(TEST_LONG_VALUE)));
assertThat(documentNumber).isNotEqualTo(Document.fromString("99"));
assertThat(documentNumber.equals(documentNumber)).isTrue();
assertThatThrownBy(() -> documentNumber.asString()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> documentNumber.asList()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> documentNumber.asMap()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> documentNumber.asBoolean()).isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void numberDocumentFromPrimitive() throws ParseException {
assertThat(Document.fromNumber("2").asNumber()).isEqualTo(SdkNumber.fromString("2"));
assertThat(Document.fromNumber(2).asNumber()).isEqualTo(SdkNumber.fromInteger(2));
assertThat(Document.fromNumber(2L).asNumber()).isEqualTo(SdkNumber.fromLong(2));
assertThat(Document.fromNumber(2.0).asNumber()).isEqualTo(SdkNumber.fromDouble(2.0));
assertThat(Document.fromNumber(2.0f).asNumber()).isEqualTo(SdkNumber.fromFloat(2));
assertThat(Document.fromNumber(2.0f).asNumber()).isEqualTo(SdkNumber.fromFloat(2));
assertThat(Document.fromNumber(BigDecimal.ONE).asNumber()).isEqualTo(SdkNumber.fromBigDecimal(new BigDecimal(1)));
assertThat(Document.fromNumber(BigInteger.TEN).asNumber()).isEqualTo(SdkNumber.fromBigInteger(new BigInteger("10")));
assertThatThrownBy(() -> Document.fromNumber("foo").asNumber().longValue()).isInstanceOf(NumberFormatException.class);
}
@Test
public void mapDocumentFromPrimitiveNumberBuilders() {
final Document actualDocumentMap = Document.mapBuilder().putNumber("int", 1)
.putNumber("long", 2L)
.putNumber("float", 3.0f)
.putNumber("double", 4.00)
.putNumber("string", "5")
.putNumber("bigDecimal", BigDecimal.TEN)
.putNumber("bigInteger", BigInteger.TEN).build();
Map<String, Document> numberMap = new LinkedHashMap<>();
numberMap.put("int", Document.fromNumber(1));
numberMap.put("long", Document.fromNumber(2L));
numberMap.put("float", Document.fromNumber(3.0f));
numberMap.put("double", Document.fromNumber(4.00));
numberMap.put("string", Document.fromNumber("5"));
numberMap.put("bigDecimal",Document.fromNumber(BigDecimal.TEN));
numberMap.put("bigInteger", Document.fromNumber(BigInteger.TEN));
final Document expectedMap = Document.fromMap(numberMap);
assertThat(actualDocumentMap).isEqualTo(expectedMap);
final Document innerMapDoc = Document.mapBuilder().putMap("innerMapKey",
mapBuilder -> mapBuilder.putNumber("key", 1)).build();
Map<String, Document> innerMap = new HashMap<>();
innerMap.put("innerMap", innerMapDoc);
Document documentMap = Document.mapBuilder().putMap("mapKey", innerMap).build();
assertThat(documentMap).hasToString("{\"mapKey\": {\"innerMap\": {\"innerMapKey\": {\"key\": 1}}}}");
assertThat(Document.fromMap(new HashMap<>())).hasToString("{}");
assertThat(Document.fromMap(new HashMap<>()).toString().equals(Document.fromString("{}"))).isFalse();
assertThat(Document.fromMap(new HashMap<>()).hashCode()).isEqualTo(new HashMap<>().hashCode());
final Document listDoc = Document.mapBuilder().putList("listDoc", new ArrayList<>()).build();
assertThat(listDoc).hasToString("{\"listDoc\": []}");
}
@Test
public void listDocumentFromPrimitiveNumberBuilders() {
final Document actualDocList = ListDocument.listBuilder()
.addNumber(1)
.addNumber(2L)
.addNumber(3.0f)
.addNumber(4.0)
.addNumber(BigDecimal.TEN)
.addNumber(BigInteger.TEN)
.addNumber("1000")
.build();
List<Document> numberList = new ArrayList<>();
numberList.add(Document.fromNumber(1));
numberList.add(Document.fromNumber(2l));
numberList.add(Document.fromNumber(3.0f));
numberList.add(Document.fromNumber(4.0));
numberList.add(Document.fromNumber(BigDecimal.TEN));
numberList.add(Document.fromNumber(BigInteger.TEN));
numberList.add(Document.fromNumber("1000"));
assertThat(actualDocList.asList()).isEqualTo(numberList);
assertThat(Document.listBuilder().addString("string").build())
.isNotEqualTo(Document.fromString("string"));
assertThat(Document.listBuilder().addString("string").build())
.isEqualTo(Document.listBuilder().addString("string").build());
assertThat(Document.listBuilder().addString("string").build().hashCode())
.isEqualTo(Document.listBuilder().addString("string").build().hashCode());
assertThat(actualDocList.equals(actualDocList)).isTrue();
}
@Test
public void mapDocumentTestWithMapBuilders() {
final Document actualDocumentMap = Document.mapBuilder()
.putString("key", "value")
.putNull("nullKey")
.putNumber("numberKey", SdkNumber.fromBigDecimal(new BigDecimal(100.1234567)))
.putList("listKey", listBuilder -> listBuilder.addNumber(SdkNumber.fromLong(9)))
.build();
final LinkedHashMap<String, Object> expectedMapObject = new LinkedHashMap<>();
expectedMapObject.put("key", "value");
expectedMapObject.put("nullKey", null);
expectedMapObject.put("numberKey", new BigDecimal(100.1234567).toString());
expectedMapObject.put("listKey", Arrays.asList("9"));
assertThat(actualDocumentMap.isString()).isFalse();
assertThat(actualDocumentMap.isBoolean()).isFalse();
assertThat(actualDocumentMap.isNumber()).isFalse();
assertThat(actualDocumentMap.isMap()).isTrue();
assertThat(actualDocumentMap.isNull()).isFalse();
assertThat(actualDocumentMap.isList()).isFalse();
assertThat(actualDocumentMap.unwrap()).isEqualTo(expectedMapObject);
assertThatThrownBy(() -> actualDocumentMap.asString()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> actualDocumentMap.asList()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> actualDocumentMap.asNumber()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> actualDocumentMap.asBoolean()).isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void mapDocumentTestFromMapConstructors() {
final LinkedHashMap<String, Object> expectedMapObject = new LinkedHashMap<>();
expectedMapObject.put("key", "value");
expectedMapObject.put("nullKey", null);
expectedMapObject.put("numberKey", new BigDecimal(100.1234567).toString());
expectedMapObject.put("listKey", Arrays.asList("9"));
final LinkedHashMap<String, Document> map = new LinkedHashMap<>();
map.put("key", Document.fromString("value"));
map.put("nullKey", Document.fromNull());
map.put("numberKey", Document.fromNumber(SdkNumber.fromBigDecimal(new BigDecimal(100.1234567))));
map.put("listKey", Document.fromList(Arrays.asList(Document.fromNumber(SdkNumber.fromLong(9)))));
Document actualDocumentMap = Document.fromMap(map);
assertThat(actualDocumentMap.isString()).isFalse();
assertThat(actualDocumentMap.isBoolean()).isFalse();
assertThat(actualDocumentMap.isNumber()).isFalse();
assertThat(actualDocumentMap.isMap()).isTrue();
assertThat(actualDocumentMap.isNull()).isFalse();
assertThat(actualDocumentMap.isList()).isFalse();
assertThat(actualDocumentMap.unwrap()).isEqualTo(expectedMapObject);
assertThatThrownBy(() -> actualDocumentMap.asString()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> actualDocumentMap.asList()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> actualDocumentMap.asNumber()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> actualDocumentMap.asBoolean()).isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void listDocumentTest() {
final Document listBuilder = Document.listBuilder()
.addDocument(Document.fromString("one")).addNumber(SdkNumber.fromLong(2)).addBoolean(true)
.addMap(mapBuilder -> mapBuilder.putString("consumerKey", "consumerKeyMap"))
.addString("string")
.addNull()
.build();
assertThat(listBuilder.isString()).isFalse();
assertThat(listBuilder.isBoolean()).isFalse();
assertThat(listBuilder.isNumber()).isFalse();
assertThat(listBuilder.isMap()).isFalse();
assertThat(listBuilder.isNull()).isFalse();
assertThat(listBuilder.isList()).isTrue();
assertThatThrownBy(() -> listBuilder.asString()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> listBuilder.asMap()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> listBuilder.asNumber()).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> listBuilder.asBoolean()).isInstanceOf(UnsupportedOperationException.class);
assertThat(listBuilder.asList().get(0).asString()).isEqualTo("one");
assertThat(listBuilder.asList().get(1).asNumber()).isEqualTo(SdkNumber.fromLong(2));
assertThat(listBuilder.asList().get(2).asBoolean()).isTrue();
assertThat(listBuilder.asList().get(3).isMap()).isTrue();
assertThat(listBuilder.asList().get(3)).isEqualTo(Document.mapBuilder().putString("consumerKey", "consumerKeyMap")
.build());
assertThat(listBuilder.asList().get(4).isString()).isTrue();
assertThat(listBuilder.asList().get(4)).isEqualTo(Document.fromString("string"));
assertThat(listBuilder.asList().get(5).isNull()).isTrue();
assertThat(listBuilder.asList().get(5)).isEqualTo(Document.fromNull());
assertThat(Document.listBuilder().addNumber(SdkNumber.fromLong(1)).addNumber(SdkNumber.fromLong(2)).addNumber(SdkNumber.fromLong(3))
.addNumber(SdkNumber.fromLong(4)).addNumber(SdkNumber.fromLong(5)).build().asList())
.isEqualTo(Arrays.asList(Document.fromNumber(SdkNumber.fromLong(1)), Document.fromNumber(SdkNumber.fromLong(2)),
Document.fromNumber(SdkNumber.fromLong(3)), Document.fromNumber(SdkNumber.fromLong(4)), Document.fromNumber(SdkNumber.fromLong(5))));
}
@Test
public void testStringDocumentEscapeQuotes() {
// Actual String is <start>"mid"<end>
Document docWithQuotes = Document.fromString("<start>" + '\u0022' + "mid" + '\u0022' + "<end>");
//We expect the quotes <start>\"mid\"<end>
assertThat(docWithQuotes).hasToString("\"<start>\\\"mid\\\"<end>\"");
Document docWithNoQuotes = Document.fromString("testString");
assertThat(docWithNoQuotes).hasToString("\"testString\"");
assertThat("\"" + docWithNoQuotes.asString() + "\"").isEqualTo(docWithNoQuotes.toString());
}
@Test
public void testStringDocumentEscapeBackSlash() {
String testString = "test\\String";
Document document = Document.fromString(testString);
assertThat(document).hasToString("\"test\\\\String\"");
assertThat("\"" + document.asString() + "\"").isNotEqualTo(document.toString());
}
}
| 2,003 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/NoopTestRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkRequestOverrideConfiguration;
public class NoopTestRequest extends SdkRequest {
private final SdkRequestOverrideConfiguration requestOverrideConfig;
private NoopTestRequest(Builder builder) {
this.requestOverrideConfig = builder.overrideConfiguration();
}
@Override
public Optional<SdkRequestOverrideConfiguration> overrideConfiguration() {
return Optional.ofNullable(requestOverrideConfig);
}
@Override
public Builder toBuilder() {
return new BuilderImpl();
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public List<SdkField<?>> sdkFields() {
return Collections.emptyList();
}
public interface Builder extends SdkRequest.Builder {
@Override
NoopTestRequest build();
@Override
SdkRequestOverrideConfiguration overrideConfiguration();
Builder overrideConfiguration(SdkRequestOverrideConfiguration requestOverrideConfig);
}
private static class BuilderImpl implements Builder {
private SdkRequestOverrideConfiguration requestOverrideConfig;
@Override
public SdkRequestOverrideConfiguration overrideConfiguration() {
return requestOverrideConfig;
}
public Builder overrideConfiguration(SdkRequestOverrideConfiguration requestOverrideConfig) {
this.requestOverrideConfig = requestOverrideConfig;
return this;
}
@Override
public NoopTestRequest build() {
return new NoopTestRequest(this);
}
}
}
| 2,004 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/InterruptFlagAlwaysClearsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.time.Duration;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.client.handler.SdkSyncClientHandler;
import software.amazon.awssdk.core.exception.AbortedException;
import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.runtime.transform.Marshaller;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import utils.HttpTestUtils;
@RunWith(MockitoJUnitRunner.class)
public class InterruptFlagAlwaysClearsTest {
private static final Duration SERVICE_LATENCY = Duration.ofMillis(10);
private static SdkSyncClientHandler syncHttpClient;
@Mock
private Marshaller<SdkRequest> marshaller;
@Mock
private HttpResponseHandler<SdkResponse> responseHandler;
@Mock(lenient = true)
private HttpResponseHandler<SdkServiceException> errorResponseHandler;
@BeforeClass
public static void setup() {
SdkClientConfiguration clientConfiguration = HttpTestUtils.testClientConfiguration()
.toBuilder()
.option(SdkClientOption.SYNC_HTTP_CLIENT, new SleepyHttpClient())
.option(SdkClientOption.API_CALL_ATTEMPT_TIMEOUT, SERVICE_LATENCY)
.build();
syncHttpClient = new TestClientHandler(clientConfiguration);
}
@Before
public void methodSetup() throws Exception {
when(marshaller.marshall(any(NoopTestRequest.class)))
.thenReturn(SdkHttpFullRequest.builder()
.protocol("http")
.host("some-host.aws")
.method(SdkHttpMethod.GET)
.build());
when(errorResponseHandler.handle(any(SdkHttpFullResponse.class), any(ExecutionAttributes.class)))
.thenReturn(SdkServiceException.builder().message("BOOM").statusCode(400).build());
}
@AfterClass
public static void cleanup() {
syncHttpClient.close();
}
@Test
public void interruptFlagClearsWithTimeoutCloseToLatency() {
int numRuns = 100;
int interruptCount = 0;
for (int i = 0; i < numRuns; ++i) {
// This request is expected to time out for some number of iterations
executeRequestIgnoreErrors(syncHttpClient);
// Check and clear interrupt flag
if (Thread.interrupted()) {
++interruptCount;
}
}
assertThat(interruptCount)
.withFailMessage("Interrupt flags are leaking: %d of %d runs leaked interrupt flags.",
interruptCount, numRuns)
.isEqualTo(0);
}
private void executeRequestIgnoreErrors(SdkSyncClientHandler syncHttpClient) {
try {
syncHttpClient.execute(new ClientExecutionParams<SdkRequest, SdkResponse>()
.withOperationName("SomeOperation")
.withResponseHandler(responseHandler)
.withErrorResponseHandler(errorResponseHandler)
.withInput(NoopTestRequest.builder().build())
.withMarshaller(marshaller));
Assert.fail();
} catch (AbortedException | ApiCallAttemptTimeoutException | SdkServiceException e) {
// Ignored
}
}
private static class SleepyHttpClient implements SdkHttpClient {
private static final HttpExecuteResponse RESPONSE = HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(400)
.build())
.build();
@Override
public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) {
return new ExecutableHttpRequest() {
@Override
public HttpExecuteResponse call() throws IOException {
try {
Thread.sleep(SERVICE_LATENCY.toMillis());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted!", e);
}
return RESPONSE;
}
@Override
public void abort() {
}
};
}
@Override
public void close() {
}
}
private static class TestClientHandler extends SdkSyncClientHandler {
protected TestClientHandler(SdkClientConfiguration clientConfiguration) {
super(clientConfiguration);
}
}
} | 2,005 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/AmazonHttpClientTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.ExecutorService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.ClientType;
import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient;
import software.amazon.awssdk.core.internal.http.pipeline.stages.ApplyUserAgentStage;
import software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpResponse;
import utils.HttpTestUtils;
import utils.ValidSdkObjects;
@RunWith(MockitoJUnitRunner.class)
public class AmazonHttpClientTest {
@Mock
private SdkHttpClient sdkHttpClient;
@Mock
private ExecutableHttpRequest abortableCallable;
@Mock
private ExecutorService executor;
private AmazonSyncHttpClient client;
@Before
public void setUp() throws Exception {
client = HttpTestUtils.testClientBuilder().httpClient(sdkHttpClient).build();
when(sdkHttpClient.prepareRequest(any())).thenReturn(abortableCallable);
when(sdkHttpClient.clientName()).thenReturn("UNKNOWN");
stubSuccessfulResponse();
}
@Test
public void testRetryIoExceptionFromExecute() throws Exception {
IOException ioException = new IOException("BOOM");
when(abortableCallable.call()).thenThrow(ioException);
ExecutionContext context = ClientExecutionAndRequestTimerTestUtils.executionContext(null);
try {
client.requestExecutionBuilder()
.request(ValidSdkObjects.sdkHttpFullRequest().build())
.originalRequest(NoopTestRequest.builder().build())
.executionContext(context)
.execute(combinedSyncResponseHandler(null, null));
Assert.fail("No exception when request repeatedly fails!");
} catch (SdkClientException e) {
Assert.assertSame(ioException, e.getCause());
}
// Verify that we called execute 4 times.
verify(sdkHttpClient, times(4)).prepareRequest(any());
}
@Test
public void testRetryIoExceptionFromHandler() throws Exception {
final IOException exception = new IOException("BOOM");
HttpResponseHandler<?> mockHandler = mock(HttpResponseHandler.class);
when(mockHandler.handle(any(), any())).thenThrow(exception);
ExecutionContext context = ClientExecutionAndRequestTimerTestUtils.executionContext(null);
try {
client.requestExecutionBuilder()
.request(ValidSdkObjects.sdkHttpFullRequest().build())
.originalRequest(NoopTestRequest.builder().build())
.executionContext(context)
.execute(combinedSyncResponseHandler(mockHandler, null));
Assert.fail("No exception when request repeatedly fails!");
} catch (SdkClientException e) {
Assert.assertSame(exception, e.getCause());
}
// Verify that we called execute 4 times.
verify(mockHandler, times(4)).handle(any(), any());
}
@Test
public void testUserAgentPrefixAndSuffixAreAdded() {
String prefix = "somePrefix";
String suffix = "someSuffix-blah-blah";
HttpResponseHandler<?> handler = mock(HttpResponseHandler.class);
String clientUserAgent =
ApplyUserAgentStage.resolveClientUserAgent(prefix, "", ClientType.SYNC, sdkHttpClient, null,
RetryPolicy.forRetryMode(RetryMode.STANDARD));
SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder()
.option(SdkAdvancedClientOption.USER_AGENT_SUFFIX, suffix)
.option(SdkClientOption.CLIENT_USER_AGENT, clientUserAgent)
.option(SdkClientOption.SYNC_HTTP_CLIENT, sdkHttpClient)
.build();
AmazonSyncHttpClient client = new AmazonSyncHttpClient(config);
client.requestExecutionBuilder()
.request(ValidSdkObjects.sdkHttpFullRequest().build())
.originalRequest(NoopTestRequest.builder().build())
.executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null))
.execute(combinedSyncResponseHandler(handler, null));
ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
verify(sdkHttpClient).prepareRequest(httpRequestCaptor.capture());
final String userAgent = httpRequestCaptor.getValue().httpRequest().firstMatchingHeader("User-Agent")
.orElseThrow(() -> new AssertionError("User-Agent header was not found"));
Assert.assertTrue(userAgent.startsWith(prefix));
Assert.assertTrue(userAgent.endsWith(suffix));
}
@Test
public void testUserAgentContainsHttpClientInfo() {
HttpResponseHandler<?> handler = mock(HttpResponseHandler.class);
String clientUserAgent =
ApplyUserAgentStage.resolveClientUserAgent(null, null, ClientType.SYNC, sdkHttpClient, null,
RetryPolicy.forRetryMode(RetryMode.STANDARD));
SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder()
.option(SdkClientOption.SYNC_HTTP_CLIENT, sdkHttpClient)
.option(SdkClientOption.CLIENT_TYPE, ClientType.SYNC)
.option(SdkClientOption.CLIENT_USER_AGENT, clientUserAgent)
.build();
AmazonSyncHttpClient client = new AmazonSyncHttpClient(config);
client.requestExecutionBuilder()
.request(ValidSdkObjects.sdkHttpFullRequest().build())
.originalRequest(NoopTestRequest.builder().build())
.executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null))
.execute(combinedSyncResponseHandler(handler, null));
ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
verify(sdkHttpClient).prepareRequest(httpRequestCaptor.capture());
final String userAgent = httpRequestCaptor.getValue().httpRequest().firstMatchingHeader("User-Agent")
.orElseThrow(() -> new AssertionError("User-Agent header was not found"));
Assert.assertTrue(userAgent.contains("io/sync"));
Assert.assertTrue(userAgent.contains("http/UNKNOWN"));
}
@Test
public void testUserAgentContainsRetryModeInfo() {
HttpResponseHandler<?> handler = mock(HttpResponseHandler.class);
String clientUserAgent =
ApplyUserAgentStage.resolveClientUserAgent(null, null, ClientType.SYNC, sdkHttpClient, null,
RetryPolicy.forRetryMode(RetryMode.STANDARD));
SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder()
.option(SdkClientOption.CLIENT_USER_AGENT, clientUserAgent)
.option(SdkClientOption.SYNC_HTTP_CLIENT, sdkHttpClient)
.build();
AmazonSyncHttpClient client = new AmazonSyncHttpClient(config);
client.requestExecutionBuilder()
.request(ValidSdkObjects.sdkHttpFullRequest().build())
.originalRequest(NoopTestRequest.builder().build())
.executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null))
.execute(combinedSyncResponseHandler(handler, null));
ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
verify(sdkHttpClient).prepareRequest(httpRequestCaptor.capture());
final String userAgent = httpRequestCaptor.getValue().httpRequest().firstMatchingHeader("User-Agent")
.orElseThrow(() -> new AssertionError("User-Agent header was not found"));
Assert.assertTrue(userAgent.contains("cfg/retry-mode/standard"));
}
@Test
public void closeClient_shouldCloseDependencies() {
SdkClientConfiguration config = HttpTestUtils.testClientConfiguration()
.toBuilder()
.option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, executor)
.option(SdkClientOption.SYNC_HTTP_CLIENT, sdkHttpClient)
.build();
AmazonSyncHttpClient client = new AmazonSyncHttpClient(config);
client.close();
verify(sdkHttpClient).close();
verify(executor).shutdown();
}
private void stubSuccessfulResponse() throws Exception {
when(abortableCallable.call()).thenReturn(HttpExecuteResponse.builder().response(SdkHttpResponse.builder()
.statusCode(200)
.build())
.build());
}
}
| 2,006 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/ContentStreamProviderWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.executionContext;
import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient;
import software.amazon.awssdk.core.internal.http.response.NullErrorResponseHandler;
import software.amazon.awssdk.core.io.SdkFilterInputStream;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import utils.HttpTestUtils;
import utils.http.WireMockTestBase;
/**
* WireMock tests related to {@link ContentStreamProvider} usage.
*/
public class ContentStreamProviderWireMockTest extends WireMockTestBase {
private static final String OPERATION = "/some-operation";
@Test
public void closesAllCreatedInputStreamsFromProvider() {
stubFor(any(urlPathEqualTo(OPERATION)).willReturn(aResponse().withStatus(500)));
TestContentStreamProvider provider = new TestContentStreamProvider();
SdkHttpFullRequest request = newRequest(OPERATION)
.contentStreamProvider(provider)
.method(SdkHttpMethod.PUT)
.build();
AmazonSyncHttpClient testClient = HttpTestUtils.testAmazonHttpClient();
try {
sendRequest(request, testClient);
fail("Should have thrown SdkServiceException");
} catch (SdkServiceException ignored) {
}
// The test client uses the default retry policy so there should be 4
// total attempts and an equal number created streams
assertThat(provider.getCreatedStreams().size()).isEqualTo(4);
for (CloseTrackingInputStream is : provider.getCreatedStreams()) {
assertThat(is.isClosed()).isTrue();
}
}
private void sendRequest(SdkHttpFullRequest request, AmazonSyncHttpClient sut) {
sut.requestExecutionBuilder()
.request(request)
.originalRequest(NoopTestRequest.builder().build())
.executionContext(executionContext(request))
.execute(combinedSyncResponseHandler(null, new NullErrorResponseHandler()));
}
private static class TestContentStreamProvider implements ContentStreamProvider {
private static final byte[] CONTENT_BYTES = "Hello".getBytes(StandardCharsets.UTF_8);
private List<CloseTrackingInputStream> createdStreams = new ArrayList<>();
@Override
public InputStream newStream() {
closeCurrentStream();
CloseTrackingInputStream s = newContentStream();
createdStreams.add(s);
return s;
}
List<CloseTrackingInputStream> getCreatedStreams() {
return createdStreams;
}
private CloseTrackingInputStream newContentStream() {
return new CloseTrackingInputStream(new ByteArrayInputStream(CONTENT_BYTES));
}
private void closeCurrentStream() {
if (createdStreams.isEmpty()) {
return;
}
invokeSafely(() -> createdStreams.get(createdStreams.size() - 1).close());
}
}
private static class CloseTrackingInputStream extends SdkFilterInputStream {
private boolean isClosed = false;
CloseTrackingInputStream(InputStream in) {
super(in);
}
@Override
public void close() throws IOException {
super.close();
isClosed = true;
}
boolean isClosed() {
return isClosed;
}
}
}
| 2,007 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/SdkTransactionIdInHeaderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.findAll;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import org.junit.Test;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient;
import software.amazon.awssdk.core.internal.http.pipeline.stages.ApplyTransactionIdStage;
import software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import utils.HttpTestUtils;
import utils.http.WireMockTestBase;
public class SdkTransactionIdInHeaderTest extends WireMockTestBase {
private static final String RESOURCE_PATH = "/transaction-id/";
@Test
public void retriedRequest_HasSameTransactionIdForAllRetries() throws Exception {
stubFor(get(urlEqualTo(RESOURCE_PATH)).willReturn(aResponse().withStatus(500)));
executeRequest();
assertTransactionIdIsUnchangedAcrossRetries();
}
private void assertTransactionIdIsUnchangedAcrossRetries() {
String previousTransactionId = null;
for (LoggedRequest request : findAll(getRequestedFor(urlEqualTo(RESOURCE_PATH)))) {
final String currentTransactionId = request.getHeader(ApplyTransactionIdStage.HEADER_SDK_TRANSACTION_ID);
// Transaction ID should always be set
assertNotNull(currentTransactionId);
// Transaction ID should be the same across retries
if (previousTransactionId != null) {
assertEquals(previousTransactionId, currentTransactionId);
}
previousTransactionId = currentTransactionId;
}
}
private void executeRequest() throws Exception {
AmazonSyncHttpClient httpClient = HttpTestUtils.testAmazonHttpClient();
try {
SdkHttpFullRequest request = newGetRequest(RESOURCE_PATH).build();
httpClient.requestExecutionBuilder()
.request(request)
.originalRequest(NoopTestRequest.builder().build())
.executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(request))
.execute(combinedSyncResponseHandler(null, stubErrorHandler()));
fail("Expected exception");
} catch (SdkServiceException expected) {
// Ignored or expected.
}
}
}
| 2,008 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/UnresponsiveMockServerTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http;
import software.amazon.awssdk.core.http.server.MockServer;
public abstract class UnresponsiveMockServerTestBase extends MockServerTestBase {
@Override
protected MockServer buildMockServer() {
return MockServer.createMockServer(MockServer.ServerBehavior.UNRESPONSIVE);
}
}
| 2,009 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/Crc32ValidationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.zip.GZIPInputStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.unitils.util.ReflectionUtils;
import software.amazon.awssdk.core.internal.util.Crc32ChecksumValidatingInputStream;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.utils.StringInputStream;
@RunWith(MockitoJUnitRunner.class)
public class Crc32ValidationTest {
@Test
public void adapt_InputStreamWithNoGzipOrCrc32_NotWrappedWhenAdapted() {
InputStream content = new StringInputStream("content");
SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder()
.statusCode(200)
.content(AbortableInputStream.create(content))
.build();
SdkHttpFullResponse adapted = adapt(httpResponse);
InputStream in = adapted.content().get().delegate();
assertThat(in).isEqualTo(content);
}
@Test
public void adapt_InputStreamWithCrc32Header_WrappedWithValidatingStream() throws UnsupportedEncodingException {
InputStream content = new StringInputStream("content");
SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder()
.statusCode(200)
.putHeader("x-amz-crc32", "1234")
.content(AbortableInputStream.create(content))
.build();
SdkHttpFullResponse adapted = adapt(httpResponse);
InputStream in = adapted.content().get().delegate();
assertThat(in).isInstanceOf((Crc32ChecksumValidatingInputStream.class));
}
@Test
public void adapt_InputStreamWithGzipEncoding_WrappedWithDecompressingStream() throws IOException {
try (InputStream content = getClass().getResourceAsStream("/resources/compressed_json_body.gz")) {
SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder()
.statusCode(200)
.putHeader("Content-Encoding", "gzip")
.content(AbortableInputStream.create(content))
.build();
SdkHttpFullResponse adapted = adapt(httpResponse);
InputStream in = adapted.content().get().delegate();
assertThat(in).isInstanceOf((GZIPInputStream.class));
}
}
@Test
public void adapt_CalculateCrcFromCompressed_WrapsWithCrc32ThenGzip() throws IOException {
try (InputStream content = getClass().getResourceAsStream("/resources/compressed_json_body.gz")) {
SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder()
.statusCode(200)
.putHeader("Content-Encoding", "gzip")
.putHeader("x-amz-crc32", "1234")
.content(AbortableInputStream.create(content))
.build();
SdkHttpFullResponse adapted = Crc32Validation.validate(true, httpResponse);
InputStream in = adapted.content().get().delegate();
assertThat(in).isInstanceOf((GZIPInputStream.class));
}
}
@Test(expected = UncheckedIOException.class)
public void adapt_InvalidGzipContent_ThrowsException() throws UnsupportedEncodingException {
InputStream content = new StringInputStream("this isn't GZIP");
SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder()
.statusCode(200)
.putHeader("Content-Encoding", "gzip")
.content(AbortableInputStream.create(content))
.build();
SdkHttpFullResponse adapted = adapt(httpResponse);
InputStream in = adapted.content().get().delegate();
assertThat(in).isInstanceOf((GZIPInputStream.class));
}
@Test
public void adapt_ResponseWithCrc32Header_And_NoContent_DoesNotThrowNPE() throws UnsupportedEncodingException {
SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder()
.statusCode(200)
.putHeader("x-amz-crc32", "1234")
.build();
SdkHttpFullResponse adapted = adapt(httpResponse);
assertThat(adapted.content().isPresent()).isFalse();
}
@Test
public void adapt_ResponseGzipEncoding_And_NoContent_DoesNotThrowNPE() throws IOException {
SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder()
.statusCode(200)
.putHeader("Content-Encoding", "gzip")
.build();
SdkHttpFullResponse adapted = adapt(httpResponse);
assertThat(adapted.content().isPresent()).isFalse();
}
private SdkHttpFullResponse adapt(SdkHttpFullResponse httpResponse) {
return Crc32Validation.validate(false, httpResponse);
}
@SuppressWarnings("unchecked")
private static <T> T getField(Object obj, String fieldName) {
try {
Field field = ReflectionUtils.getFieldWithName(obj.getClass(), fieldName, false);
field.setAccessible(true);
return (T) field.get(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 2,010 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/AmazonHttpClientWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.matching;
import static com.github.tomakehurst.wiremock.client.WireMock.optionsRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.executionContext;
import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient;
import software.amazon.awssdk.core.internal.http.response.NullErrorResponseHandler;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import utils.HttpTestUtils;
import utils.http.WireMockTestBase;
public class AmazonHttpClientWireMockTest extends WireMockTestBase {
private static final String OPERATION = "/some-operation";
private static final String HEADER = "Some-Header";
private static final String CONFIG_HEADER_VALUE = "client config header value";
private static final String REQUEST_HEADER_VALUE = "request header value";
@Before
public void setUp() {
stubFor(any(urlPathEqualTo(OPERATION)).willReturn(aResponse()));
}
@Test
public void headersSpecifiedInClientConfigurationArePutOnRequest() {
SdkHttpFullRequest request = newGetRequest(OPERATION).build();
AmazonSyncHttpClient sut = createClient(HEADER, CONFIG_HEADER_VALUE);
sendRequest(request, sut);
verify(getRequestedFor(urlPathEqualTo(OPERATION)).withHeader(HEADER, matching(CONFIG_HEADER_VALUE)));
}
@Test
public void headersOnRequestsWinOverClientConfigurationHeaders() {
SdkHttpFullRequest request = newGetRequest(OPERATION)
.putHeader(HEADER, REQUEST_HEADER_VALUE)
.build();
AmazonSyncHttpClient sut = createClient(HEADER, CONFIG_HEADER_VALUE);
sendRequest(request, sut);
verify(getRequestedFor(urlPathEqualTo(OPERATION)).withHeader(HEADER, matching(REQUEST_HEADER_VALUE)));
}
@Test
public void canHandleOptionsRequest() {
SdkHttpFullRequest request = newRequest(OPERATION)
.method(SdkHttpMethod.OPTIONS)
.build();
AmazonSyncHttpClient sut = HttpTestUtils.testAmazonHttpClient();
sendRequest(request, sut);
verify(optionsRequestedFor(urlPathEqualTo(OPERATION)));
}
private void sendRequest(SdkHttpFullRequest request, AmazonSyncHttpClient sut) {
sut.requestExecutionBuilder()
.request(request)
.originalRequest(NoopTestRequest.builder().build())
.executionContext(executionContext(request))
.execute(combinedSyncResponseHandler(null, new NullErrorResponseHandler()));
}
private AmazonSyncHttpClient createClient(String headerName, String headerValue) {
return HttpTestUtils.testClientBuilder().additionalHeader(headerName, headerValue).build();
}
}
| 2,011 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/MockServerTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http;
import org.junit.After;
import org.junit.Before;
import software.amazon.awssdk.core.http.server.MockServer;
public abstract class MockServerTestBase {
protected MockServer server;
@Before
public void setupBaseFixture() {
server = buildMockServer();
server.startServer();
}
@After
public void tearDownBaseFixture() {
server.stopServer();
}
/**
* Implemented by test subclasses to build the correct type of {@link MockServer}
*/
protected abstract MockServer buildMockServer();
}
| 2,012 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/server/MockServer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http.server;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.URI;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.StringInputStream;
/**
* MockServer implementation with several different configurable behaviors
*/
public class MockServer {
private final ServerBehaviorStrategy serverBehaviorStrategy;
/**
* The server socket which the test service will listen to.
*/
private ServerSocket serverSocket;
private Thread listenerThread;
public MockServer(final ServerBehaviorStrategy serverBehaviorStrategy) {
this.serverBehaviorStrategy = serverBehaviorStrategy;
}
public static MockServer createMockServer(ServerBehavior serverBehavior) {
switch (serverBehavior) {
case UNRESPONSIVE:
return new MockServer(new UnresponsiveServerBehavior());
case OVERLOADED:
return new MockServer(new OverloadedServerBehavior());
default:
throw new IllegalArgumentException("Unsupported implementation for server issue: " + serverBehavior);
}
}
public void startServer() {
try {
serverSocket = new ServerSocket(0); // auto-assign a port at localhost
System.out.println("Listening on port " + serverSocket.getLocalPort());
} catch (IOException e) {
throw new RuntimeException("Unable to start the server socker.", e);
}
listenerThread = new MockServerListenerThread(serverSocket, serverBehaviorStrategy);
listenerThread.setDaemon(true);
listenerThread.start();
}
public void stopServer() {
listenerThread.interrupt();
try {
listenerThread.join(10 * 1000);
} catch (InterruptedException e1) {
System.err.println("The listener thread didn't terminate " + "after waiting for 10 seconds.");
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Unable to stop the server socket.", e);
}
}
}
public int getPort() {
return serverSocket.getLocalPort();
}
public SdkHttpFullRequest.Builder configureHttpsEndpoint(SdkHttpFullRequest.Builder request) {
return request.uri(URI.create("https://localhost"))
.port(getPort());
}
public SdkHttpFullRequest.Builder configureHttpEndpoint(SdkHttpFullRequest.Builder request) {
return request.uri(URI.create("http://localhost"))
.port(getPort());
}
public enum ServerBehavior {
UNRESPONSIVE,
OVERLOADED,
DUMMY_RESPONSE;
}
public interface ServerBehaviorStrategy {
void runServer(ServerSocket serverSocket);
}
private static class MockServerListenerThread extends Thread {
/** The server socket which this thread listens and responds to. */
private final ServerSocket serverSocket;
private final ServerBehaviorStrategy behaviorStrategy;
public MockServerListenerThread(ServerSocket serverSocket, ServerBehaviorStrategy behaviorStrategy) {
super(behaviorStrategy.getClass().getName());
this.serverSocket = serverSocket;
this.behaviorStrategy = behaviorStrategy;
setDaemon(true);
}
@Override
public void run() {
this.behaviorStrategy.runServer(serverSocket);
}
}
/**
* A daemon thread which runs a simple server that listens to a specific server socket. Whenever
* a connection is created, the server simply keeps holding the connection open while
* periodically writing data. The test client talking to this server is expected to timeout
* appropriately, instead of hanging and waiting for the response forever.
*/
public static class OverloadedServerBehavior implements ServerBehaviorStrategy {
@Override
public void runServer(ServerSocket serverSocket) {
try {
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept();
try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
out.writeBytes("HTTP/1.1 200 OK\r\n");
out.writeBytes("Content-Type: text/html\r\n");
out.writeBytes("Content-Length: 500\r\n\r\n");
out.writeBytes("<html><head></head><body><h1>Hello.");
while (true) {
Thread.sleep(1 * 1000);
out.writeBytes("Hi.");
}
}
} catch (SocketException se) {
// Ignored or expected.
} finally {
if (socket != null) {
socket.close();
}
}
}
} catch (IOException e) {
throw new RuntimeException("Error when waiting for new socket connection.", e);
} catch (InterruptedException e) {
System.err.println("Socket listener thread interrupted. Terminating the thread...");
return;
}
}
}
/**
* A daemon thread which runs a simple server that listens to a specific server socket. Whenever
* a connection is created, the server simply keeps holding the connection open and no byte will
* be written to the socket. The test client talking to this server is expected to timeout
* appropriately, instead of hanging and waiting for the response forever.
*/
public static class UnresponsiveServerBehavior implements ServerBehaviorStrategy {
@Override
public void runServer(ServerSocket serverSocket) {
Socket socket = null;
try {
socket = serverSocket.accept();
System.out.println("Socket created on port " + socket.getLocalPort());
while (true) {
System.out.println("I don't want to talk.");
Thread.sleep(10 * 1000);
}
} catch (IOException e) {
throw new RuntimeException("Error when waiting for new socket connection.", e);
} catch (InterruptedException e) {
System.err.println("Socket listener thread interrupted. Terminating the thread...");
return;
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
throw new RuntimeException("Fail to close the socket", e);
}
}
}
}
public static class DummyResponseServerBehavior implements ServerBehaviorStrategy {
private final HttpResponse response;
private String content;
public DummyResponseServerBehavior(HttpResponse response) {
this.response = response;
try {
this.content = IoUtils.toUtf8String(response.getEntity().getContent());
} catch (Exception e) {
// Ignored or expected.
}
}
public static DummyResponseServerBehavior build(int statusCode, String statusMessage, String content) {
HttpResponse response = new BasicHttpResponse(
new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), statusCode, statusMessage));
setEntity(response, content);
response.addHeader("Content-Length", String.valueOf(content.getBytes().length));
response.addHeader("Connection", "close");
return new DummyResponseServerBehavior(response);
}
private static void setEntity(HttpResponse response, String content) {
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new StringInputStream(content));
response.setEntity(entity);
}
@Override
public void runServer(ServerSocket serverSocket) {
try {
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept();
try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
StringBuilder builder = new StringBuilder();
builder.append(response.getStatusLine().toString() + "\r\n");
for (Header header : response.getAllHeaders()) {
builder.append(header.getName() + ":" + header.getValue() + "\r\n");
}
builder.append("\r\n");
builder.append(content);
System.out.println(builder.toString());
out.writeBytes(builder.toString());
}
} catch (SocketException se) {
// Ignored or expected.
} finally {
if (socket != null) {
socket.close();
}
}
}
} catch (IOException e) {
throw new RuntimeException("Error when waiting for new socket connection.", e);
}
}
}
}
| 2,013 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/compression/CompressorTypeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.compression;
import static org.assertj.core.api.Assertions.assertThat;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.internal.compression.CompressorType;
public class CompressorTypeTest {
@Test
public void equalsHashcode() {
EqualsVerifier.forClass(CompressorType.class)
.withNonnullFields("id")
.verify();
}
@Test
public void compressorType_gzip() {
CompressorType gzip = CompressorType.GZIP;
CompressorType gzipFromString = CompressorType.of("gzip");
assertThat(gzip).isSameAs(gzipFromString);
assertThat(gzip).isEqualTo(gzipFromString);
}
@Test
public void compressorType_usesSameInstance_when_sameCompressorTypeOfSameValue() {
CompressorType brotliFromString = CompressorType.of("brotli");
CompressorType brotliFromStringDuplicate = CompressorType.of("brotli");
assertThat(brotliFromString).isSameAs(brotliFromStringDuplicate);
assertThat(brotliFromString).isEqualTo(brotliFromStringDuplicate);
}
}
| 2,014 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/sync/RequestBodyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.sync;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import software.amazon.awssdk.core.internal.util.Mimetype;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.StringInputStream;
public class RequestBodyTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void stringConstructorUsesUTF8ByteLength() {
// U+03A9 U+03C9
final String multibyteChars = "Ωω";
RequestBody rb = RequestBody.fromString(multibyteChars);
assertThat(rb.contentLength()).isEqualTo(4L);
}
@Test
public void stringConstructorHasCorrectContentType() {
RequestBody requestBody = RequestBody.fromString("hello world");
assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_TEXT_PLAIN + "; charset=UTF-8");
}
@Test
public void stringConstructorWithCharsetHasCorrectContentType() {
RequestBody requestBody = RequestBody.fromString("hello world", StandardCharsets.US_ASCII);
assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_TEXT_PLAIN + "; charset=US-ASCII");
}
@Test
public void fileConstructorHasCorrectContentType() throws IOException {
FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
Path path = fs.getPath("./test");
Files.write(path, "hello world".getBytes());
RequestBody requestBody = RequestBody.fromFile(path);
assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM);
}
@Test
public void streamConstructorHasCorrectContentType() {
StringInputStream inputStream = new StringInputStream("hello world");
RequestBody requestBody = RequestBody.fromInputStream(inputStream, 11);
assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM);
IoUtils.closeQuietly(inputStream, null);
}
@Test
public void nonMarkSupportedInputStreamContentType() throws IOException {
File file = folder.newFile();
try (FileWriter writer = new FileWriter(file)) {
writer.write("hello world");
}
InputStream inputStream = Files.newInputStream(file.toPath());
RequestBody requestBody = RequestBody.fromInputStream(inputStream, 11);
assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM);
assertThat(requestBody.contentStreamProvider().newStream()).isNotNull();
IoUtils.closeQuietly(inputStream, null);
}
@Test
public void bytesArrayConstructorHasCorrectContentType() {
RequestBody requestBody = RequestBody.fromBytes("hello world".getBytes());
assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM);
}
@Test
public void bytesBufferConstructorHasCorrectContentType() {
ByteBuffer byteBuffer = ByteBuffer.wrap("hello world".getBytes());
RequestBody requestBody = RequestBody.fromByteBuffer(byteBuffer);
assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM);
}
@Test
public void emptyBytesConstructorHasCorrectContentType() {
RequestBody requestBody = RequestBody.empty();
assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM);
}
@Test
public void contentProviderConstuctorWithNullContentLength_NoContentLength() {
byte[] bytes = new byte[0];
RequestBody requestBody = RequestBody.fromContentProvider(() -> new ByteArrayInputStream(bytes),
Mimetype.MIMETYPE_OCTET_STREAM);
assertThat(requestBody.optionalContentLength().isPresent()).isFalse();
assertThatThrownBy(() -> requestBody.contentLength()).isInstanceOf(IllegalStateException.class);
}
@Test
public void remainingByteBufferConstructorOnlyRemainingBytesCopied() throws IOException {
ByteBuffer bb = ByteBuffer.allocate(4);
bb.put(new byte[]{1, 2, 3, 4});
bb.flip();
bb.get();
bb.get();
int originalRemaining = bb.remaining();
RequestBody requestBody = RequestBody.fromRemainingByteBuffer(bb);
assertThat(requestBody.contentLength()).isEqualTo(originalRemaining);
byte[] requestBodyBytes = IoUtils.toByteArray(requestBody.contentStreamProvider().newStream());
assertThat(ByteBuffer.wrap(requestBodyBytes)).isEqualTo(bb);
}
}
| 2,015 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/checksum/AwsChunkedEncodingInputStreamTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.checksum;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.core.internal.util.ChunkContentUtils.calculateChecksumTrailerLength;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.internal.io.AwsChunkedEncodingInputStream;
import software.amazon.awssdk.core.internal.io.AwsUnsignedChunkedEncodingInputStream;
import software.amazon.awssdk.core.internal.util.ChunkContentUtils;
public class AwsChunkedEncodingInputStreamTest {
private static final String CRLF = "\r\n";
final private static Algorithm SHA256_ALGORITHM = Algorithm.SHA256;
final private String SHA256_HEADER_NAME = "x-amz-checksum-sha-256";
@Test
public void readAwsUnsignedChunkedEncodingInputStream() throws IOException {
String initialString = "Hello world";
InputStream targetStream = new ByteArrayInputStream(initialString.getBytes());
final AwsChunkedEncodingInputStream checksumCalculatingInputStream =
AwsUnsignedChunkedEncodingInputStream.builder()
.inputStream(targetStream)
.sdkChecksum(SdkChecksum.forAlgorithm(SHA256_ALGORITHM))
.checksumHeaderForTrailer(SHA256_HEADER_NAME)
.build();
StringBuilder sb = new StringBuilder();
for (int ch; (ch = checksumCalculatingInputStream.read()) != -1; ) {
sb.append((char) ch);
}
assertThat(sb).hasToString("b" + CRLF + initialString +CRLF + "0" + CRLF
+ "x-amz-checksum-sha-256:ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=" + CRLF+CRLF);
}
@Test
public void lengthsOfCalculateByChecksumCalculatingInputStream(){
String initialString = "Hello world";
long calculateChunkLength = ChunkContentUtils.calculateStreamContentLength(initialString.length(),
AwsChunkedEncodingInputStream.DEFAULT_CHUNK_SIZE);
long checksumContentLength = calculateChecksumTrailerLength(SHA256_ALGORITHM, SHA256_HEADER_NAME);
assertThat(calculateChunkLength).isEqualTo(19);
assertThat(checksumContentLength).isEqualTo(71);
}
@Test
public void markAndResetAwsChunkedEncodingInputStream() throws IOException {
String initialString = "Hello world";
InputStream targetStream = new ByteArrayInputStream(initialString.getBytes());
final AwsChunkedEncodingInputStream checksumCalculatingInputStream =
AwsUnsignedChunkedEncodingInputStream.builder()
.inputStream(targetStream)
.sdkChecksum(SdkChecksum.forAlgorithm(SHA256_ALGORITHM))
.checksumHeaderForTrailer(SHA256_HEADER_NAME)
.build();
StringBuilder sb = new StringBuilder();
checksumCalculatingInputStream.mark(3);
boolean marked = true;
int count = 0;
for (int ch; (ch = checksumCalculatingInputStream.read()) != -1; ) {
sb.append((char) ch);
if(marked && count++ == 5){
checksumCalculatingInputStream.reset();
sb = new StringBuilder();
marked = false;
}
}
assertThat(sb).hasToString("b" + CRLF + initialString +CRLF + "0" + CRLF
+ "x-amz-checksum-sha-256:ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=" + CRLF+CRLF); }
}
| 2,016 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/checksum/ChecksumInstantiationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.checksum;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.utils.BinaryUtils;
class ChecksumInstantiationTest {
static final String TEST_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static Stream<Arguments> provideAlgorithmAndTestStringChecksums() {
return Stream.of(
Arguments.of(Algorithm.SHA1, "761c457bf73b14d27e9e9265c46f4b4dda11f940"),
Arguments.of(Algorithm.SHA256, "db4bfcbd4da0cd85a60c3c37d3fbd8805c77f15fc6b1fdfe614ee0a7c8fdb4c0"),
Arguments.of(Algorithm.CRC32, "000000000000000000000000000000001fc2e6d2"),
Arguments.of(Algorithm.CRC32C, "00000000000000000000000000000000a245d57d")
);
}
@ParameterizedTest
@MethodSource("provideAlgorithmAndTestStringChecksums")
void validateCheckSumValues(Algorithm algorithm, String expectedValue) {
final SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm);
final byte[] bytes = TEST_STRING.getBytes(StandardCharsets.UTF_8);
sdkChecksum.update(bytes, 0, bytes.length);
assertThat(getAsString(sdkChecksum.getChecksumBytes())).isEqualTo(expectedValue);
}
private static Stream<Arguments> provideAlgorithmAndTestBaseEncodedValue() {
return Stream.of(
Arguments.of(Algorithm.CRC32C, "Nks/tw=="),
Arguments.of(Algorithm.CRC32, "NSRBwg=="),
Arguments.of(Algorithm.SHA1, "qZk+NkcGgWq6PiVxeFDCbJzQ2J0="),
Arguments.of(Algorithm.SHA256, "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=")
);
}
@ParameterizedTest
@MethodSource("provideAlgorithmAndTestBaseEncodedValue")
void validateEncodedBase64ForAlgorithm(Algorithm algorithm, String expectedValue) {
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm);
sdkChecksum.update("abc".getBytes(StandardCharsets.UTF_8));
String toBase64 = BinaryUtils.toBase64(sdkChecksum.getChecksumBytes());
assertThat(toBase64).isEqualTo(expectedValue);
}
private static Stream<Arguments> provideAlgorithmAndTestMarkReset() {
return Stream.of(
Arguments.of(Algorithm.CRC32C, "Nks/tw=="),
Arguments.of(Algorithm.CRC32, "NSRBwg=="),
Arguments.of(Algorithm.SHA1, "qZk+NkcGgWq6PiVxeFDCbJzQ2J0="),
Arguments.of(Algorithm.SHA256, "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=")
);
}
@ParameterizedTest
@MethodSource("provideAlgorithmAndTestMarkReset")
void validateMarkAndResetForAlgorithm(Algorithm algorithm, String expectedValue) {
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm);
sdkChecksum.update("ab".getBytes(StandardCharsets.UTF_8));
sdkChecksum.mark(3);
sdkChecksum.update("xyz".getBytes(StandardCharsets.UTF_8));
sdkChecksum.reset();
sdkChecksum.update("c".getBytes(StandardCharsets.UTF_8));
String toBase64 = BinaryUtils.toBase64(sdkChecksum.getChecksumBytes());
assertThat(toBase64).isEqualTo(expectedValue);
}
private static Stream<Arguments> provideAlgorithmAndTestMarkNoReset() {
return Stream.of(
Arguments.of(Algorithm.CRC32C, "crUfeA=="),
Arguments.of(Algorithm.CRC32, "i9aeUg=="),
Arguments.of(Algorithm.SHA1, "e1AsOh9IyGCa4hLN+2Od7jlnP14="),
Arguments.of(Algorithm.SHA256, "ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=")
);
}
@ParameterizedTest
@MethodSource("provideAlgorithmAndTestMarkNoReset")
void validateMarkForMarkNoReset(Algorithm algorithm, String expectedValue) {
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm);
sdkChecksum.update("Hello ".getBytes(StandardCharsets.UTF_8));
sdkChecksum.mark(3);
sdkChecksum.update("world".getBytes(StandardCharsets.UTF_8));
String toBase64 = BinaryUtils.toBase64(sdkChecksum.getChecksumBytes());
assertThat(toBase64).isEqualTo(expectedValue);
}
private static Stream<Arguments> provideAlgorithmAndIntChecksums() {
return Stream.of(
Arguments.of(Algorithm.CRC32, "MtcGkw=="),
Arguments.of(Algorithm.SHA256, "AbpHGcgLb+kRsJGnwFEktk7uzpZOCcBY74+YBdrKVGs="),
Arguments.of(Algorithm.CRC32C, "OZ97aQ=="),
Arguments.of(Algorithm.SHA1, "rcg7GeeTSRscbqD9i0bNnzLlkvw=")
);
}
@ParameterizedTest
@MethodSource("provideAlgorithmAndIntChecksums")
void validateChecksumWithIntAsInput(Algorithm algorithm, String expectedValue) {
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm);
sdkChecksum.update(10);
assertThat(BinaryUtils.toBase64(sdkChecksum.getChecksumBytes())).isEqualTo(expectedValue);
}
private static Stream<Arguments> provide_SHA_AlgorithmAndExpectedException() {
return Stream.of(
Arguments.of(Algorithm.SHA256),
Arguments.of(Algorithm.SHA1)
);
}
@ParameterizedTest
@MethodSource("provide_SHA_AlgorithmAndExpectedException")
void validateShaChecksumWithIntAsInput(Algorithm algorithm) {
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm);
sdkChecksum.update(10);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> sdkChecksum.getValue());
}
private static Stream<Arguments> provide_CRC_AlgorithmAndExpectedValues() {
return Stream.of(
Arguments.of(Algorithm.CRC32, 852952723L),
Arguments.of(Algorithm.CRC32C, 966753129L)
);
}
@ParameterizedTest
@MethodSource("provide_CRC_AlgorithmAndExpectedValues")
void validateCrcChecksumWithIntAsInput(Algorithm algorithm, long expectedValue) {
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm);
sdkChecksum.update(10);
assertThat(sdkChecksum.getValue()).isEqualTo(expectedValue);
}
private static Stream<Arguments> provideAlgorithmAndResetWithNoMark() {
return Stream.of(
Arguments.of(Algorithm.CRC32C, "AAAAAA=="),
Arguments.of(Algorithm.CRC32, "AAAAAA=="),
Arguments.of(Algorithm.SHA1, "2jmj7l5rSw0yVb/vlWAYkK/YBwk="),
Arguments.of(Algorithm.SHA256, "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=")
);
}
@ParameterizedTest
@MethodSource("provideAlgorithmAndResetWithNoMark")
void validateChecksumWithResetAndNoMark(Algorithm algorithm, String expectedValue) {
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm);
sdkChecksum.update("abc".getBytes(StandardCharsets.UTF_8));
sdkChecksum.reset();
assertThat(BinaryUtils.toBase64(sdkChecksum.getChecksumBytes())).isEqualTo(expectedValue);
}
private String getAsString(byte[] checksumBytes) {
return String.format("%040x", new BigInteger(1, checksumBytes));
}
} | 2,017 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/exception/SdkExceptionMessageTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.exception;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* Verifies the ways in which a message in an {@link SdkException} can be populated.
*/
public class SdkExceptionMessageTest {
@Test
public void noMessage_noCause_implies_noMessage() {
assertThat(SdkException.builder().build().getMessage()).isEqualTo(null);
}
@Test
public void message_noCause_implies_messageFromMessage() {
assertThat(SdkException.builder().message("foo").build().getMessage()).isEqualTo("foo");
}
@Test
public void message_cause_implies_messageFromMessage() {
assertThat(SdkException.builder().message("foo").cause(new Exception("bar")).build().getMessage()).isEqualTo("foo");
}
@Test
public void noMessage_causeWithoutMessage_implies_noMessage() {
assertThat(SdkException.builder().cause(new Exception()).build().getMessage()).isEqualTo(null);
}
@Test
public void noMessage_causeWithMessage_implies_messageFromCause() {
assertThat(SdkException.builder().cause(new Exception("bar")).build().getMessage()).isEqualTo("bar");
}
} | 2,018 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/AsyncClientHandlerInterceptorExceptionTest.java |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.client;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.stubbing.Answer;
import org.testng.Assert;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.EmptyPublisher;
import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.client.handler.SdkAsyncClientHandler;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.protocol.VoidSdkResponse;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.runtime.transform.Marshaller;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import utils.HttpTestUtils;
import utils.ValidSdkObjects;
/**
* Tests to ensure that any failures thrown from calling into the {@link
* software.amazon.awssdk.core.interceptor.ExecutionInterceptor}s is reported
* through the returned {@link java.util.concurrent.CompletableFuture}.
*/
@RunWith(Parameterized.class)
public class AsyncClientHandlerInterceptorExceptionTest {
private final SdkRequest request = mock(SdkRequest.class);
private final SdkAsyncHttpClient asyncHttpClient = mock(SdkAsyncHttpClient.class);
private final Marshaller<SdkRequest> marshaller = mock(Marshaller.class);
private final HttpResponseHandler<SdkResponse> responseHandler = mock(HttpResponseHandler.class);
private final HttpResponseHandler<SdkServiceException> errorResponseHandler = mock(HttpResponseHandler.class);
private final Hook hook;
private SdkAsyncClientHandler clientHandler;
private ClientExecutionParams<SdkRequest, SdkResponse> executionParams;
@Parameterized.Parameters(name = "Interceptor Hook: {0}")
public static Collection<Object> data() {
return Arrays.asList(Hook.values());
}
public AsyncClientHandlerInterceptorExceptionTest(Hook hook) {
this.hook = hook;
}
@Before
public void testSetup() throws Exception {
executionParams = new ClientExecutionParams<SdkRequest, SdkResponse>()
.withInput(request)
.withMarshaller(marshaller)
.withResponseHandler(responseHandler)
.withErrorResponseHandler(errorResponseHandler);
SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder()
.option(SdkClientOption.EXECUTION_INTERCEPTORS, Collections.singletonList(hook.interceptor()))
.option(SdkClientOption.ASYNC_HTTP_CLIENT, asyncHttpClient)
.option(SdkClientOption.RETRY_POLICY, RetryPolicy.none())
.option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, Runnable::run)
.build();
clientHandler = new SdkAsyncClientHandler(config);
when(request.overrideConfiguration()).thenReturn(Optional.empty());
when(marshaller.marshall(eq(request))).thenReturn(ValidSdkObjects.sdkHttpFullRequest().build());
when(responseHandler.handle(any(SdkHttpFullResponse.class), any(ExecutionAttributes.class)))
.thenReturn(VoidSdkResponse.builder().build());
Answer<CompletableFuture<Void>> prepareRequestAnswer;
if (hook != Hook.ON_EXECUTION_FAILURE) {
prepareRequestAnswer = invocationOnMock -> {
SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgument(0, AsyncExecuteRequest.class).responseHandler();
handler.onHeaders(SdkHttpFullResponse.builder()
.statusCode(200)
.build());
handler.onStream(new EmptyPublisher<>());
return CompletableFuture.completedFuture(null);
};
} else {
prepareRequestAnswer = invocationOnMock -> {
SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgument(0, AsyncExecuteRequest.class).responseHandler();
RuntimeException error = new RuntimeException("Something went horribly wrong!");
handler.onError(error);
return CompletableFutureUtils.failedFuture(error);
};
}
when(asyncHttpClient.execute(any(AsyncExecuteRequest.class)))
.thenAnswer(prepareRequestAnswer);
}
@Test
public void test() {
if (hook != Hook.ON_EXECUTION_FAILURE) {
doVerify(() -> clientHandler.execute(executionParams), (t) -> ExceptionUtils.getRootCause(t).getMessage()
.equals(hook.name()));
} else {
// ON_EXECUTION_FAILURE is handled differently because we don't
// want an exception thrown from the interceptor to replace the
// original exception.
doVerify(() -> clientHandler.execute(executionParams),
(t) -> {
for (; t != null; t = t.getCause()) {
if (Hook.ON_EXECUTION_FAILURE.name().equals(t.getMessage())) {
return false;
}
}
return true;
});
}
}
private void doVerify(Supplier<CompletableFuture<?>> s, Predicate<Throwable> assertFn) {
CompletableFuture<?> cf = s.get();
try {
cf.join();
Assert.fail("get() method did not fail as expected.");
} catch (Throwable t) {
assertTrue(assertFn.test(t));
}
}
public enum Hook {
BEFORE_EXECUTION(new ExecutionInterceptor() {
@Override
public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) {
throw new RuntimeException(BEFORE_EXECUTION.name());
}
}),
MODIFY_REQUEST(new ExecutionInterceptor() {
@Override
public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) {
throw new RuntimeException(MODIFY_REQUEST.name());
}
}),
BEFORE_MARSHALLING(new ExecutionInterceptor() {
@Override
public void beforeMarshalling(Context.BeforeMarshalling context, ExecutionAttributes executionAttributes) {
throw new RuntimeException(BEFORE_MARSHALLING.name());
}
}),
AFTER_MARSHALLING(new ExecutionInterceptor() {
@Override
public void afterMarshalling(Context.AfterMarshalling context, ExecutionAttributes executionAttributes) {
throw new RuntimeException(AFTER_MARSHALLING.name());
}
}),
MODIFY_HTTP_REQUEST(new ExecutionInterceptor() {
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes) {
throw new RuntimeException(MODIFY_HTTP_REQUEST.name());
}
}),
BEFORE_TRANSMISSION(new ExecutionInterceptor() {
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
throw new RuntimeException(BEFORE_TRANSMISSION.name());
}
}),
AFTER_TRANSMISSION(new ExecutionInterceptor() {
@Override
public void afterTransmission(Context.AfterTransmission context, ExecutionAttributes executionAttributes) {
throw new RuntimeException(AFTER_TRANSMISSION.name());
}
}),
MODIFY_HTTP_RESPONSE(new ExecutionInterceptor() {
@Override
public SdkHttpFullResponse modifyHttpResponse(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes) {
throw new RuntimeException(MODIFY_HTTP_RESPONSE.name());
}
}),
BEFORE_UNMARSHALLING(new ExecutionInterceptor() {
@Override
public void beforeUnmarshalling(Context.BeforeUnmarshalling context, ExecutionAttributes executionAttributes) {
throw new RuntimeException(BEFORE_UNMARSHALLING.name());
}
}),
AFTER_UNMARSHALLING(new ExecutionInterceptor() {
@Override
public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) {
throw new RuntimeException(AFTER_UNMARSHALLING.name());
}
}),
MODIFY_RESPONSE(new ExecutionInterceptor() {
@Override
public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) {
throw new RuntimeException(MODIFY_RESPONSE.name());
}
}),
AFTER_EXECUTION(new ExecutionInterceptor() {
@Override
public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) {
throw new RuntimeException(AFTER_EXECUTION.name());
}
}),
ON_EXECUTION_FAILURE(new ExecutionInterceptor() {
@Override
public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) {
throw new RuntimeException(ON_EXECUTION_FAILURE.name());
}
})
;
private ExecutionInterceptor interceptor;
Hook(ExecutionInterceptor interceptor) {
this.interceptor = interceptor;
}
public ExecutionInterceptor interceptor() {
return interceptor;
}
}
}
| 2,019 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/AsyncClientHandlerExceptionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.client;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.Assert.fail;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.stubbing.Answer;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.EmptyPublisher;
import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.client.handler.SdkAsyncClientHandler;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.protocol.VoidSdkResponse;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.runtime.transform.Marshaller;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import utils.HttpTestUtils;
import utils.ValidSdkObjects;
/**
* Tests to verify that when exceptions are thrown during various stages of
* execution within the handler, they are reported through the returned {@link
* java.util.concurrent.CompletableFuture}.
*
* @see AsyncClientHandlerInterceptorExceptionTest
*/
public class AsyncClientHandlerExceptionTest {
private final SdkRequest request = mock(SdkRequest.class);
private final SdkAsyncHttpClient asyncHttpClient = mock(SdkAsyncHttpClient.class);
private final Marshaller<SdkRequest> marshaller = mock(Marshaller.class);
private final HttpResponseHandler<SdkResponse> responseHandler = mock(HttpResponseHandler.class);
private final HttpResponseHandler<SdkServiceException> errorResponseHandler = mock(HttpResponseHandler.class);
private SdkAsyncClientHandler clientHandler;
private ClientExecutionParams<SdkRequest, SdkResponse> executionParams;
@BeforeEach
public void methodSetup() throws Exception {
executionParams = new ClientExecutionParams<SdkRequest, SdkResponse>()
.withInput(request)
.withMarshaller(marshaller)
.withResponseHandler(responseHandler)
.withErrorResponseHandler(errorResponseHandler);
SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder()
.option(SdkClientOption.ASYNC_HTTP_CLIENT, asyncHttpClient)
.option(SdkClientOption.RETRY_POLICY, RetryPolicy.none())
.option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, Runnable::run)
.build();
clientHandler = new SdkAsyncClientHandler(config);
when(request.overrideConfiguration()).thenReturn(Optional.empty());
when(marshaller.marshall(eq(request))).thenReturn(ValidSdkObjects.sdkHttpFullRequest().build());
when(responseHandler.handle(any(SdkHttpFullResponse.class), any(ExecutionAttributes.class)))
.thenReturn(VoidSdkResponse.builder().build());
when(asyncHttpClient.execute(any(AsyncExecuteRequest.class))).thenAnswer((Answer<CompletableFuture<Void>>) invocationOnMock -> {
SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgument(0, AsyncExecuteRequest.class).responseHandler();
handler.onHeaders(SdkHttpFullResponse.builder()
.statusCode(200)
.build());
handler.onStream(new EmptyPublisher<>());
return CompletableFuture.completedFuture(null);
});
}
@Test
public void marshallerThrowsReportedThroughFuture() throws Exception {
final SdkClientException e = SdkClientException.create("Could not marshall");
when(marshaller.marshall(any(SdkRequest.class))).thenThrow(e);
doVerify(() -> clientHandler.execute(executionParams), e);
}
@Test
public void responseHandlerThrowsReportedThroughFuture() throws Exception {
final SdkClientException e = SdkClientException.create("Could not handle response");
when(responseHandler.handle(any(SdkHttpFullResponse.class), any(ExecutionAttributes.class))).thenThrow(e);
doVerify(() -> clientHandler.execute(executionParams), e);
}
@Test
public void streamingRequest_marshallingException_shouldInvokeExceptionOccurred() throws Exception {
AsyncResponseTransformer asyncResponseTransformer = mock(AsyncResponseTransformer.class);
CompletableFuture<?> future = new CompletableFuture<>();
when(asyncResponseTransformer.prepare()).thenReturn(future);
SdkClientException exception = SdkClientException.create("Could not handle response");
when(marshaller.marshall(any(SdkRequest.class))).thenThrow(exception);
doVerify(() -> clientHandler.execute(executionParams, asyncResponseTransformer), exception);
verify(asyncResponseTransformer, times(1)).prepare();
verify(asyncResponseTransformer, times(1)).exceptionOccurred(exception);
}
private void doVerify(Supplier<CompletableFuture<?>> s, final Throwable expectedException) {
doVerify(s, (thrown) -> thrown.getCause() == expectedException);
}
private void doVerify(Supplier<CompletableFuture<?>> s, Predicate<Throwable> assertFn) {
CompletableFuture<?> cf = s.get();
try {
cf.get();
fail("get() method did not fail as expected.");
} catch (Throwable t) {
assertTrue(assertFn.test(t));
}
}
}
| 2,020 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/handler/AsyncClientHandlerTransformerVerificationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.client.handler;
import static junit.framework.TestCase.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;
import java.nio.ByteBuffer;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Before;
import org.junit.Test;
import org.mockito.stubbing.Answer;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.DrainingSubscriber;
import software.amazon.awssdk.core.async.EmptyPublisher;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.exception.RetryableException;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.protocol.VoidSdkResponse;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.runtime.transform.Marshaller;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import utils.HttpTestUtils;
import utils.ValidSdkObjects;
/**
* Verification tests to ensure that the behavior of {@link SdkAsyncClientHandler} is in line with the
* {@link AsyncResponseTransformer} interface.
*/
public class AsyncClientHandlerTransformerVerificationTest {
private static final RetryPolicy RETRY_POLICY = RetryPolicy.defaultRetryPolicy();
private final SdkRequest request = mock(SdkRequest.class);
private final Marshaller<SdkRequest> marshaller = mock(Marshaller.class);
private final HttpResponseHandler<SdkResponse> responseHandler = mock(HttpResponseHandler.class);
private final HttpResponseHandler<SdkServiceException> errorResponseHandler = mock(HttpResponseHandler.class);
private SdkAsyncHttpClient mockClient;
private SdkAsyncClientHandler clientHandler;
private ClientExecutionParams<SdkRequest, SdkResponse> executionParams;
@Before
public void testSetup() throws Exception {
mockClient = mock(SdkAsyncHttpClient.class);
executionParams = new ClientExecutionParams<SdkRequest, SdkResponse>()
.withInput(request)
.withMarshaller(marshaller)
.withResponseHandler(responseHandler)
.withErrorResponseHandler(errorResponseHandler);
SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder()
.option(SdkClientOption.ASYNC_HTTP_CLIENT, mockClient)
.option(SdkClientOption.RETRY_POLICY, RETRY_POLICY)
.option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, Runnable::run)
.build();
clientHandler = new SdkAsyncClientHandler(config);
when(request.overrideConfiguration()).thenReturn(Optional.empty());
when(marshaller.marshall(eq(request))).thenReturn(ValidSdkObjects.sdkHttpFullRequest().build());
when(responseHandler.handle(any(), any())).thenReturn(VoidSdkResponse.builder().build());
}
@Test
public void marshallerThrowsException_shouldTriggerExceptionOccurred() {
SdkClientException exception = SdkClientException.create("Could not handle response");
when(marshaller.marshall(any(SdkRequest.class))).thenThrow(exception);
AtomicBoolean exceptionOccurred = new AtomicBoolean(false);
executeAndWaitError(new TestTransformer<SdkResponse, Void>(){
@Override
public void exceptionOccurred(Throwable error) {
exceptionOccurred.set(true);
super.exceptionOccurred(error);
}
});
assertThat(exceptionOccurred.get()).isTrue();
}
@Test
public void nonRetryableErrorDoesNotTriggerRetry() {
mockSuccessfulResponse();
AtomicLong prepareCalls = new AtomicLong(0);
executeAndWaitError(new TestTransformer<SdkResponse, Void>() {
@Override
public CompletableFuture<Void> prepare() {
prepareCalls.incrementAndGet();
return super.prepare();
}
@Override
public void onStream(SdkPublisher<ByteBuffer> stream) {
super.transformFuture().completeExceptionally(new RuntimeException("some error"));
}
});
assertThat(prepareCalls.get()).isEqualTo(1L);
}
@Test
public void prepareCallsEqualToExecuteAttempts() {
mockSuccessfulResponse();
AtomicLong prepareCalls = new AtomicLong(0);
executeAndWaitError(new TestTransformer<SdkResponse, Void>() {
@Override
public CompletableFuture<Void> prepare() {
prepareCalls.incrementAndGet();
return super.prepare();
}
@Override
public void onStream(SdkPublisher<ByteBuffer> stream) {
stream.subscribe(new DrainingSubscriber<ByteBuffer>() {
@Override
public void onComplete() {
transformFuture().completeExceptionally(RetryableException.builder().message("retry me please: " + prepareCalls.get()).build());
}
});
}
});
assertThat(prepareCalls.get()).isEqualTo(1 + RETRY_POLICY.numRetries());
}
@Test//(timeout = 1000L)
public void handlerExecutionCompletesIndependentlyOfRequestExecution_CompleteAfterResponse() {
mockSuccessfulResponse_NonSignalingStream();
// Since we never signal any elements on the response stream, if the async client handler waited for the stream to
// finish before completing the future, this would never return.
assertThat(execute(new TestTransformer<SdkResponse, SdkResponse>() {
@Override
public void onResponse(SdkResponse response) {
transformFuture().complete(response);
}
})).isNotNull();
}
@Test(timeout = 1000L)
public void handlerExecutionCompletesIndependentlyOfRequestExecution_CompleteAfterStream() {
mockSuccessfulResponse_NonSignalingStream();
// Since we never signal any elements on the response stream, if the async client handler waited for the stream to
// finish before completing the future, this would never return.
assertThat(execute(new TestTransformer<SdkResponse, Publisher<ByteBuffer>>() {
@Override
public void onStream(SdkPublisher<ByteBuffer> stream) {
transformFuture().complete(stream);
}
})).isNotNull();
}
private void mockSuccessfulResponse() {
Answer<CompletableFuture<Void>> executeAnswer = invocationOnMock -> {
SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgument(0, AsyncExecuteRequest.class).responseHandler();
handler.onHeaders(SdkHttpFullResponse.builder()
.statusCode(200)
.build());
handler.onStream(new EmptyPublisher<>());
return CompletableFuture.completedFuture(null);
};
reset(mockClient);
when(mockClient.execute(any(AsyncExecuteRequest.class))).thenAnswer(executeAnswer);
}
/**
* Mock a response with success status (200), but with a stream that never signals anything on the Subscriber. This
* roughly emulates a very slow response.
*/
private void mockSuccessfulResponse_NonSignalingStream() {
Answer<CompletableFuture<Void>> executeAnswer = invocationOnMock -> {
SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgument(0, AsyncExecuteRequest.class).responseHandler();
handler.onHeaders(SdkHttpFullResponse.builder()
.statusCode(200)
.build());
handler.onStream(subscriber -> {
// never signal onSubscribe
});
return CompletableFuture.completedFuture(null);
};
reset(mockClient);
when(mockClient.execute(any())).thenAnswer(executeAnswer);
}
private void executeAndWaitError(AsyncResponseTransformer<SdkResponse, ?> transformer) {
try {
execute(transformer);
fail("Client execution should have completed exceptionally");
} catch (CompletionException e) {
// ignored
}
}
private <ResultT> ResultT execute(AsyncResponseTransformer<SdkResponse, ResultT> transformer) {
return clientHandler.execute(executionParams, transformer).join();
}
private static class TestTransformer<ResponseT, ResultT> implements AsyncResponseTransformer<ResponseT, ResultT> {
private volatile CompletableFuture<ResultT> transformFuture;
@Override
public CompletableFuture<ResultT> prepare() {
this.transformFuture = new CompletableFuture<>();
return transformFuture;
}
@Override
public void onResponse(ResponseT response) {
}
@Override
public void onStream(SdkPublisher<ByteBuffer> publisher) {
publisher.subscribe(new DrainingSubscriber<ByteBuffer>() {
@Override
public void onComplete() {
transformFuture.complete(null);
}
});
}
@Override
public void exceptionOccurred(Throwable error) {
transformFuture.completeExceptionally(error);
}
CompletableFuture<ResultT> transformFuture() {
return transformFuture;
}
}
}
| 2,021 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/handler/SyncClientHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.client.handler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.exception.AbortedException;
import software.amazon.awssdk.core.exception.NonRetryableException;
import software.amazon.awssdk.core.exception.RetryableException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.protocol.VoidSdkResponse;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.runtime.transform.Marshaller;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import utils.HttpTestUtils;
import utils.ValidSdkObjects;
@RunWith(MockitoJUnitRunner.class)
public class SyncClientHandlerTest {
private SdkSyncClientHandler syncClientHandler;
@Mock
private SdkRequest request;
@Mock
private Marshaller<SdkRequest> marshaller;
private SdkHttpFullRequest marshalledRequest = ValidSdkObjects.sdkHttpFullRequest().build();
@Mock
private SdkHttpClient httpClient;
@Mock
private ExecutableHttpRequest httpClientCall;
@Mock
private HttpResponseHandler<SdkResponse> responseHandler;
@Mock
private HttpResponseHandler<SdkServiceException> errorResponseHandler;
@Mock
private ResponseTransformer<SdkResponse, ?> responseTransformer;
@Before
public void setup() {
this.syncClientHandler = new SdkSyncClientHandler(clientConfiguration());
when(request.overrideConfiguration()).thenReturn(Optional.empty());
}
@Test
public void successfulExecutionCallsResponseHandler() throws Exception {
SdkResponse expected = VoidSdkResponse.builder().build();
Map<String, List<String>> headers = new HashMap<>();
headers.put("foo", Arrays.asList("bar"));
// Given
expectRetrievalFromMocks();
when(httpClientCall.call()).thenReturn(HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(200)
.headers(headers)
.build())
.build()); // Successful HTTP call
when(responseHandler.handle(any(), any())).thenReturn(expected); // Response handler call
// When
SdkResponse actual = syncClientHandler.execute(clientExecutionParams());
// Then
verifyNoMoreInteractions(errorResponseHandler); // No error handler calls
assertThat(actual.sdkHttpResponse().statusCode()).isEqualTo(200);
assertThat(actual.sdkHttpResponse().headers()).isEqualTo(headers);
}
@Test
public void failedExecutionCallsErrorResponseHandler() throws Exception {
SdkServiceException exception = SdkServiceException.builder().message("Uh oh!").statusCode(500).build();
Map<String, List<String>> headers = new HashMap<>();
headers.put("foo", Arrays.asList("bar"));
// Given
expectRetrievalFromMocks();
when(httpClientCall.call()).thenReturn(HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(500)
.headers(headers)
.build())
.build()); // Failed HTTP call
when(errorResponseHandler.handle(any(), any())).thenReturn(exception); // Error response handler call
// When
assertThatThrownBy(() -> syncClientHandler.execute(clientExecutionParams())).isEqualToComparingFieldByField(exception);
// Then
verifyNoMoreInteractions(responseHandler); // No response handler calls
}
@Test
public void responseTransformerThrowsRetryableException_shouldPropogate() throws Exception {
mockSuccessfulApiCall();
when(responseTransformer.transform(any(SdkResponse.class), any(AbortableInputStream.class))).thenThrow(
RetryableException.create("test"));
assertThatThrownBy(() -> syncClientHandler.execute(clientExecutionParams(), responseTransformer))
.isInstanceOf(RetryableException.class);
}
@Test
public void responseTransformerThrowsInterruptedException_shouldPropagate() throws Exception {
try {
verifyResponseTransformerPropagateException(new InterruptedException());
} finally {
Thread.interrupted();
}
}
@Test
public void responseTransformerThrowsAbortedException_shouldPropagate() throws Exception {
verifyResponseTransformerPropagateException(AbortedException.create(""));
}
@Test
public void responseTransformerThrowsOtherException_shouldWrapWithNonRetryableException() throws Exception {
mockSuccessfulApiCall();
when(responseTransformer.transform(any(SdkResponse.class), any(AbortableInputStream.class))).thenThrow(
new RuntimeException());
assertThatThrownBy(() -> syncClientHandler.execute(clientExecutionParams(), responseTransformer))
.hasCauseInstanceOf(NonRetryableException.class);
}
private void verifyResponseTransformerPropagateException(Exception exception) throws Exception {
mockSuccessfulApiCall();
when(responseTransformer.transform(any(SdkResponse.class), any(AbortableInputStream.class))).thenThrow(
exception);
assertThatThrownBy(() -> syncClientHandler.execute(clientExecutionParams(), responseTransformer))
.hasCauseInstanceOf(exception.getClass());
}
private void mockSuccessfulApiCall() throws Exception {
expectRetrievalFromMocks();
when(httpClientCall.call()).thenReturn(HttpExecuteResponse.builder()
.responseBody(AbortableInputStream.create(new ByteArrayInputStream("TEST".getBytes())))
.response(SdkHttpResponse.builder().statusCode(200).build())
.build());
when(responseHandler.handle(any(), any())).thenReturn(VoidSdkResponse.builder().build());
}
private void expectRetrievalFromMocks() {
when(marshaller.marshall(request)).thenReturn(marshalledRequest);
when(httpClient.prepareRequest(any())).thenReturn(httpClientCall);
}
private ClientExecutionParams<SdkRequest, SdkResponse> clientExecutionParams() {
return new ClientExecutionParams<SdkRequest, SdkResponse>()
.withInput(request)
.withMarshaller(marshaller)
.withResponseHandler(responseHandler)
.withErrorResponseHandler(errorResponseHandler);
}
public SdkClientConfiguration clientConfiguration() {
return HttpTestUtils.testClientConfiguration().toBuilder()
.option(SdkClientOption.SYNC_HTTP_CLIENT, httpClient)
.option(SdkClientOption.RETRY_POLICY, RetryPolicy.none())
.build();
}
}
| 2,022 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/handler/AsyncClientHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.client.handler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.EmptyPublisher;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.protocol.VoidSdkResponse;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.runtime.transform.Marshaller;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import utils.HttpTestUtils;
import utils.ValidSdkObjects;
@RunWith(MockitoJUnitRunner.class)
public class AsyncClientHandlerTest {
private SdkAsyncClientHandler asyncClientHandler;
@Mock
private SdkRequest request;
@Mock
private Marshaller<SdkRequest> marshaller;
private SdkHttpFullRequest marshalledRequest = ValidSdkObjects.sdkHttpFullRequest().build();
@Mock
private SdkAsyncHttpClient httpClient;
private CompletableFuture<Void> httpClientFuture = CompletableFuture.completedFuture(null);
@Mock
private HttpResponseHandler<SdkResponse> responseHandler;
@Mock
private HttpResponseHandler<SdkServiceException> errorResponseHandler;
@Before
public void setup() {
this.asyncClientHandler = new SdkAsyncClientHandler(clientConfiguration());
when(request.overrideConfiguration()).thenReturn(Optional.empty());
}
@Test
public void successfulExecutionCallsResponseHandler() throws Exception {
// Given
SdkResponse expected = VoidSdkResponse.builder().build();
Map<String, List<String>> headers = new HashMap<>();
headers.put("foo", Arrays.asList("bar"));
ArgumentCaptor<AsyncExecuteRequest> executeRequest = ArgumentCaptor.forClass(AsyncExecuteRequest.class);
expectRetrievalFromMocks();
when(httpClient.execute(executeRequest.capture())).thenReturn(httpClientFuture);
when(responseHandler.handle(any(), any())).thenReturn(expected); // Response handler call
// When
CompletableFuture<SdkResponse> responseFuture = asyncClientHandler.execute(clientExecutionParams());
SdkAsyncHttpResponseHandler capturedHandler = executeRequest.getValue().responseHandler();
capturedHandler.onHeaders(SdkHttpFullResponse.builder().statusCode(200)
.headers(headers).build());
capturedHandler.onStream(new EmptyPublisher<>());
SdkResponse actualResponse = responseFuture.get(1, TimeUnit.SECONDS);
// Then
verifyNoMoreInteractions(errorResponseHandler); // No error handler calls
assertThat(actualResponse.sdkHttpResponse().statusCode()).isEqualTo(200);
assertThat(actualResponse.sdkHttpResponse().headers()).isEqualTo(headers);
}
@Test
public void failedExecutionCallsErrorResponseHandler() throws Exception {
SdkServiceException exception = SdkServiceException.builder().message("Uh oh!").statusCode(500).build();
// Given
ArgumentCaptor<AsyncExecuteRequest> executeRequest = ArgumentCaptor.forClass(AsyncExecuteRequest.class);
expectRetrievalFromMocks();
when(httpClient.execute(executeRequest.capture())).thenReturn(httpClientFuture);
when(errorResponseHandler.handle(any(), any())).thenReturn(exception); // Error response handler call
// When
CompletableFuture<SdkResponse> responseFuture = asyncClientHandler.execute(clientExecutionParams());
SdkAsyncHttpResponseHandler capturedHandler = executeRequest.getValue().responseHandler();
capturedHandler.onHeaders(SdkHttpFullResponse.builder().statusCode(500).build());
capturedHandler.onStream(new EmptyPublisher<>());
assertThatThrownBy(() -> responseFuture.get(1, TimeUnit.SECONDS)).hasCause(exception);
// Then
verifyNoMoreInteractions(responseHandler); // Response handler is not called
}
private void expectRetrievalFromMocks() {
when(marshaller.marshall(request)).thenReturn(marshalledRequest);
}
private ClientExecutionParams<SdkRequest, SdkResponse> clientExecutionParams() {
return new ClientExecutionParams<SdkRequest, SdkResponse>()
.withInput(request)
.withMarshaller(marshaller)
.withResponseHandler(responseHandler)
.withErrorResponseHandler(errorResponseHandler);
}
public SdkClientConfiguration clientConfiguration() {
return HttpTestUtils.testClientConfiguration().toBuilder()
.option(SdkClientOption.ASYNC_HTTP_CLIENT, httpClient)
.option(SdkClientOption.RETRY_POLICY, RetryPolicy.none())
.build();
}
}
| 2,023 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/handler/ClientHandlerSignerValidationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.client.handler;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.CredentialType;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.protocol.VoidSdkResponse;
import software.amazon.awssdk.core.runtime.transform.Marshaller;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpRequest;
import utils.HttpTestUtils;
import utils.ValidSdkObjects;
@RunWith(MockitoJUnitRunner.class)
public class ClientHandlerSignerValidationTest {
private final SdkRequest request = ValidSdkObjects.sdkRequest();
@Mock
private Marshaller<SdkRequest> marshaller;
@Mock
private SdkHttpClient httpClient;
@Mock
private Signer signer;
@Mock
private HttpResponseHandler<SdkResponse> responseHandler;
private CompletableFuture<Void> httpClientFuture = CompletableFuture.completedFuture(null);
@Mock
private ExecutableHttpRequest httpClientCall;
@Before
public void setup() throws Exception {
when(httpClient.prepareRequest(any(HttpExecuteRequest.class))).thenReturn(httpClientCall);
when(httpClientCall.call()).thenReturn(
HttpExecuteResponse.builder()
.response(SdkHttpFullResponse.builder()
.statusCode(200)
.build())
.build());
when(signer.credentialType()).thenReturn(CredentialType.TOKEN);
SdkResponse mockSdkResponse = VoidSdkResponse.builder().build();
when(responseHandler.handle(any(), any())).thenReturn(mockSdkResponse);
}
@Test
public void execute_requestHasHttpEndpoint_usesBearerAuth_fails() {
SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build();
when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest);
SdkClientConfiguration config = testClientConfiguration();
SdkSyncClientHandler sdkSyncClientHandler = new SdkSyncClientHandler(config);
assertThatThrownBy(() -> sdkSyncClientHandler.execute(executionParams()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("plaintext HTTP endpoint");
}
@Test
public void execute_interceptorChangesToHttp_usesBearerAuth_fails() {
SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("https").build();
when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest);
ExecutionInterceptor interceptor = new ExecutionInterceptor() {
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
return context.httpRequest()
.toBuilder()
.protocol("http")
.build();
}
};
SdkClientConfiguration config = testClientConfiguration()
.toBuilder()
.option(SdkClientOption.EXECUTION_INTERCEPTORS, Collections.singletonList(interceptor))
.build();
SdkSyncClientHandler sdkSyncClientHandler = new SdkSyncClientHandler(config);
assertThatThrownBy(() -> sdkSyncClientHandler.execute(executionParams()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("plaintext HTTP endpoint");
}
@Test
public void execute_interceptorChangesToHttps_usesBearerAuth_succeeds() {
SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build();
when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest);
when(signer.sign(any(), any())).thenReturn(httpRequest);
ExecutionInterceptor interceptor = new ExecutionInterceptor() {
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
return context.httpRequest()
.toBuilder()
.protocol("https")
.build();
}
};
SdkClientConfiguration config = testClientConfiguration()
.toBuilder()
.option(SdkClientOption.EXECUTION_INTERCEPTORS, Collections.singletonList(interceptor))
.build();
SdkSyncClientHandler sdkSyncClientHandler = new SdkSyncClientHandler(config);
assertThatNoException().isThrownBy(() -> sdkSyncClientHandler.execute(executionParams()));
}
@Test
public void execute_requestHasHttpsEndpoint_usesBearerAuth_succeeds(){
SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("https").build();
when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest);
when(signer.sign(any(), any())).thenReturn(httpRequest);
SdkSyncClientHandler sdkSyncClientHandler = new SdkSyncClientHandler(testClientConfiguration());
assertThatNoException().isThrownBy(() -> sdkSyncClientHandler.execute(executionParams()));
}
@Test
public void execute_requestHasHttpEndpoint_doesNotBearerAuth_succeeds(){
SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build();
when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest);
when(signer.sign(any(), any())).thenReturn(httpRequest);
when(signer.credentialType()).thenReturn(CredentialType.of("AWS"));
SdkSyncClientHandler sdkSyncClientHandler = new SdkSyncClientHandler(testClientConfiguration());
assertThatNoException().isThrownBy(() -> sdkSyncClientHandler.execute(executionParams()));
}
private ClientExecutionParams<SdkRequest, SdkResponse> executionParams() {
return new ClientExecutionParams<SdkRequest, SdkResponse>()
.withInput(request)
.withMarshaller(marshaller)
.withResponseHandler(responseHandler);
}
private SdkClientConfiguration testClientConfiguration() {
return HttpTestUtils.testClientConfiguration()
.toBuilder()
.option(SdkClientOption.SYNC_HTTP_CLIENT, httpClient)
.option(SdkAdvancedClientOption.SIGNER, signer)
.build();
}
}
| 2,024 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/handler/AsyncClientHandlerSignerValidationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.client.handler;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.CredentialType;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.EmptyPublisher;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.protocol.VoidSdkResponse;
import software.amazon.awssdk.core.runtime.transform.Marshaller;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import utils.HttpTestUtils;
import utils.ValidSdkObjects;
@RunWith(MockitoJUnitRunner.class)
public class AsyncClientHandlerSignerValidationTest {
private final SdkRequest request = ValidSdkObjects.sdkRequest();
@Mock
private Marshaller<SdkRequest> marshaller;
@Mock
private SdkAsyncHttpClient httpClient;
@Mock
private Signer signer;
@Mock
private HttpResponseHandler<SdkResponse> responseHandler;
private CompletableFuture<Void> httpClientFuture = CompletableFuture.completedFuture(null);
private ArgumentCaptor<AsyncExecuteRequest> executeRequestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class);
@Before
public void setup() {
when(httpClient.execute(executeRequestCaptor.capture())).thenReturn(httpClientFuture);
when(signer.credentialType()).thenReturn(CredentialType.TOKEN);
}
@Test
public void execute_requestHasHttpEndpoint_usesBearerAuth_fails() {
SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build();
when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest);
SdkClientConfiguration config = testClientConfiguration();
SdkAsyncClientHandler sdkAsyncClientHandler = new SdkAsyncClientHandler(config);
CompletableFuture<SdkResponse> execute = sdkAsyncClientHandler.execute(executionParams());
assertThatThrownBy(execute::get)
.hasCauseInstanceOf(SdkClientException.class)
.hasMessageContaining("plaintext HTTP endpoint");
}
@Test
public void execute_interceptorChangesToHttp_usesBearerAuth_fails() {
SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("https").build();
when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest);
ExecutionInterceptor interceptor = new ExecutionInterceptor() {
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
return context.httpRequest()
.toBuilder()
.protocol("http")
.build();
}
};
SdkClientConfiguration config = testClientConfiguration()
.toBuilder()
.option(SdkClientOption.EXECUTION_INTERCEPTORS, Collections.singletonList(interceptor))
.build();
SdkAsyncClientHandler sdkAsyncClientHandler = new SdkAsyncClientHandler(config);
CompletableFuture<SdkResponse> execute = sdkAsyncClientHandler.execute(executionParams());
assertThatThrownBy(execute::get)
.hasCauseInstanceOf(SdkClientException.class)
.hasMessageContaining("plaintext HTTP endpoint");
}
@Test
public void execute_interceptorChangesToHttps_usesBearerAuth_succeeds() throws Exception {
SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build();
when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest);
when(signer.sign(any(), any())).thenReturn(httpRequest);
SdkResponse mockSdkResponse = VoidSdkResponse.builder().build();
when(responseHandler.handle(any(), any())).thenReturn(mockSdkResponse);
ExecutionInterceptor interceptor = new ExecutionInterceptor() {
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
return context.httpRequest()
.toBuilder()
.protocol("https")
.build();
}
};
SdkClientConfiguration config = testClientConfiguration()
.toBuilder()
.option(SdkClientOption.EXECUTION_INTERCEPTORS, Collections.singletonList(interceptor))
.build();
SdkAsyncClientHandler sdkAsyncClientHandler = new SdkAsyncClientHandler(config);
CompletableFuture<SdkResponse> execute = sdkAsyncClientHandler.execute(executionParams());
SdkAsyncHttpResponseHandler capturedHandler = executeRequestCaptor.getValue().responseHandler();
Map<String, List<String>> headers = new HashMap<>();
headers.put("foo", Arrays.asList("bar"));
capturedHandler.onHeaders(SdkHttpFullResponse.builder()
.statusCode(200)
.headers(headers)
.build());
capturedHandler.onStream(new EmptyPublisher<>());
assertThatNoException().isThrownBy(execute::get);
}
@Test
public void execute_requestHasHttpsEndpoint_usesBearerAuth_succeeds() throws Exception {
SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("https").build();
when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest);
when(signer.sign(any(), any())).thenReturn(httpRequest);
SdkResponse mockSdkResponse = VoidSdkResponse.builder().build();
when(responseHandler.handle(any(), any())).thenReturn(mockSdkResponse);
SdkAsyncClientHandler sdkAsyncClientHandler = new SdkAsyncClientHandler(testClientConfiguration());
CompletableFuture<SdkResponse> execute = sdkAsyncClientHandler.execute(executionParams());
SdkAsyncHttpResponseHandler capturedHandler = executeRequestCaptor.getValue().responseHandler();
Map<String, List<String>> headers = new HashMap<>();
headers.put("foo", Arrays.asList("bar"));
capturedHandler.onHeaders(SdkHttpFullResponse.builder()
.statusCode(200)
.headers(headers)
.build());
capturedHandler.onStream(new EmptyPublisher<>());
assertThatNoException().isThrownBy(execute::get);
}
@Test
public void execute_requestHasHttpEndpoint_doesNotBearerAuth_succeeds() throws Exception {
SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build();
when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest);
when(signer.credentialType()).thenReturn(CredentialType.of("AWS"));
when(signer.sign(any(), any())).thenReturn(httpRequest);
SdkResponse mockSdkResponse = VoidSdkResponse.builder().build();
when(responseHandler.handle(any(), any())).thenReturn(mockSdkResponse);
SdkAsyncClientHandler sdkAsyncClientHandler = new SdkAsyncClientHandler(testClientConfiguration());
CompletableFuture<SdkResponse> execute = sdkAsyncClientHandler.execute(executionParams());
SdkAsyncHttpResponseHandler capturedHandler = executeRequestCaptor.getValue().responseHandler();
Map<String, List<String>> headers = new HashMap<>();
headers.put("foo", Arrays.asList("bar"));
capturedHandler.onHeaders(SdkHttpFullResponse.builder()
.statusCode(200)
.headers(headers)
.build());
capturedHandler.onStream(new EmptyPublisher<>());
assertThatNoException().isThrownBy(execute::get);
}
private ClientExecutionParams<SdkRequest, SdkResponse> executionParams() {
return new ClientExecutionParams<SdkRequest, SdkResponse>()
.withInput(request)
.withMarshaller(marshaller)
.withResponseHandler(responseHandler);
}
private SdkClientConfiguration testClientConfiguration() {
return HttpTestUtils.testClientConfiguration()
.toBuilder()
.option(SdkClientOption.ASYNC_HTTP_CLIENT, httpClient)
.option(SdkAdvancedClientOption.SIGNER, signer)
.build();
}
}
| 2,025 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/config/ClientOverrideConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.client.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.internal.http.request.SlowExecutionInterceptor;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.utils.ImmutableMap;
public class ClientOverrideConfigurationTest {
private static final ConcurrentMap<String, ExecutionAttribute<Object>> ATTR_POOL = new ConcurrentHashMap<>();
private static ExecutionAttribute<Object> attr(String name) {
name = ClientOverrideConfigurationTest.class.getName() + ":" + name;
return ATTR_POOL.computeIfAbsent(name, ExecutionAttribute::new);
}
@Test
public void addingSameItemTwice_shouldOverride() {
ClientOverrideConfiguration configuration = ClientOverrideConfiguration.builder()
.putHeader("value", "foo")
.putHeader("value", "bar")
.putAdvancedOption(SdkAdvancedClientOption
.USER_AGENT_SUFFIX, "foo")
.putAdvancedOption(SdkAdvancedClientOption
.USER_AGENT_SUFFIX, "bar")
.build();
assertThat(configuration.headers().get("value")).containsExactly("bar");
assertThat(configuration.advancedOption(SdkAdvancedClientOption.USER_AGENT_SUFFIX).get()).isEqualTo("bar");
ClientOverrideConfiguration anotherConfig = configuration.toBuilder().putHeader("value", "foobar").build();
assertThat(anotherConfig.headers().get("value")).containsExactly("foobar");
}
@Test
public void settingCollection_shouldOverrideAddItem() {
ClientOverrideConfiguration configuration = ClientOverrideConfiguration.builder()
.putHeader("value", "foo")
.headers(ImmutableMap.of("value",
Arrays.asList
("hello",
"world")))
.putAdvancedOption(SdkAdvancedClientOption
.USER_AGENT_SUFFIX, "test")
.advancedOptions(new HashMap<>())
.putAdvancedOption(SdkAdvancedClientOption
.USER_AGENT_PREFIX, "test")
.addExecutionInterceptor(new SlowExecutionInterceptor())
.executionInterceptors(new ArrayList<>())
.build();
assertThat(configuration.headers().get("value")).containsExactly("hello", "world");
assertFalse(configuration.advancedOption(SdkAdvancedClientOption.USER_AGENT_SUFFIX).isPresent());
assertThat(configuration.advancedOption(SdkAdvancedClientOption.USER_AGENT_PREFIX).get()).isEqualTo("test");
assertTrue(configuration.executionInterceptors().isEmpty());
}
@Test
public void addSameItemAfterSetCollection_shouldOverride() {
ImmutableMap<String, List<String>> map =
ImmutableMap.of("value", Arrays.asList("hello", "world"));
ClientOverrideConfiguration configuration = ClientOverrideConfiguration.builder()
.headers(map)
.putHeader("value", "blah")
.build();
assertThat(configuration.headers().get("value")).containsExactly("blah");
}
@Test
public void shouldGuaranteeImmutability() {
List<String> headerValues = new ArrayList<>();
headerValues.add("bar");
Map<String, List<String>> headers = new HashMap<>();
headers.put("foo", headerValues);
List<ExecutionInterceptor> executionInterceptors = new ArrayList<>();
SlowExecutionInterceptor slowExecutionInterceptor = new SlowExecutionInterceptor();
executionInterceptors.add(slowExecutionInterceptor);
ClientOverrideConfiguration.Builder configurationBuilder =
ClientOverrideConfiguration.builder().executionInterceptors(executionInterceptors)
.headers(headers);
headerValues.add("test");
headers.put("new header", Collections.singletonList("new value"));
executionInterceptors.clear();
assertThat(configurationBuilder.headers().size()).isEqualTo(1);
assertThat(configurationBuilder.headers().get("foo")).containsExactly("bar");
assertThat(configurationBuilder.executionInterceptors()).containsExactly(slowExecutionInterceptor);
}
@Test
public void metricPublishers_createsCopy() {
List<MetricPublisher> publishers = new ArrayList<>();
publishers.add(mock(MetricPublisher.class));
List<MetricPublisher> toModify = new ArrayList<>(publishers);
ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
.metricPublishers(toModify)
.build();
toModify.clear();
assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers);
}
@Test
public void addMetricPublisher_maintainsAllAdded() {
List<MetricPublisher> publishers = new ArrayList<>();
publishers.add(mock(MetricPublisher.class));
publishers.add(mock(MetricPublisher.class));
publishers.add(mock(MetricPublisher.class));
ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder();
publishers.forEach(builder::addMetricPublisher);
ClientOverrideConfiguration overrideConfig = builder.build();
assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers);
}
@Test
public void metricPublishers_overwritesPreviouslyAdded() {
MetricPublisher firstAdded = mock(MetricPublisher.class);
List<MetricPublisher> publishers = new ArrayList<>();
publishers.add(mock(MetricPublisher.class));
publishers.add(mock(MetricPublisher.class));
ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder();
builder.addMetricPublisher(firstAdded);
builder.metricPublishers(publishers);
ClientOverrideConfiguration overrideConfig = builder.build();
assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers);
}
@Test
public void addMetricPublisher_listPreviouslyAdded_appendedToList() {
List<MetricPublisher> publishers = new ArrayList<>();
publishers.add(mock(MetricPublisher.class));
publishers.add(mock(MetricPublisher.class));
MetricPublisher thirdAdded = mock(MetricPublisher.class);
ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder();
builder.metricPublishers(publishers);
builder.addMetricPublisher(thirdAdded);
ClientOverrideConfiguration overrideConfig = builder.build();
assertThat(overrideConfig.metricPublishers()).containsExactly(publishers.get(0), publishers.get(1), thirdAdded);
}
@Test
public void executionAttributes_createsCopy() {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
ExecutionAttribute testAttribute = attr("TestAttribute");
String expectedValue = "Value1";
executionAttributes.putAttribute(testAttribute, expectedValue);
ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
.executionAttributes(executionAttributes)
.build();
executionAttributes.putAttribute(testAttribute, "Value2");
assertThat(overrideConfig.executionAttributes().getAttribute(testAttribute)).isEqualTo(expectedValue);
}
@Test
public void executionAttributes_isImmutable() {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
ExecutionAttribute testAttribute = attr("TestAttribute");
String expectedValue = "Value1";
executionAttributes.putAttribute(testAttribute, expectedValue);
ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
.executionAttributes(executionAttributes)
.build();
try {
overrideConfig.executionAttributes().putAttribute(testAttribute, 2);
fail("Expected unsupported operation exception");
} catch(Exception ex) {
assertThat(ex instanceof UnsupportedOperationException).isTrue();
}
}
@Test
public void executionAttributes_maintainsAllAdded() {
Map<ExecutionAttribute, Object> executionAttributeObjectMap = new HashMap<>();
for (int i = 0; i < 5; i++) {
executionAttributeObjectMap.put(attr("Attribute" + i), mock(Object.class));
}
ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder();
for (Map.Entry<ExecutionAttribute, Object> attributeObjectEntry : executionAttributeObjectMap.entrySet()) {
builder.putExecutionAttribute(attributeObjectEntry.getKey(), attributeObjectEntry.getValue());
}
ClientOverrideConfiguration overrideConfig = builder.build();
assertThat(overrideConfig.executionAttributes().getAttributes()).isEqualTo(executionAttributeObjectMap);
}
@Test
public void executionAttributes_overwritesPreviouslyAdded() {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
for (int i = 0; i < 5; i++) {
executionAttributes.putAttribute(attr("Attribute" + i), mock(Object.class));
}
ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder();
builder.putExecutionAttribute(attr("AddedAttribute"), mock(Object.class));
builder.executionAttributes(executionAttributes);
ClientOverrideConfiguration overrideConfig = builder.build();
assertThat(overrideConfig.executionAttributes().getAttributes()).isEqualTo(executionAttributes.getAttributes());
}
@Test
public void executionAttributes_listPreviouslyAdded_appendedToList() {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
for (int i = 0; i < 5; i++) {
executionAttributes.putAttribute(attr("Attribute" + i), mock(Object.class));
}
ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder();
builder.executionAttributes(executionAttributes);
ExecutionAttribute addedAttribute = attr("AddedAttribute");
Object addedValue = mock(Object.class);
builder.putExecutionAttribute(addedAttribute, addedValue);
ClientOverrideConfiguration overrideConfig = builder.build();
assertThat(overrideConfig.executionAttributes().getAttribute(addedAttribute)).isEqualTo(addedValue);
}
}
| 2,026 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/config/SdkClientConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.client.config;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ClientType;
import software.amazon.awssdk.utils.AttributeMap;
public class SdkClientConfigurationTest {
@Test
public void equalsHashcode() {
AttributeMap one = AttributeMap.empty();
AttributeMap two = AttributeMap.builder().put(SdkClientOption.CLIENT_TYPE, ClientType.SYNC).build();
EqualsVerifier.forClass(SdkClientConfiguration.class)
.withNonnullFields("attributes")
.withPrefabValues(AttributeMap.class, one, two)
.verify();
}
}
| 2,027 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/config/ConfigurationBuilderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.client.config;
import static java.util.stream.Collectors.toMap;
import static org.assertj.core.api.Assertions.assertThat;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;
/**
* Validate the functionality of the Client*Configuration classes
*/
public class ConfigurationBuilderTest {
@Test
public void overrideConfigurationClassHasExpectedMethods() throws Exception {
assertConfigurationClassIsValid(ClientOverrideConfiguration.class);
}
private void assertConfigurationClassIsValid(Class<?> configurationClass) throws Exception {
// Builders should be instantiable from the configuration class
Method createBuilderMethod = configurationClass.getMethod("builder");
Object builder = createBuilderMethod.invoke(null);
// Builders should implement the configuration class's builder interface
Class<?> builderInterface = Class.forName(configurationClass.getName() + "$Builder");
assertThat(builder).isInstanceOf(builderInterface);
Class<?> builderClass = builder.getClass();
Method[] builderMethods = builderClass.getDeclaredMethods();
// Builder's build methods should return the configuration object
Optional<Method> buildMethod = Arrays.stream(builderMethods).filter(m -> m.getName().equals("build")).findFirst();
assertThat(buildMethod).isPresent();
Object builtObject = buildMethod.get().invoke(builder);
assertThat(builtObject).isInstanceOf(configurationClass);
// Analyze the builder for compliance with the bean specification
BeanInfo builderBeanInfo = Introspector.getBeanInfo(builderClass);
Map<String, PropertyDescriptor> builderProperties = Arrays.stream(builderBeanInfo.getPropertyDescriptors())
.collect(toMap(PropertyDescriptor::getName, p -> p));
// Validate method names
for (Field field : configurationClass.getFields()) {
// Ignore generated fields (eg. by Jacoco)
if (field.isSynthetic()) {
continue;
}
String builderPropertyName = builderClass.getSimpleName() + "'s " + field.getName() + " property";
PropertyDescriptor builderProperty = builderProperties.get(field.getName());
// Builders should have a bean-style write method for each field
assertThat(builderProperty).as(builderPropertyName).isNotNull();
assertThat(builderProperty.getReadMethod()).as(builderPropertyName + "'s read method").isNull();
assertThat(builderProperty.getWriteMethod()).as(builderPropertyName + "'s write method").isNotNull();
// Builders should have a fluent write method for each field
Arrays.stream(builderMethods)
.filter(builderMethod -> matchesSignature(field.getName(), builderProperty, builderMethod))
.findAny()
.orElseThrow(() -> new AssertionError(builderClass + " can't write " + field.getName()));
}
}
private boolean matchesSignature(String methodName, PropertyDescriptor property, Method builderMethod) {
return builderMethod.getName().equals(methodName) &&
builderMethod.getParameters().length == 1 &&
builderMethod.getParameters()[0].getType().equals(property.getPropertyType());
}
}
| 2,028 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/builder/DefaultClientBuilderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.client.builder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION;
import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER;
import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.USER_AGENT_PREFIX;
import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.USER_AGENT_SUFFIX;
import static software.amazon.awssdk.core.client.config.SdkClientOption.ADDITIONAL_HTTP_HEADERS;
import static software.amazon.awssdk.core.client.config.SdkClientOption.API_CALL_ATTEMPT_TIMEOUT;
import static software.amazon.awssdk.core.client.config.SdkClientOption.API_CALL_TIMEOUT;
import static software.amazon.awssdk.core.client.config.SdkClientOption.ENDPOINT_OVERRIDDEN;
import static software.amazon.awssdk.core.client.config.SdkClientOption.EXECUTION_ATTRIBUTES;
import static software.amazon.awssdk.core.client.config.SdkClientOption.EXECUTION_INTERCEPTORS;
import static software.amazon.awssdk.core.client.config.SdkClientOption.METRIC_PUBLISHERS;
import static software.amazon.awssdk.core.client.config.SdkClientOption.PROFILE_FILE;
import static software.amazon.awssdk.core.client.config.SdkClientOption.PROFILE_FILE_SUPPLIER;
import static software.amazon.awssdk.core.client.config.SdkClientOption.PROFILE_NAME;
import static software.amazon.awssdk.core.client.config.SdkClientOption.RETRY_POLICY;
import static software.amazon.awssdk.core.client.config.SdkClientOption.SCHEDULED_EXECUTOR_SERVICE;
import static software.amazon.awssdk.core.internal.SdkInternalTestAdvancedClientOption.ENDPOINT_OVERRIDDEN_OVERRIDE;
import com.google.common.collect.ImmutableSet;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Supplier;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.signer.NoOpSigner;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.StringInputStream;
/**
* Validate the functionality of the {@link SdkDefaultClientBuilder}.
*/
@RunWith(MockitoJUnitRunner.class)
public class DefaultClientBuilderTest {
private static final AttributeMap MOCK_DEFAULTS = AttributeMap
.builder()
.put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(10))
.build();
private static final String ENDPOINT_PREFIX = "prefix";
private static final URI DEFAULT_ENDPOINT = URI.create("https://defaultendpoint.com");
private static final URI ENDPOINT = URI.create("https://example.com");
private static final NoOpSigner TEST_SIGNER = new NoOpSigner();
@Mock
private SdkHttpClient.Builder defaultHttpClientFactory;
@Mock
private SdkAsyncHttpClient.Builder defaultAsyncHttpClientFactory;
@Before
public void setup() {
when(defaultHttpClientFactory.buildWithDefaults(any())).thenReturn(mock(SdkHttpClient.class));
when(defaultAsyncHttpClientFactory.buildWithDefaults(any())).thenReturn(mock(SdkAsyncHttpClient.class));
}
@Test
public void overrideConfigurationIsNeverNull() {
ClientOverrideConfiguration config = testClientBuilder().overrideConfiguration();
assertThat(config).isNotNull();
config = testClientBuilder().overrideConfiguration((ClientOverrideConfiguration) null).overrideConfiguration();
assertThat(config).isNotNull();
}
@Test
public void overrideConfigurationReturnsSetValues() {
List<ExecutionInterceptor> interceptors = new ArrayList<>();
RetryPolicy retryPolicy = RetryPolicy.builder().build();
Map<String, List<String>> headers = new HashMap<>();
List<MetricPublisher> metricPublishers = new ArrayList<>();
ExecutionAttributes executionAttributes = new ExecutionAttributes();
Signer signer = (request, execAttributes) -> request;
String suffix = "suffix";
String prefix = "prefix";
Duration apiCallTimeout = Duration.ofMillis(42);
Duration apiCallAttemptTimeout = Duration.ofMillis(43);
ProfileFile profileFile = ProfileFile.builder()
.content(new StringInputStream(""))
.type(ProfileFile.Type.CONFIGURATION)
.build();
Supplier<ProfileFile> profileFileSupplier = () -> profileFile;
String profileName = "name";
ScheduledExecutorService scheduledExecutorService = mock(ScheduledExecutorService.class);
ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
.executionInterceptors(interceptors)
.retryPolicy(retryPolicy)
.headers(headers)
.putAdvancedOption(SIGNER, signer)
.putAdvancedOption(USER_AGENT_SUFFIX, suffix)
.putAdvancedOption(USER_AGENT_PREFIX, prefix)
.apiCallTimeout(apiCallTimeout)
.apiCallAttemptTimeout(apiCallAttemptTimeout)
.putAdvancedOption(DISABLE_HOST_PREFIX_INJECTION, Boolean.TRUE)
.defaultProfileFileSupplier(profileFileSupplier)
.defaultProfileName(profileName)
.metricPublishers(metricPublishers)
.executionAttributes(executionAttributes)
.putAdvancedOption(ENDPOINT_OVERRIDDEN_OVERRIDE, Boolean.TRUE)
.scheduledExecutorService(scheduledExecutorService)
.build();
TestClientBuilder builder = testClientBuilder().overrideConfiguration(overrideConfig);
ClientOverrideConfiguration builderOverrideConfig = builder.overrideConfiguration();
assertThat(builderOverrideConfig.executionInterceptors()).isEqualTo(interceptors);
assertThat(builderOverrideConfig.retryPolicy()).isEqualTo(Optional.of(retryPolicy));
assertThat(builderOverrideConfig.headers()).isEqualTo(headers);
assertThat(builderOverrideConfig.advancedOption(SIGNER)).isEqualTo(Optional.of(signer));
assertThat(builderOverrideConfig.advancedOption(USER_AGENT_SUFFIX)).isEqualTo(Optional.of(suffix));
assertThat(builderOverrideConfig.apiCallTimeout()).isEqualTo(Optional.of(apiCallTimeout));
assertThat(builderOverrideConfig.apiCallAttemptTimeout()).isEqualTo(Optional.of(apiCallAttemptTimeout));
assertThat(builderOverrideConfig.advancedOption(DISABLE_HOST_PREFIX_INJECTION)).isEqualTo(Optional.of(Boolean.TRUE));
assertThat(builderOverrideConfig.defaultProfileFileSupplier()).hasValue(profileFileSupplier);
assertThat(builderOverrideConfig.defaultProfileFile()).isEqualTo(Optional.of(profileFile));
assertThat(builderOverrideConfig.defaultProfileName()).isEqualTo(Optional.of(profileName));
assertThat(builderOverrideConfig.metricPublishers()).isEqualTo(metricPublishers);
assertThat(builderOverrideConfig.executionAttributes().getAttributes()).isEqualTo(executionAttributes.getAttributes());
assertThat(builderOverrideConfig.advancedOption(ENDPOINT_OVERRIDDEN_OVERRIDE)).isEqualTo(Optional.of(Boolean.TRUE));
Runnable runnable = () -> {
};
builderOverrideConfig.scheduledExecutorService().get().submit(runnable);
verify(scheduledExecutorService).submit(runnable);
}
@Test
public void overrideConfigurationOmitsUnsetValues() {
ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
.build();
TestClientBuilder builder = testClientBuilder().overrideConfiguration(overrideConfig);
ClientOverrideConfiguration builderOverrideConfig = builder.overrideConfiguration();
assertThat(builderOverrideConfig.executionInterceptors()).isEmpty();
assertThat(builderOverrideConfig.retryPolicy()).isEmpty();
assertThat(builderOverrideConfig.headers()).isEmpty();
assertThat(builderOverrideConfig.advancedOption(SIGNER)).isEmpty();
assertThat(builderOverrideConfig.advancedOption(USER_AGENT_SUFFIX)).isEmpty();
assertThat(builderOverrideConfig.apiCallTimeout()).isEmpty();
assertThat(builderOverrideConfig.apiCallAttemptTimeout()).isEmpty();
assertThat(builderOverrideConfig.advancedOption(DISABLE_HOST_PREFIX_INJECTION)).isEmpty();
assertThat(builderOverrideConfig.defaultProfileFileSupplier()).isEmpty();
assertThat(builderOverrideConfig.defaultProfileFile()).isEmpty();
assertThat(builderOverrideConfig.defaultProfileName()).isEmpty();
assertThat(builderOverrideConfig.metricPublishers()).isEmpty();
assertThat(builderOverrideConfig.executionAttributes().getAttributes()).isEmpty();
assertThat(builderOverrideConfig.advancedOption(ENDPOINT_OVERRIDDEN_OVERRIDE)).isEmpty();
assertThat(builderOverrideConfig.scheduledExecutorService()).isEmpty();
}
@Test
public void buildIncludesClientOverrides() {
List<ExecutionInterceptor> interceptors = new ArrayList<>();
ExecutionInterceptor interceptor = new ExecutionInterceptor() {};
interceptors.add(interceptor);
RetryPolicy retryPolicy = RetryPolicy.builder().build();
ScheduledExecutorService scheduledExecutorService = Mockito.spy(Executors.newScheduledThreadPool(1));
Map<String, List<String>> headers = new HashMap<>();
List<String> headerValues = new ArrayList<>();
headerValues.add("value");
headers.put("client-override-test", headerValues);
List<MetricPublisher> metricPublishers = new ArrayList<>();
MetricPublisher metricPublisher = new MetricPublisher() {
@Override
public void publish(MetricCollection metricCollection) {
}
@Override
public void close() {
}
};
metricPublishers.add(metricPublisher);
ExecutionAttribute<String> execAttribute = new ExecutionAttribute<>("test");
ExecutionAttributes executionAttributes = ExecutionAttributes.builder().put(execAttribute, "value").build();
Signer signer = (request, execAttributes) -> request;
String suffix = "suffix";
String prefix = "prefix";
Duration apiCallTimeout = Duration.ofMillis(42);
Duration apiCallAttemptTimeout = Duration.ofMillis(43);
ProfileFile profileFile = ProfileFile.builder()
.content(new StringInputStream(""))
.type(ProfileFile.Type.CONFIGURATION)
.build();
String profileName = "name";
ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
.executionInterceptors(interceptors)
.retryPolicy(retryPolicy)
.headers(headers)
.putAdvancedOption(SIGNER, signer)
.putAdvancedOption(USER_AGENT_SUFFIX, suffix)
.putAdvancedOption(USER_AGENT_PREFIX, prefix)
.apiCallTimeout(apiCallTimeout)
.apiCallAttemptTimeout(apiCallAttemptTimeout)
.putAdvancedOption(DISABLE_HOST_PREFIX_INJECTION, Boolean.TRUE)
.defaultProfileFile(profileFile)
.defaultProfileName(profileName)
.metricPublishers(metricPublishers)
.executionAttributes(executionAttributes)
.putAdvancedOption(ENDPOINT_OVERRIDDEN_OVERRIDE, Boolean.TRUE)
.scheduledExecutorService(scheduledExecutorService)
.build();
SdkClientConfiguration config =
testClientBuilder().overrideConfiguration(overrideConfig).build().clientConfiguration;
assertThat(config.option(EXECUTION_INTERCEPTORS)).contains(interceptor);
assertThat(config.option(RETRY_POLICY)).isEqualTo(retryPolicy);
assertThat(config.option(ADDITIONAL_HTTP_HEADERS).get("client-override-test")).isEqualTo(headerValues);
assertThat(config.option(SIGNER)).isEqualTo(signer);
assertThat(config.option(USER_AGENT_SUFFIX)).isEqualTo(suffix);
assertThat(config.option(USER_AGENT_PREFIX)).isEqualTo(prefix);
assertThat(config.option(API_CALL_TIMEOUT)).isEqualTo(apiCallTimeout);
assertThat(config.option(API_CALL_ATTEMPT_TIMEOUT)).isEqualTo(apiCallAttemptTimeout);
assertThat(config.option(DISABLE_HOST_PREFIX_INJECTION)).isEqualTo(Boolean.TRUE);
assertThat(config.option(PROFILE_FILE)).isEqualTo(profileFile);
assertThat(config.option(PROFILE_FILE_SUPPLIER).get()).isEqualTo(profileFile);
assertThat(config.option(PROFILE_NAME)).isEqualTo(profileName);
assertThat(config.option(METRIC_PUBLISHERS)).contains(metricPublisher);
assertThat(config.option(EXECUTION_ATTRIBUTES).getAttribute(execAttribute)).isEqualTo("value");
assertThat(config.option(ENDPOINT_OVERRIDDEN)).isEqualTo(Boolean.TRUE);
// Ensure that the SDK won't close the scheduled executor service we provided.
config.close();
config.option(SCHEDULED_EXECUTOR_SERVICE).shutdownNow();
config.option(SCHEDULED_EXECUTOR_SERVICE).shutdown();
Mockito.verify(scheduledExecutorService, never()).shutdown();
Mockito.verify(scheduledExecutorService, never()).shutdownNow();
}
@Test
public void buildIncludesServiceDefaults() {
TestClient client = testClientBuilder().build();
assertThat(client.clientConfiguration.option(SIGNER))
.isEqualTo(TEST_SIGNER);
}
@Test
public void buildWithEndpointShouldHaveCorrectEndpointAndSigningRegion() {
TestClient client = testClientBuilder().endpointOverride(ENDPOINT).build();
assertThat(client.clientConfiguration.option(SdkClientOption.ENDPOINT)).isEqualTo(ENDPOINT);
}
@Test
public void buildWithEndpointWithoutScheme_shouldThrowException() {
assertThatThrownBy(() -> testClientBuilder().endpointOverride(URI.create("localhost")).build())
.hasMessageContaining("The URI scheme of endpointOverride must not be null");
}
@Test
public void noClientProvided_DefaultHttpClientIsManagedBySdk() {
TestClient client = testClientBuilder().build();
assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT))
.isNotInstanceOf(SdkDefaultClientBuilder.NonManagedSdkHttpClient.class);
verify(defaultHttpClientFactory, times(1)).buildWithDefaults(any());
}
@Test
public void noAsyncClientProvided_DefaultAsyncHttpClientIsManagedBySdk() {
TestAsyncClient client = testAsyncClientBuilder().build();
assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT))
.isNotInstanceOf(SdkDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class);
verify(defaultAsyncHttpClientFactory, times(1)).buildWithDefaults(any());
}
@Test
public void clientFactoryProvided_ClientIsManagedBySdk() {
TestClient client = testClientBuilder().httpClientBuilder((SdkHttpClient.Builder) serviceDefaults -> {
Assertions.assertThat(serviceDefaults).isEqualTo(MOCK_DEFAULTS);
return mock(SdkHttpClient.class);
})
.build();
assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT))
.isNotInstanceOf(SdkDefaultClientBuilder.NonManagedSdkHttpClient.class);
verify(defaultHttpClientFactory, never()).buildWithDefaults(any());
}
@Test
public void asyncHttpClientFactoryProvided_ClientIsManagedBySdk() {
TestAsyncClient client = testAsyncClientBuilder()
.httpClientBuilder((SdkAsyncHttpClient.Builder) serviceDefaults -> {
assertThat(serviceDefaults).isEqualTo(MOCK_DEFAULTS);
return mock(SdkAsyncHttpClient.class);
})
.build();
assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT))
.isNotInstanceOf(SdkDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class);
verify(defaultAsyncHttpClientFactory, never()).buildWithDefaults(any());
}
@Test
public void explicitClientProvided_ClientIsNotManagedBySdk() {
TestClient client = testClientBuilder()
.httpClient(mock(SdkHttpClient.class))
.build();
assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT))
.isInstanceOf(SdkDefaultClientBuilder.NonManagedSdkHttpClient.class);
verify(defaultHttpClientFactory, never()).buildWithDefaults(any());
}
@Test
public void explicitAsyncHttpClientProvided_ClientIsNotManagedBySdk() {
TestAsyncClient client = testAsyncClientBuilder()
.httpClient(mock(SdkAsyncHttpClient.class))
.build();
assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT))
.isInstanceOf(SdkDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class);
verify(defaultAsyncHttpClientFactory, never()).buildWithDefaults(any());
}
@Test
public void clientBuilderFieldsHaveBeanEquivalents() throws Exception {
// Mutating properties might not have bean equivalents. This is probably fine, since very few customers require
// bean-equivalent methods and it's not clear what they'd expect them to be named anyway. Ignore these methods for now.
Set<String> NON_BEAN_EQUIVALENT_METHODS = ImmutableSet.of("addPlugin", "plugins", "putAuthScheme");
SdkClientBuilder<TestClientBuilder, TestClient> builder = testClientBuilder();
BeanInfo beanInfo = Introspector.getBeanInfo(builder.getClass());
Method[] clientBuilderMethods = SdkClientBuilder.class.getDeclaredMethods();
Arrays.stream(clientBuilderMethods).filter(m -> !m.isSynthetic()).forEach(builderMethod -> {
String propertyName = builderMethod.getName();
if (NON_BEAN_EQUIVALENT_METHODS.contains(propertyName)) {
return;
}
Optional<PropertyDescriptor> propertyForMethod =
Arrays.stream(beanInfo.getPropertyDescriptors())
.filter(property -> property.getName().equals(propertyName))
.findFirst();
assertThat(propertyForMethod).as(propertyName + " property").hasValueSatisfying(property -> {
assertThat(property.getReadMethod()).as(propertyName + " getter").isNull();
assertThat(property.getWriteMethod()).as(propertyName + " setter").isNotNull();
});
});
}
@Test
public void defaultProfileFileSupplier_isStaticOrHasIdentityCaching() {
SdkClientConfiguration config =
testClientBuilder().build().clientConfiguration;
Supplier<ProfileFile> defaultProfileFileSupplier = config.option(PROFILE_FILE_SUPPLIER);
ProfileFile firstGet = defaultProfileFileSupplier.get();
ProfileFile secondGet = defaultProfileFileSupplier.get();
assertThat(secondGet).isSameAs(firstGet);
}
private SdkDefaultClientBuilder<TestClientBuilder, TestClient> testClientBuilder() {
ClientOverrideConfiguration overrideConfig =
ClientOverrideConfiguration.builder()
.putAdvancedOption(SIGNER, TEST_SIGNER)
.build();
return new TestClientBuilder().overrideConfiguration(overrideConfig);
}
private SdkDefaultClientBuilder<TestAsyncClientBuilder, TestAsyncClient> testAsyncClientBuilder() {
ClientOverrideConfiguration overrideConfig =
ClientOverrideConfiguration.builder()
.putAdvancedOption(SIGNER, TEST_SIGNER)
.build();
return new TestAsyncClientBuilder().overrideConfiguration(overrideConfig);
}
private static class TestClient {
private final SdkClientConfiguration clientConfiguration;
private TestClient(SdkClientConfiguration clientConfiguration) {
this.clientConfiguration = clientConfiguration;
}
}
private class TestClientWithoutEndpointDefaultBuilder extends SdkDefaultClientBuilder<TestClientBuilder, TestClient>
implements SdkClientBuilder<TestClientBuilder, TestClient> {
public TestClientWithoutEndpointDefaultBuilder() {
super(defaultHttpClientFactory, null);
}
@Override
protected TestClient buildClient() {
return new TestClient(super.syncClientConfiguration());
}
@Override
protected SdkClientConfiguration mergeChildDefaults(SdkClientConfiguration configuration) {
return configuration.merge(c -> c.option(SdkAdvancedClientOption.SIGNER, TEST_SIGNER));
}
@Override
protected AttributeMap childHttpConfig() {
return MOCK_DEFAULTS;
}
}
private class TestClientBuilder extends SdkDefaultClientBuilder<TestClientBuilder, TestClient>
implements SdkClientBuilder<TestClientBuilder, TestClient> {
public TestClientBuilder() {
super(defaultHttpClientFactory, null);
}
@Override
protected TestClient buildClient() {
return new TestClient(super.syncClientConfiguration());
}
@Override
protected SdkClientConfiguration mergeChildDefaults(SdkClientConfiguration configuration) {
return configuration.merge(c -> c.option(SdkClientOption.ENDPOINT, DEFAULT_ENDPOINT));
}
@Override
protected AttributeMap childHttpConfig() {
return MOCK_DEFAULTS;
}
}
private static class TestAsyncClient {
private final SdkClientConfiguration clientConfiguration;
private TestAsyncClient(SdkClientConfiguration clientConfiguration) {
this.clientConfiguration = clientConfiguration;
}
}
private class TestAsyncClientBuilder extends SdkDefaultClientBuilder<TestAsyncClientBuilder, TestAsyncClient>
implements SdkClientBuilder<TestAsyncClientBuilder, TestAsyncClient> {
public TestAsyncClientBuilder() {
super(defaultHttpClientFactory, defaultAsyncHttpClientFactory);
}
@Override
protected TestAsyncClient buildClient() {
return new TestAsyncClient(super.asyncClientConfiguration());
}
@Override
protected SdkClientConfiguration mergeChildDefaults(SdkClientConfiguration configuration) {
return configuration.merge(c -> c.option(SdkClientOption.ENDPOINT, DEFAULT_ENDPOINT));
}
@Override
protected AttributeMap childHttpConfig() {
return MOCK_DEFAULTS;
}
}
}
| 2,029 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/interceptor/ExecutionAttributesTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.interceptor;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
public class ExecutionAttributesTest {
private static final ExecutionAttribute<String> ATTR_1 = new ExecutionAttribute<>("Attr1");
private static final ExecutionAttribute<String> ATTR_2 = new ExecutionAttribute<>("Attr2");
@Test
public void equals_identity_returnsTrue() {
ExecutionAttributes executionAttributes = ExecutionAttributes.builder()
.put(ATTR_1, "hello")
.put(ATTR_2, "world")
.build();
assertThat(executionAttributes.equals(executionAttributes)).isTrue();
}
@Test
public void equals_sameAttributes_returnsTrue() {
ExecutionAttributes executionAttributes1 = ExecutionAttributes.builder()
.put(ATTR_1, "hello")
.put(ATTR_2, "world")
.build();
ExecutionAttributes executionAttributes2 = ExecutionAttributes.builder()
.put(ATTR_1, "hello")
.put(ATTR_2, "world")
.build();
assertThat(executionAttributes1).isEqualTo(executionAttributes2);
assertThat(executionAttributes2).isEqualTo(executionAttributes1);
}
@Test
public void equals_differentAttributes_returnsFalse() {
ExecutionAttributes executionAttributes1 = ExecutionAttributes.builder()
.put(ATTR_1, "HELLO")
.put(ATTR_2, "WORLD")
.build();
ExecutionAttributes executionAttributes2 = ExecutionAttributes.builder()
.put(ATTR_1, "hello")
.put(ATTR_2, "world")
.build();
assertThat(executionAttributes1).isNotEqualTo(executionAttributes2);
assertThat(executionAttributes2).isNotEqualTo(executionAttributes1);
}
@Test
public void hashCode_objectsEqual_valuesEqual() {
ExecutionAttributes executionAttributes1 = ExecutionAttributes.builder()
.put(ATTR_1, "hello")
.put(ATTR_2, "world")
.build();
ExecutionAttributes executionAttributes2 = ExecutionAttributes.builder()
.put(ATTR_1, "hello")
.put(ATTR_2, "world")
.build();
assertThat(executionAttributes1.hashCode()).isEqualTo(executionAttributes2.hashCode());
}
}
| 2,030 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/interceptor/ExecutionAttributeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.interceptor;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class ExecutionAttributeTest {
@Test
@DisplayName("Ensure that two different ExecutionAttributes are not allowed to have the same name (and hash key)")
void testUniqueness() {
String name = "ExecutionAttributeTest";
ExecutionAttribute<Integer> first = new ExecutionAttribute<>(name);
assertThatThrownBy(() -> {
ExecutionAttribute<Integer> second = new ExecutionAttribute<>(name);
}).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(name);
}
} | 2,031 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core/http/AmazonHttpClientSslHandshakeTimeoutTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.executionContext;
import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler;
import java.io.IOException;
import java.time.Duration;
import org.junit.Test;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient;
import software.amazon.awssdk.core.internal.http.response.NullErrorResponseHandler;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import utils.HttpTestUtils;
/**
* This test is to verify that the apache-httpclient library has fixed the bug where socket timeout configuration is
* incorrectly ignored during SSL handshake. This test is expected to hang (and fail after the junit timeout) if run
* against the problematic httpclient version (e.g. 4.3).
*
* @link https://issues.apache.org/jira/browse/HTTPCLIENT-1478
*/
public class AmazonHttpClientSslHandshakeTimeoutTest extends UnresponsiveMockServerTestBase {
private static final Duration CLIENT_SOCKET_TO = Duration.ofSeconds(1);
@Test(timeout = 60 * 1000)
public void testSslHandshakeTimeout() {
AmazonSyncHttpClient httpClient = HttpTestUtils.testClientBuilder()
.retryPolicy(RetryPolicy.none())
.httpClient(ApacheHttpClient.builder()
.socketTimeout(CLIENT_SOCKET_TO)
.build())
.build();
System.out.println("Sending request to localhost...");
try {
SdkHttpFullRequest request = server.configureHttpsEndpoint(SdkHttpFullRequest.builder())
.method(SdkHttpMethod.GET)
.build();
httpClient.requestExecutionBuilder()
.request(request)
.originalRequest(NoopTestRequest.builder().build())
.executionContext(executionContext(request))
.execute(combinedSyncResponseHandler(null, new NullErrorResponseHandler()));
fail("Client-side socket read timeout is expected!");
} catch (SdkClientException e) {
e.printStackTrace();
/**
* Http client catches the SocketTimeoutException and throws a
* ConnectTimeoutException.
* {@link DefaultHttpClientConnectionOperator#connect(ManagedHttpClientConnection, HttpHost,
* InetSocketAddress, int, SocketConfig, HttpContext)}
*/
assertThat(e).hasCauseInstanceOf(IOException.class);
}
}
}
| 2,032 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core/http/ConnectionPoolMaxConnectionsIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http;
import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.executionContext;
import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler;
import java.time.Duration;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.http.server.MockServer;
import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient;
import software.amazon.awssdk.core.internal.http.response.EmptySdkResponseHandler;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import utils.HttpTestUtils;
public class ConnectionPoolMaxConnectionsIntegrationTest {
private static MockServer server;
@BeforeClass
public static void setup() {
server = MockServer.createMockServer(MockServer.ServerBehavior.OVERLOADED);
server.startServer();
}
@AfterClass
public static void tearDown() {
if (server != null) {
server.stopServer();
}
}
@Test(timeout = 60 * 1000)
public void leasing_a_new_connection_fails_with_connection_pool_timeout() {
AmazonSyncHttpClient httpClient = HttpTestUtils.testClientBuilder()
.retryPolicy(RetryPolicy.none())
.httpClient(ApacheHttpClient.builder()
.connectionTimeout(Duration.ofMillis(100))
.maxConnections(1)
.build())
.build();
SdkHttpFullRequest request = server.configureHttpEndpoint(SdkHttpFullRequest.builder())
.method(SdkHttpMethod.GET)
.build();
// Block the first connection in the pool with this request.
httpClient.requestExecutionBuilder()
.request(request)
.originalRequest(NoopTestRequest.builder().build())
.executionContext(executionContext(request))
.execute(combinedSyncResponseHandler(new EmptySdkResponseHandler(), null));
try {
// A new connection will be leased here which would fail in
// ConnectionPoolTimeoutException.
httpClient.requestExecutionBuilder()
.request(request)
.originalRequest(NoopTestRequest.builder().build())
.executionContext(executionContext(request))
.execute(combinedSyncResponseHandler(null, null));
Assert.fail("Connection pool timeout exception is expected!");
} catch (SdkClientException e) {
Assert.assertTrue(e.getCause() instanceof ConnectionPoolTimeoutException);
}
}
}
| 2,033 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core/http/timers | Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core/http/timers/client/AbortedExceptionClientExecutionTimerIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.http.timers.client;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.createMockGetRequest;
import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.execute;
import java.time.Duration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.exception.AbortedException;
import software.amazon.awssdk.core.exception.ApiCallTimeoutException;
import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpResponse;
import utils.HttpTestUtils;
@RunWith(MockitoJUnitRunner.class)
public class AbortedExceptionClientExecutionTimerIntegrationTest {
private AmazonSyncHttpClient httpClient;
@Mock
private SdkHttpClient sdkHttpClient;
@Mock
private ExecutableHttpRequest abortableCallable;
@Before
public void setup() throws Exception {
when(sdkHttpClient.prepareRequest(any())).thenReturn(abortableCallable);
httpClient = HttpTestUtils.testClientBuilder().httpClient(sdkHttpClient)
.apiCallTimeout(Duration.ofMillis(1000))
.build();
when(abortableCallable.call()).thenReturn(HttpExecuteResponse.builder().response(SdkHttpResponse.builder()
.statusCode(200)
.build())
.build());
}
@Test(expected = AbortedException.class)
public void clientExecutionTimeoutEnabled_aborted_exception_occurs_timeout_not_expired() throws Exception {
when(abortableCallable.call()).thenThrow(AbortedException.builder().build());
execute(httpClient, createMockGetRequest().build());
}
@Test(expected = ApiCallTimeoutException.class)
public void clientExecutionTimeoutEnabled_aborted_exception_occurs_timeout_expired() throws Exception {
// Simulate a slow HTTP request
when(abortableCallable.call()).thenAnswer(i -> {
Thread.sleep(10_000);
return null;
});
execute(httpClient, createMockGetRequest().build());
}
}
| 2,034 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/FileRequestBodyConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.nio.file.Path;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Configuration options for {@link AsyncRequestBody#fromFile(FileRequestBodyConfiguration)} to configure how the SDK
* should read the file.
*
* @see #builder()
*/
@SdkPublicApi
public final class FileRequestBodyConfiguration implements ToCopyableBuilder<FileRequestBodyConfiguration.Builder,
FileRequestBodyConfiguration> {
private final Integer chunkSizeInBytes;
private final Long position;
private final Long numBytesToRead;
private final Path path;
private FileRequestBodyConfiguration(DefaultBuilder builder) {
this.path = Validate.notNull(builder.path, "path");
this.chunkSizeInBytes = Validate.isPositiveOrNull(builder.chunkSizeInBytes, "chunkSizeInBytes");
this.position = Validate.isNotNegativeOrNull(builder.position, "position");
this.numBytesToRead = Validate.isNotNegativeOrNull(builder.numBytesToRead, "numBytesToRead");
}
/**
* Create a {@link Builder}, used to create a {@link FileRequestBodyConfiguration}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
/**
* @return the size of each chunk to read from the file
*/
public Integer chunkSizeInBytes() {
return chunkSizeInBytes;
}
/**
* @return the file position at which the request body begins.
*/
public Long position() {
return position;
}
/**
* @return the number of bytes to read from this file.
*/
public Long numBytesToRead() {
return numBytesToRead;
}
/**
* @return the file path
*/
public Path path() {
return path;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FileRequestBodyConfiguration that = (FileRequestBodyConfiguration) o;
if (!Objects.equals(chunkSizeInBytes, that.chunkSizeInBytes)) {
return false;
}
if (!Objects.equals(position, that.position)) {
return false;
}
if (!Objects.equals(numBytesToRead, that.numBytesToRead)) {
return false;
}
return Objects.equals(path, that.path);
}
@Override
public int hashCode() {
int result = chunkSizeInBytes != null ? chunkSizeInBytes.hashCode() : 0;
result = 31 * result + (position != null ? position.hashCode() : 0);
result = 31 * result + (numBytesToRead != null ? numBytesToRead.hashCode() : 0);
result = 31 * result + (path != null ? path.hashCode() : 0);
return result;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<Builder, FileRequestBodyConfiguration> {
/**
* Sets the {@link Path} to the file containing data to send to the service
*
* @param path Path to file to read.
* @return This builder for method chaining.
*/
Builder path(Path path);
/**
* Sets the size of chunks read from the file. Increasing this will cause more data to be buffered into memory but
* may yield better latencies. Decreasing this will reduce memory usage but may cause reduced latency. Setting this value
* is very dependent on upload speed and requires some performance testing to tune.
*
* <p>The default chunk size is 16 KiB</p>
*
* @param chunkSize New chunk size in bytes.
* @return This builder for method chaining.
*/
Builder chunkSizeInBytes(Integer chunkSize);
/**
* Sets the file position at which the request body begins.
*
* <p>By default, it's 0, i.e., reading from the beginning.
*
* @param position the position of the file
* @return The builder for method chaining.
*/
Builder position(Long position);
/**
* Sets the number of bytes to read from this file.
*
* <p>By default, it's same as the file length.
*
* @param numBytesToRead number of bytes to read
* @return The builder for method chaining.
*/
Builder numBytesToRead(Long numBytesToRead);
}
private static final class DefaultBuilder implements Builder {
private Long position;
private Path path;
private Integer chunkSizeInBytes;
private Long numBytesToRead;
private DefaultBuilder(FileRequestBodyConfiguration configuration) {
this.position = configuration.position;
this.path = configuration.path;
this.chunkSizeInBytes = configuration.chunkSizeInBytes;
this.numBytesToRead = configuration.numBytesToRead;
}
private DefaultBuilder() {
}
@Override
public Builder path(Path path) {
this.path = path;
return this;
}
@Override
public Builder chunkSizeInBytes(Integer chunkSizeInBytes) {
this.chunkSizeInBytes = chunkSizeInBytes;
return this;
}
@Override
public Builder position(Long position) {
this.position = position;
return this;
}
@Override
public Builder numBytesToRead(Long numBytesToRead) {
this.numBytesToRead = numBytesToRead;
return this;
}
@Override
public FileRequestBodyConfiguration build() {
return new FileRequestBodyConfiguration(this);
}
}
} | 2,035 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/ResponseInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.io.InputStream;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.io.SdkFilterInputStream;
import software.amazon.awssdk.http.Abortable;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.utils.Validate;
/**
* Input stream that provides access to the unmarshalled POJO response returned by the service in addition to the streamed
* contents. This input stream should be closed to release the underlying connection back to the connection pool.
*
* <p>
* If it is not desired to read remaining data from the stream, you can explicitly abort the connection via {@link #abort()}.
* Note that this will close the underlying connection and require establishing an HTTP connection which may outweigh the
* cost of reading the additional data.
* </p>
*/
@SdkPublicApi
public final class ResponseInputStream<ResponseT> extends SdkFilterInputStream implements Abortable {
private final ResponseT response;
private final Abortable abortable;
public ResponseInputStream(ResponseT resp, AbortableInputStream in) {
super(in);
this.response = Validate.paramNotNull(resp, "response");
this.abortable = Validate.paramNotNull(in, "abortableInputStream");
}
public ResponseInputStream(ResponseT resp, InputStream in) {
super(in);
this.response = Validate.paramNotNull(resp, "response");
this.abortable = in instanceof Abortable ? (Abortable) in : null;
}
/**
* @return The unmarshalled POJO response associated with this content.
*/
public ResponseT response() {
return response;
}
@Override
public void abort() {
if (abortable != null) {
abortable.abort();
}
}
}
| 2,036 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/Response.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.http.SdkHttpFullResponse;
/**
* Response wrapper that indicates success or failure with the associated unmarshalled response object or exception
* object. This object is used by the core request/response pipeline to pass response metadata alongside the actual
* deserialized response object through different stages of the pipeline.
*
* @param <T> the modelled SDK response type.
*/
@SdkProtectedApi
public final class Response<T> {
private final Boolean isSuccess;
private final T response;
private final SdkException exception;
private final SdkHttpFullResponse httpResponse;
private Response(Builder<T> builder) {
this.isSuccess = builder.isSuccess;
this.response = builder.response;
this.exception = builder.exception;
this.httpResponse = builder.httpResponse;
}
/**
* Returns a newly initialized builder object for a {@link Response}
* @param <T> Modelled response type.
*/
public static <T> Builder<T> builder() {
return new Builder<>();
}
/**
* Creates a new builder with initial values pulled from the current object.
*/
public Builder<T> toBuilder() {
return new Builder<T>().isSuccess(this.isSuccess)
.response(this.response)
.exception(this.exception)
.httpResponse(this.httpResponse);
}
/**
* The modelled response object returned by the service. If the response was a failure, this value is likely to
* be null.
*/
public T response() {
return response;
}
/**
* The modelled exception returned by the service. If the response was not a failure, this value is likely to
* be null.
*/
public SdkException exception() {
return exception;
}
/**
* The HTTP response that was received by the SDK prior to determining the result.
*/
public SdkHttpFullResponse httpResponse() {
return httpResponse;
}
/**
* Indicates whether the result indicates success or failure of the original request. A true value indicates
* success; a false value indicates failure.
*/
public Boolean isSuccess() {
return isSuccess;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Response<?> response1 = (Response<?>) o;
if (isSuccess != null ? ! isSuccess.equals(response1.isSuccess) : response1.isSuccess != null) {
return false;
}
if (response != null ? ! response.equals(response1.response) : response1.response != null) {
return false;
}
if (exception != null ? ! exception.equals(response1.exception) : response1.exception != null) {
return false;
}
return httpResponse != null ? httpResponse.equals(response1.httpResponse) : response1.httpResponse == null;
}
@Override
public int hashCode() {
int result = isSuccess != null ? isSuccess.hashCode() : 0;
result = 31 * result + (response != null ? response.hashCode() : 0);
result = 31 * result + (exception != null ? exception.hashCode() : 0);
result = 31 * result + (httpResponse != null ? httpResponse.hashCode() : 0);
return result;
}
public static final class Builder<T> {
private Boolean isSuccess;
private T response;
private SdkException exception;
private SdkHttpFullResponse httpResponse;
private Builder() {
}
/**
* Indicates whether the result indicates success or failure of the original request. A true value indicates
* success; a false value indicates failure.
*/
public Builder<T> isSuccess(Boolean success) {
isSuccess = success;
return this;
}
/**
* The modelled response object returned by the service. If the response was a failure, this value is likely to
* be null.
*/
public Builder<T> response(T response) {
this.response = response;
return this;
}
/**
* The modelled exception returned by the service. If the response was not a failure, this value is likely to
* be null.
*/
public Builder<T> exception(SdkException exception) {
this.exception = exception;
return this;
}
/**
* The HTTP response that was received by the SDK prior to determining the result.
*/
public Builder<T> httpResponse(SdkHttpFullResponse httpResponse) {
this.httpResponse = httpResponse;
return this;
}
/**
* Builds a {@link Response} object based on the values held by this builder.
*/
public Response<T> build() {
return new Response<>(this);
}
}
}
| 2,037 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkSystemSetting.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.utils.SystemSetting;
/**
* System properties to configure the SDK runtime.
*/
@SdkProtectedApi
public enum SdkSystemSetting implements SystemSetting {
/**
* Configure the AWS access key ID.
*
* This value will not be ignored if the {@link #AWS_SECRET_ACCESS_KEY} is not specified.
*/
AWS_ACCESS_KEY_ID("aws.accessKeyId", null),
/**
* Configure the AWS secret access key.
*
* This value will not be ignored if the {@link #AWS_ACCESS_KEY_ID} is not specified.
*/
AWS_SECRET_ACCESS_KEY("aws.secretAccessKey", null),
/**
* Configure the AWS session token.
*/
AWS_SESSION_TOKEN("aws.sessionToken", null),
/**
* Configure the AWS web identity token file path.
*/
AWS_WEB_IDENTITY_TOKEN_FILE("aws.webIdentityTokenFile", null),
/**
* Configure the AWS role arn.
*/
AWS_ROLE_ARN("aws.roleArn", null),
/**
* Configure the session name for a role.
*/
AWS_ROLE_SESSION_NAME("aws.roleSessionName", null),
/**
* Configure the default region.
*/
AWS_REGION("aws.region", null),
/**
* Whether to load information such as credentials, regions from EC2 Metadata instance service.
*/
AWS_EC2_METADATA_DISABLED("aws.disableEc2Metadata", "false"),
/**
* The EC2 instance metadata service endpoint.
*
* This allows a service running in EC2 to automatically load its credentials and region without needing to configure them
* in the SdkClientBuilder.
*/
AWS_EC2_METADATA_SERVICE_ENDPOINT("aws.ec2MetadataServiceEndpoint", "http://169.254.169.254"),
AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE("aws.ec2MetadataServiceEndpointMode", "IPv4"),
/**
* The elastic container metadata service endpoint that should be called by the ContainerCredentialsProvider
* when loading data from the container metadata service.
*
* This allows a service running in an elastic container to automatically load its credentials without needing to configure
* them in the SdkClientBuilder.
*
* This is not used if the {@link #AWS_CONTAINER_CREDENTIALS_RELATIVE_URI} is not specified.
*/
AWS_CONTAINER_SERVICE_ENDPOINT("aws.containerServiceEndpoint", "http://169.254.170.2"),
/**
* The elastic container metadata service path that should be called by the ContainerCredentialsProvider when
* loading credentials form the container metadata service. If this is not specified, credentials will not be automatically
* loaded from the container metadata service.
*
* @see #AWS_CONTAINER_SERVICE_ENDPOINT
*/
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI("aws.containerCredentialsPath", null),
/**
* The full URI path to a localhost metadata service to be used.
*/
AWS_CONTAINER_CREDENTIALS_FULL_URI("aws.containerCredentialsFullUri", null),
/**
* An authorization token to pass to a container metadata service, only used when {@link #AWS_CONTAINER_CREDENTIALS_FULL_URI}
* is specified.
*
* @see #AWS_CONTAINER_CREDENTIALS_FULL_URI
*/
AWS_CONTAINER_AUTHORIZATION_TOKEN("aws.containerAuthorizationToken", null),
/**
* Explicitly identify the default synchronous HTTP implementation the SDK will use. Useful
* when there are multiple implementations on the classpath or as a performance optimization
* since implementation discovery requires classpath scanning.
*/
SYNC_HTTP_SERVICE_IMPL("software.amazon.awssdk.http.service.impl", null),
/**
* Explicitly identify the default Async HTTP implementation the SDK will use. Useful
* when there are multiple implementations on the classpath or as a performance optimization
* since implementation discovery requires classpath scanning.
*/
ASYNC_HTTP_SERVICE_IMPL("software.amazon.awssdk.http.async.service.impl", null),
/**
* Whether CBOR optimization should automatically be used if its support is found on the classpath and the service supports
* CBOR-formatted JSON.
*/
CBOR_ENABLED("aws.cborEnabled", "true"),
/**
* Whether binary ION representation optimization should automatically be used if the service supports ION.
*/
BINARY_ION_ENABLED("aws.binaryIonEnabled", "true"),
/**
* The execution environment of the SDK user. This is automatically set in certain environments by the underlying AWS service.
* For example, AWS Lambda will automatically specify a runtime indicating that the SDK is being used within Lambda.
*/
AWS_EXECUTION_ENV("aws.executionEnvironment", null),
/**
* Whether endpoint discovery should be enabled.
*/
AWS_ENDPOINT_DISCOVERY_ENABLED("aws.endpointDiscoveryEnabled", null),
/**
* The S3 regional endpoint setting for the {@code us-east-1} region. Setting the value to {@code regional} causes
* the SDK to use the {@code s3.us-east-1.amazonaws.com} endpoint when using the {@code US_EAST_1} region instead of
* the global {@code s3.amazonaws.com}. Using the regional endpoint is disabled by default.
*/
AWS_S3_US_EAST_1_REGIONAL_ENDPOINT("aws.s3UseUsEast1RegionalEndpoint", null),
/**
* Which {@link RetryMode} to use for the default {@link RetryPolicy}, when one is not specified at the client level.
*/
AWS_RETRY_MODE("aws.retryMode", null),
/**
* Defines the default value for {@link RetryPolicy.Builder#numRetries(Integer)}, if the retry count is not overridden in the
* retry policy configured via {@link ClientOverrideConfiguration.Builder#retryPolicy(RetryPolicy)}. This is one more than
* the number of retries, so aws.maxAttempts = 1 is 0 retries.
*/
AWS_MAX_ATTEMPTS("aws.maxAttempts", null),
/**
* Which {@code DefaultsMode} to use, case insensitive
*/
AWS_DEFAULTS_MODE("aws.defaultsMode", null),
/**
* Defines whether dualstack endpoints should be resolved during default endpoint resolution instead of non-dualstack
* endpoints.
*/
AWS_USE_DUALSTACK_ENDPOINT("aws.useDualstackEndpoint", null),
/**
* Defines whether fips endpoints should be resolved during default endpoint resolution instead of non-fips endpoints.
*/
AWS_USE_FIPS_ENDPOINT("aws.useFipsEndpoint", null),
/**
* Whether request compression is disabled for operations marked with the RequestCompression trait. The default value is
* false, i.e., request compression is enabled.
*/
AWS_DISABLE_REQUEST_COMPRESSION("aws.disableRequestCompression", null),
/**
* Defines the minimum compression size in bytes, inclusive, for a request to be compressed. The default value is 10_240.
* The value must be non-negative and no greater than 10_485_760.
*/
AWS_REQUEST_MIN_COMPRESSION_SIZE_BYTES("aws.requestMinCompressionSizeBytes", null),
;
private final String systemProperty;
private final String defaultValue;
SdkSystemSetting(String systemProperty, String defaultValue) {
this.systemProperty = systemProperty;
this.defaultValue = defaultValue;
}
@Override
public String property() {
return systemProperty;
}
@Override
public String environmentVariable() {
return name();
}
@Override
public String defaultValue() {
return defaultValue;
}
}
| 2,038 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/CredentialType.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Class that identifies the type of credentials typically used by the service to authorize an api request.
*/
@SdkPublicApi
public final class CredentialType {
/**
* Credential type that uses Bearer Token Authorization to authorize a request.
* <p>For more details, see:
* <a href="https://oauth.net/2/bearer-tokens/">
* https://oauth.net/2/bearer-tokens/</a></p>
*/
public static final CredentialType TOKEN = of("TOKEN");
private final String value;
private CredentialType(String value) {
this.value = value;
}
/**
* Retrieves the Credential Type for a given value.
* @param value Teh value to get CredentialType for.
* @return {@link CredentialType} for the given value.
*/
public static CredentialType of(String value) {
Validate.paramNotNull(value, "value");
return CredentialTypeCache.put(value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CredentialType that = (CredentialType) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hashCode(value);
}
@Override
public String toString() {
return ToString.builder("CredentialType{" +
"value='" + value + '\'' +
'}').build();
}
private static class CredentialTypeCache {
private static final ConcurrentHashMap<String, CredentialType> VALUES = new ConcurrentHashMap<>();
private CredentialTypeCache() {
}
private static CredentialType put(String value) {
return VALUES.computeIfAbsent(value, v -> new CredentialType(value));
}
}
}
| 2,039 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/FileTransformerConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Configuration options for {@link AsyncResponseTransformer#toFile(Path, FileTransformerConfiguration)} to configure how the SDK
* should write the file and if the SDK should delete the file when an exception occurs.
*
* @see #builder()
* @see FileWriteOption
* @see FailureBehavior
*/
@SdkPublicApi
public final class FileTransformerConfiguration implements ToCopyableBuilder<FileTransformerConfiguration.Builder,
FileTransformerConfiguration> {
private final FileWriteOption fileWriteOption;
private final FailureBehavior failureBehavior;
private final ExecutorService executorService;
private FileTransformerConfiguration(DefaultBuilder builder) {
this.fileWriteOption = Validate.paramNotNull(builder.fileWriteOption, "fileWriteOption");
this.failureBehavior = Validate.paramNotNull(builder.failureBehavior, "failureBehavior");
this.executorService = builder.executorService;
}
/**
* The configured {@link FileWriteOption}
*/
public FileWriteOption fileWriteOption() {
return fileWriteOption;
}
/**
* The configured {@link FailureBehavior}
*/
public FailureBehavior failureBehavior() {
return failureBehavior;
}
/**
* The configured {@link ExecutorService} the writes should be executed on.
* <p>
* If not set, the default thread pool defined by the underlying {@link java.nio.file.spi.FileSystemProvider} will be used.
* This will typically be the thread pool defined by the {@link AsynchronousChannelGroup}.
*/
public Optional<ExecutorService> executorService() {
return Optional.ofNullable(executorService);
}
/**
* Create a {@link Builder}, used to create a {@link FileTransformerConfiguration}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Returns the default {@link FileTransformerConfiguration} for {@link FileWriteOption#CREATE_NEW}
* <p>
* Always create a new file. If the file already exists, {@link FileAlreadyExistsException} will be thrown.
* In the event of an error, the SDK will attempt to delete the file (whatever has been written to it so far).
*/
public static FileTransformerConfiguration defaultCreateNew() {
return builder().fileWriteOption(FileWriteOption.CREATE_NEW)
.failureBehavior(FailureBehavior.DELETE)
.build();
}
/**
* Returns the default {@link FileTransformerConfiguration} for {@link FileWriteOption#CREATE_OR_REPLACE_EXISTING}
* <p>
* Create a new file if it doesn't exist, otherwise replace the existing file.
* In the event of an error, the SDK will NOT attempt to delete the file, leaving it as-is
*/
public static FileTransformerConfiguration defaultCreateOrReplaceExisting() {
return builder().fileWriteOption(FileWriteOption.CREATE_OR_REPLACE_EXISTING)
.failureBehavior(FailureBehavior.LEAVE)
.build();
}
/**
* Returns the default {@link FileTransformerConfiguration} for {@link FileWriteOption#CREATE_OR_APPEND_TO_EXISTING}
* <p>
* Create a new file if it doesn't exist, otherwise append to the existing file.
* In the event of an error, the SDK will NOT attempt to delete the file, leaving it as-is
*/
public static FileTransformerConfiguration defaultCreateOrAppend() {
return builder().fileWriteOption(FileWriteOption.CREATE_OR_APPEND_TO_EXISTING)
.failureBehavior(FailureBehavior.LEAVE)
.build();
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FileTransformerConfiguration that = (FileTransformerConfiguration) o;
if (fileWriteOption != that.fileWriteOption) {
return false;
}
if (failureBehavior != that.failureBehavior) {
return false;
}
return Objects.equals(executorService, that.executorService);
}
@Override
public int hashCode() {
int result = fileWriteOption != null ? fileWriteOption.hashCode() : 0;
result = 31 * result + (failureBehavior != null ? failureBehavior.hashCode() : 0);
result = 31 * result + (executorService != null ? executorService.hashCode() : 0);
return result;
}
/**
* Defines how the SDK should write the file
*/
public enum FileWriteOption {
/**
* Always create a new file. If the file already exists, {@link FileAlreadyExistsException} will be thrown.
*/
CREATE_NEW,
/**
* Create a new file if it doesn't exist, otherwise replace the existing file.
*/
CREATE_OR_REPLACE_EXISTING,
/**
* Create a new file if it doesn't exist, otherwise append to the existing file.
*/
CREATE_OR_APPEND_TO_EXISTING
}
/**
* Defines how the SDK should handle the file if there is an exception
*/
public enum FailureBehavior {
/**
* In the event of an error, the SDK will attempt to delete the file and whatever has been written to it so far.
*/
DELETE,
/**
* In the event of an error, the SDK will NOT attempt to delete the file and leave the file as-is (with whatever has been
* written to it so far)
*/
LEAVE
}
public interface Builder extends CopyableBuilder<Builder, FileTransformerConfiguration> {
/**
* Configures how to write the file
*
* @param fileWriteOption the file write option
* @return This object for method chaining.
*/
Builder fileWriteOption(FileWriteOption fileWriteOption);
/**
* Configures the {@link FailureBehavior} in the event of an error
*
* @param failureBehavior the failure behavior
* @return This object for method chaining.
*/
Builder failureBehavior(FailureBehavior failureBehavior);
/**
* Configures the {@link ExecutorService} the writes should be executed on.
*
* @param executorService the executor service to use, or null if using the default thread pool.
* @return This object for method chaining.
*/
Builder executorService(ExecutorService executorService);
}
private static final class DefaultBuilder implements Builder {
private FileWriteOption fileWriteOption;
private FailureBehavior failureBehavior;
private ExecutorService executorService;
private DefaultBuilder() {
}
private DefaultBuilder(FileTransformerConfiguration fileTransformerConfiguration) {
this.fileWriteOption = fileTransformerConfiguration.fileWriteOption;
this.failureBehavior = fileTransformerConfiguration.failureBehavior;
this.executorService = fileTransformerConfiguration.executorService;
}
@Override
public Builder fileWriteOption(FileWriteOption fileWriteOption) {
this.fileWriteOption = fileWriteOption;
return this;
}
@Override
public Builder failureBehavior(FailureBehavior failureBehavior) {
this.failureBehavior = failureBehavior;
return this;
}
@Override
public Builder executorService(ExecutorService executorService) {
this.executorService = executorService;
return this;
}
@Override
public FileTransformerConfiguration build() {
return new FileTransformerConfiguration(this);
}
}
} | 2,040 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkStandardLogger.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZN_REQUEST_ID_HEADERS;
import static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZ_ID_2_HEADER;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.utils.Logger;
/**
* A centralized set of loggers that used across the SDK to log particular types of events. SDK users can then specifically enable
* just these loggers to get the type of that they want instead of having to enable all logging.
*/
@SdkProtectedApi
public final class SdkStandardLogger {
/**
* Logger providing detailed information on requests/responses. Users can enable this logger to get access to AWS request IDs
* for responses, individual requests and parameters sent to AWS, etc.
*/
public static final Logger REQUEST_LOGGER = Logger.loggerFor("software.amazon.awssdk.request");
/**
* Logger used for the purpose of logging the request id extracted either from the
* http response header or from the response body.
*/
public static final Logger REQUEST_ID_LOGGER = Logger.loggerFor("software.amazon.awssdk.requestId");
private SdkStandardLogger() {
}
/**
* Log the response status code and request ID
*/
public static void logRequestId(SdkHttpResponse response) {
Supplier<String> logStatement = () -> {
String placeholder = "not available";
String requestId = "Request ID: " + response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS).orElse(placeholder) +
", " +
"Extended Request ID: " + response.firstMatchingHeader(X_AMZ_ID_2_HEADER).orElse(placeholder);
String responseState = response.isSuccessful() ? "successful" : "failed";
return "Received " + responseState + " response: " + response.statusCode() + ", " + requestId;
};
REQUEST_ID_LOGGER.debug(logStatement);
REQUEST_LOGGER.debug(logStatement);
}
}
| 2,041 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkBytes.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* An in-memory representation of data being given to a service or being returned by a service.
*
* This can be created via static methods, like {@link SdkBytes#fromByteArray(byte[])}. This can be converted to binary types
* via instance methods, like {@link SdkBytes#asByteArray()}.
*/
@SdkPublicApi
public final class SdkBytes extends BytesWrapper implements Serializable {
private static final long serialVersionUID = 1L;
// Needed for serialization
private SdkBytes() {
super();
}
/**
* @see #fromByteArray(byte[])
* @see #fromByteBuffer(ByteBuffer)
* @see #fromInputStream(InputStream)
* @see #fromUtf8String(String)
* @see #fromString(String, Charset)
*/
private SdkBytes(byte[] bytes) {
super(bytes);
}
/**
* Create {@link SdkBytes} from a Byte buffer. This will read the remaining contents of the byte buffer.
*/
public static SdkBytes fromByteBuffer(ByteBuffer byteBuffer) {
Validate.paramNotNull(byteBuffer, "byteBuffer");
return new SdkBytes(BinaryUtils.copyBytesFrom(byteBuffer));
}
/**
* Create {@link SdkBytes} from a Byte array. This will copy the contents of the byte array.
*/
public static SdkBytes fromByteArray(byte[] bytes) {
Validate.paramNotNull(bytes, "bytes");
return new SdkBytes(Arrays.copyOf(bytes, bytes.length));
}
/**
* Create {@link SdkBytes} from a Byte array <b>without</b> copying the contents of the byte array. This introduces
* concurrency risks, allowing: (1) the caller to modify the byte array stored in this {@code SdkBytes} implementation AND
* (2) any users of {@link #asByteArrayUnsafe()} to modify the byte array passed into this {@code SdkBytes} implementation.
*
* <p>As the method name implies, this is unsafe. Use {@link #fromByteArray(byte[])} unless you're sure you know the risks.
*/
public static SdkBytes fromByteArrayUnsafe(byte[] bytes) {
Validate.paramNotNull(bytes, "bytes");
return new SdkBytes(bytes);
}
/**
* Create {@link SdkBytes} from a string, using the provided charset.
*/
public static SdkBytes fromString(String string, Charset charset) {
Validate.paramNotNull(string, "string");
Validate.paramNotNull(charset, "charset");
return new SdkBytes(string.getBytes(charset));
}
/**
* Create {@link SdkBytes} from a string, using the UTF-8 charset.
*/
public static SdkBytes fromUtf8String(String string) {
return fromString(string, StandardCharsets.UTF_8);
}
/**
* Create {@link SdkBytes} from an input stream. This will read all of the remaining contents of the stream, but will not
* close it.
*/
public static SdkBytes fromInputStream(InputStream inputStream) {
Validate.paramNotNull(inputStream, "inputStream");
return new SdkBytes(invokeSafely(() -> IoUtils.toByteArray(inputStream)));
}
@Override
public String toString() {
return ToString.builder("SdkBytes")
.add("bytes", asByteArrayUnsafe())
.build();
}
}
| 2,042 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/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.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Represents the communication protocol to use when sending requests to AWS.
* <p>
* Communication over HTTPS is the default, and is more secure than HTTP, which
* is why AWS recommends using HTTPS. HTTPS connections can use more system
* resources because of the extra work to encrypt network traffic, so the option
* to use HTTP is available in case users need it.
*/
@SdkProtectedApi
public enum Protocol {
/**
* HTTP Protocol - Using the HTTP protocol is less secure than HTTPS, but
* can slightly reduce the system resources used when communicating with
* AWS.
*/
HTTP("http"),
/**
* HTTPS Protocol - Using the HTTPS protocol is more secure than using the
* HTTP protocol, but may use slightly more system resources. AWS recommends
* using HTTPS for maximize security.
*/
HTTPS("https");
private final String protocol;
Protocol(String protocol) {
this.protocol = protocol;
}
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return protocol;
}
}
| 2,043 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/CompressionConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Configuration options for operations with the RequestCompression trait to disable request configuration and set the minimum
* compression threshold in bytes.
*/
@SdkPublicApi
public final class CompressionConfiguration implements ToCopyableBuilder<CompressionConfiguration.Builder,
CompressionConfiguration> {
private final Boolean requestCompressionEnabled;
private final Integer minimumCompressionThresholdInBytes;
private CompressionConfiguration(DefaultBuilder builder) {
this.requestCompressionEnabled = builder.requestCompressionEnabled;
this.minimumCompressionThresholdInBytes = builder.minimumCompressionThresholdInBytes;
}
/**
* If set, returns true if request compression is enabled, else false if request compression is disabled.
*/
public Boolean requestCompressionEnabled() {
return requestCompressionEnabled;
}
/**
* If set, returns the minimum compression threshold in bytes, inclusive, in order to trigger request compression.
*/
public Integer minimumCompressionThresholdInBytes() {
return minimumCompressionThresholdInBytes;
}
/**
* Create a {@link CompressionConfiguration.Builder}, used to create a {@link CompressionConfiguration}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public String toString() {
return ToString.builder("CompressionConfiguration")
.add("requestCompressionEnabled", requestCompressionEnabled)
.add("minimumCompressionThresholdInBytes", minimumCompressionThresholdInBytes)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompressionConfiguration that = (CompressionConfiguration) o;
if (!Objects.equals(requestCompressionEnabled, that.requestCompressionEnabled)) {
return false;
}
return Objects.equals(minimumCompressionThresholdInBytes, that.minimumCompressionThresholdInBytes);
}
@Override
public int hashCode() {
int result = requestCompressionEnabled != null ? requestCompressionEnabled.hashCode() : 0;
result = 31 * result + (minimumCompressionThresholdInBytes != null ? minimumCompressionThresholdInBytes.hashCode() : 0);
return result;
}
public interface Builder extends CopyableBuilder<Builder, CompressionConfiguration> {
/**
* Configures whether request compression is enabled or not, for operations that the service has designated as
* supporting compression. The default value is true.
*
* @param requestCompressionEnabled
* @return This object for method chaining.
*/
Builder requestCompressionEnabled(Boolean requestCompressionEnabled);
/**
* Configures the minimum compression threshold, inclusive, in bytes. A request whose size is less than the threshold
* will not be compressed, even if the compression trait is present. The default value is 10_240. The value must be
* non-negative and no greater than 10_485_760.
*
* @param minimumCompressionThresholdInBytes
* @return This object for method chaining.
*/
Builder minimumCompressionThresholdInBytes(Integer minimumCompressionThresholdInBytes);
}
private static final class DefaultBuilder implements Builder {
private Boolean requestCompressionEnabled;
private Integer minimumCompressionThresholdInBytes;
private DefaultBuilder() {
}
private DefaultBuilder(CompressionConfiguration compressionConfiguration) {
this.requestCompressionEnabled = compressionConfiguration.requestCompressionEnabled;
this.minimumCompressionThresholdInBytes = compressionConfiguration.minimumCompressionThresholdInBytes;
}
@Override
public Builder requestCompressionEnabled(Boolean requestCompressionEnabled) {
this.requestCompressionEnabled = requestCompressionEnabled;
return this;
}
@Override
public Builder minimumCompressionThresholdInBytes(Integer minimumCompressionThresholdInBytes) {
this.minimumCompressionThresholdInBytes = minimumCompressionThresholdInBytes;
return this;
}
@Override
public CompressionConfiguration build() {
return new CompressionConfiguration(this);
}
}
}
| 2,044 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SelectedAuthScheme.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption;
import software.amazon.awssdk.http.auth.spi.signer.HttpSigner;
import software.amazon.awssdk.identity.spi.Identity;
import software.amazon.awssdk.utils.Validate;
/**
* A container for the identity resolver, signer and auth option that we selected for use with this service call attempt.
*/
@SdkProtectedApi
public final class SelectedAuthScheme<T extends Identity> {
private final CompletableFuture<? extends T> identity;
private final HttpSigner<T> signer;
private final AuthSchemeOption authSchemeOption;
public SelectedAuthScheme(CompletableFuture<? extends T> identity,
HttpSigner<T> signer,
AuthSchemeOption authSchemeOption) {
this.identity = Validate.paramNotNull(identity, "identity");
this.signer = Validate.paramNotNull(signer, "signer");
this.authSchemeOption = Validate.paramNotNull(authSchemeOption, "authSchemeOption");
}
public CompletableFuture<? extends T> identity() {
return identity;
}
public HttpSigner<T> signer() {
return signer;
}
public AuthSchemeOption authSchemeOption() {
return authSchemeOption;
}
}
| 2,045 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/ServiceConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import software.amazon.awssdk.annotations.SdkPublicApi;
@SdkPublicApi
public interface ServiceConfiguration {
}
| 2,046 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkPlugin.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import software.amazon.awssdk.annotations.SdkPreviewApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* A plugin modifies a client's configuration when the client is created or at request execution
* time.
*/
@SdkPreviewApi
@SdkPublicApi
@ThreadSafe
@FunctionalInterface
public interface SdkPlugin extends SdkAutoCloseable {
/**
* Modify the provided client configuration.
*/
void configureClient(SdkServiceClientConfiguration.Builder config);
@Override
default void close() {
}
}
| 2,047 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkNumber.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Objects;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Validate;
/**
* An in-memory representation of Number being given to a service or being returned by a service.
* This is a SDK representation of a Number. This allows conversion to any desired numeric type by providing constructors
* as below
* <ul>
* <li>{@link #fromBigDecimal(BigDecimal)} to create from a BigDecimal.</li>
* <li>{@link #fromBigInteger(BigInteger)} to create from a BigInteger.</li>
* <li>{@link #fromDouble(double)} to create from a double</li>
* <li>{@link #fromFloat(float)} to create from a float.</li>
* <li>{@link #fromLong(long)} to create from a long.</li>
* <li>{@link #fromShort(short)} to create from a short.</li>
* <li>{@link #fromInteger(int)} to create from an integer.</li>
* <li>{@link #fromString(String)} to create from a String</li>
* </ul>
*
* Thus, by doing this, this class is able to preserve arbitrary precision of any given number.
* <p>
* If {@link SdkNumber} is expected in a particular number format then its corresponding getter methods can be used.
* <p>
* Example for a {@link SdkNumber} created with {@link BigDecimal} the
* {@link #fromBigDecimal(BigDecimal)} can be used.
*/
@SdkPublicApi
@Immutable
public final class SdkNumber extends Number implements Serializable {
private static final long serialVersionUID = 1L;
private final Number numberValue;
private final String stringValue;
/**
* @param value Number value as passed in the from COnstructor.
* @see #fromBigDecimal(BigDecimal)
* @see #fromBigInteger(BigInteger)
* @see #fromDouble(double)
* @see #fromFloat(float)
* @see #fromLong(long)
* @see #fromShort(short)
* @see #fromInteger(int)
*/
private SdkNumber(Number value) {
this.numberValue = value;
this.stringValue = null;
}
/**
* .
*
* @param stringValue String value.
* @see #fromString(String)
*/
private SdkNumber(String stringValue) {
this.stringValue = stringValue;
this.numberValue = null;
}
private static boolean isNumberValueNaN(Number numberValue) {
return (numberValue instanceof Double && Double.isNaN((double) numberValue)) ||
(numberValue instanceof Float && Float.isNaN((float) numberValue));
}
private static boolean isNumberValueInfinite(Number numberValue) {
return (numberValue instanceof Double && Double.isInfinite((double) numberValue)) ||
(numberValue instanceof Float && Float.isInfinite((float) numberValue));
}
private static Number valueOf(Number numberValue) {
Number valueOfInfiniteOrNaN = valueOfInfiniteOrNaN(numberValue);
return valueOfInfiniteOrNaN != null ? valueOfInfiniteOrNaN : valueInBigDecimal(numberValue);
}
private static Number valueOfInfiniteOrNaN(Number numberValue) {
if (numberValue instanceof Double
&& (Double.isInfinite((double) numberValue) || Double.isNaN((double) numberValue))) {
return Double.valueOf(numberValue.doubleValue());
} else if ((numberValue instanceof Float
&& (Float.isInfinite((float) numberValue) || Float.isNaN((float) numberValue)))) {
return Float.valueOf(numberValue.floatValue());
} else {
return null;
}
}
/**
* This function converts a given number to BigDecimal Number where the caller can convert to an primitive number.
* This is done to keep the precision.
*
* @param numberValue The number value.
* @return Big Decimal value for the given number.
*/
private static BigDecimal valueInBigDecimal(Number numberValue) {
if (numberValue instanceof Double) {
return BigDecimal.valueOf((double) numberValue);
} else if (numberValue instanceof Float) {
return BigDecimal.valueOf((float) numberValue);
} else if (numberValue instanceof Integer) {
return new BigDecimal((int) numberValue);
} else if (numberValue instanceof Short) {
return new BigDecimal((short) numberValue);
} else if (numberValue instanceof Long) {
return BigDecimal.valueOf((Long) numberValue);
} else if (numberValue instanceof BigDecimal) {
return (BigDecimal) numberValue;
} else if (numberValue instanceof BigInteger) {
return new BigDecimal((BigInteger) numberValue);
} else {
return new BigDecimal(numberValue.toString());
}
}
/**
* Create {@link SdkNumber} from a integer value.
*
* @param integerValue Integer value.
* @return new {@link SdkNumber} for the given int value.
*/
public static SdkNumber fromInteger(int integerValue) {
return new SdkNumber(integerValue);
}
/**
* Create {@link SdkNumber} from a BigInteger value.
*
* @param bigIntegerValue BigInteger value.
* @return new {@link SdkNumber} for the given BigInteger value.
*/
public static SdkNumber fromBigInteger(BigInteger bigIntegerValue) {
return new SdkNumber(bigIntegerValue);
}
/**
* Create {@link SdkNumber} from a BigDecimal value.
*
* @param bigDecimalValue BigInteger value.
* @return new {@link SdkNumber} for the given BigDecimal value.
*/
public static SdkNumber fromBigDecimal(BigDecimal bigDecimalValue) {
Validate.notNull(bigDecimalValue, "BigDecimal cannot be null");
return new SdkNumber(bigDecimalValue);
}
/**
* Create {@link SdkNumber} from a long Value.
*
* @param longValue long value.
* @return new {@link SdkNumber} for the given long value.
*/
public static SdkNumber fromLong(long longValue) {
return new SdkNumber(longValue);
}
/**
* Create {@link SdkNumber} from a double Value.
*
* @param doubleValue long value.
* @return new {@link SdkNumber} for the given double value.
*/
public static SdkNumber fromDouble(double doubleValue) {
return new SdkNumber(doubleValue);
}
/**
* Create {@link SdkNumber} from a long Value.
*
* @param shortValue long value.
* @return new {@link SdkNumber} for the given long value.
*/
public static SdkNumber fromShort(short shortValue) {
return new SdkNumber(shortValue);
}
/**
* Create {@link SdkNumber} from a float Value.
*
* @param floatValue float value.
* @return new {@link SdkNumber} for the given float value.
*/
public static SdkNumber fromFloat(float floatValue) {
return new SdkNumber(floatValue);
}
/**
* Create {@link SdkNumber} from a long Value.
*
* @param stringValue String value.
* @return new {@link SdkNumber} for the given stringValue value.
*/
public static SdkNumber fromString(String stringValue) {
return new SdkNumber(stringValue);
}
/**
* Gets the integer value of the {@link SdkNumber}.
* If we do a intValue() for {@link SdkNumber} constructed
* from float, double, long, BigDecimal, BigInteger number type then it
* may result in loss of magnitude and a loss of precision.
* The result may lose some of the least significant bits of the value.
* Precision is not lost while getting a {@link SdkNumber} which was constructed as
* lower precision number type like short, byte, integer.
*
* @return integer value of {@link SdkNumber} .
*/
@Override
public int intValue() {
return numberValue instanceof Integer ? numberValue.intValue() :
stringValue != null ? new BigDecimal(stringValue).intValue()
: valueOf(numberValue).intValue();
}
/**
* Gets the long value of the {@link SdkNumber}.
* If we do a longValue() for {@link SdkNumber} constructed from
* float, double, BigDecimal, BigInteger number type then it
* may result in loss of magnitude and a loss of precision.
* Precision is not lost while getting a {@link SdkNumber} which was constructed from
* lower precision type like short, byte, integer.
*
* @return long value of {@link SdkNumber}.
*/
@Override
public long longValue() {
return numberValue instanceof Long ? numberValue.longValue() :
stringValue != null ? new BigDecimal(stringValue).longValue() : valueOf(numberValue).longValue();
}
/**
* Gets the float value of the {@link SdkNumber}.
* If we do a floatValue() for {@link SdkNumber} constructed from
* double, BigDecimal, BigInteger number type then it
* may result in loss of magnitude and a loss of precision.
* Precision is not lost while getting a {@link SdkNumber} which was constructed from
* precision type like short, byte, integer, long.
*
* @return long value of {@link SdkNumber}.
*/
@Override
public float floatValue() {
return numberValue instanceof Float ? numberValue.floatValue() :
numberValue != null ? valueOf(numberValue).floatValue() : new BigDecimal(stringValue).floatValue();
}
/**
* Gets the double value of the {@link SdkNumber}.
* If we do a doubleValue() for {@link SdkNumber} constructed from BigDecimal, BigInteger number type then it
* may result in loss of magnitude and a loss of precision.
* Precision is not lost while getting a {@link SdkNumber} which was constructed from
* precision type like short, byte, integer, long, float.
*
* @return long value of {@link SdkNumber}.
*/
@Override
public double doubleValue() {
return numberValue instanceof Double ? numberValue.doubleValue() :
numberValue != null ? valueOf(numberValue).doubleValue() :
new BigDecimal(stringValue).doubleValue();
}
/**
* Gets the bigDecimalValue of the {@link SdkNumber}.
* Precision is not lost in this case.
* However bigDecimalValue cannot be performed on
* a {{@link SdkNumber}} constructed from Float/Double Nan/Infinity.
*
* @return BigDecimal value of {@link SdkNumber}
* @throws NumberFormatException Exception in thrown if a {@link SdkNumber} was constructed asNan/Infinte number
* of Double/FLoat type.Since we cannot convert NaN/Infinite numbers to BigDecimal.
*/
public BigDecimal bigDecimalValue() {
if (stringValue != null) {
return new BigDecimal(stringValue);
}
if (numberValue instanceof BigDecimal) {
return (BigDecimal) numberValue;
}
if (isNumberValueNaN(numberValue) || isNumberValueInfinite(numberValue)) {
throw new NumberFormatException("Nan or Infinite Number can not be converted to BigDecimal.");
} else {
return valueInBigDecimal(numberValue);
}
}
/**
* Gets the String value of the {@link SdkNumber}.
*
* @return the stringValue
*/
public String stringValue() {
return stringValue != null ? stringValue : numberValue.toString();
}
@Override
public String toString() {
return stringValue != null ? stringValue : numberValue.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SdkNumber)) {
return false;
}
SdkNumber sdkNumber = (SdkNumber) o;
return Objects.equals(stringValue(), sdkNumber.stringValue());
}
@Override
public int hashCode() {
return Objects.hashCode(stringValue());
}
}
| 2,048 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/ResponseBytes.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.Arrays;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* An in-memory representation of the service's response from a streaming operation. This usually obtained by calling the "bytes"
* form of a streaming operation, like S3's {@code getObjectBytes}. Can also be retrieved by passing
* {@link ResponseTransformer#toBytes()} or {@link AsyncResponseTransformer#toBytes()} to a streaming output operation.
*/
@SdkPublicApi
public final class ResponseBytes<ResponseT> extends BytesWrapper {
private final ResponseT response;
private ResponseBytes(ResponseT response, byte[] bytes) {
super(bytes);
this.response = Validate.paramNotNull(response, "response");
}
/**
* Create {@link ResponseBytes} from a Byte array. This will copy the contents of the byte array.
*/
public static <ResponseT> ResponseBytes<ResponseT> fromInputStream(ResponseT response, InputStream stream)
throws UncheckedIOException {
return new ResponseBytes<>(response, invokeSafely(() -> IoUtils.toByteArray(stream)));
}
/**
* Create {@link ResponseBytes} from a Byte array. This will copy the contents of the byte array.
*/
public static <ResponseT> ResponseBytes<ResponseT> fromByteArray(ResponseT response, byte[] bytes) {
return new ResponseBytes<>(response, Arrays.copyOf(bytes, bytes.length));
}
/**
* Create {@link ResponseBytes} from a Byte array <b>without</b> copying the contents of the byte array. This introduces
* concurrency risks, allowing: (1) the caller to modify the byte array stored in this {@code SdkBytes} implementation AND
* (2) any users of {@link #asByteArrayUnsafe()} to modify the byte array passed into this {@code SdkBytes} implementation.
*
* <p>As the method name implies, this is unsafe. Use {@link #fromByteArray(Object, byte[])} unless you're sure you know the
* risks.
*/
public static <ResponseT> ResponseBytes<ResponseT> fromByteArrayUnsafe(ResponseT response, byte[] bytes) {
return new ResponseBytes<>(response, bytes);
}
/**
* @return the unmarshalled response object from the service.
*/
public ResponseT response() {
return response;
}
@Override
public String toString() {
return ToString.builder("ResponseBytes")
.add("response", response)
.add("bytes", asByteArrayUnsafe())
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
ResponseBytes<?> that = (ResponseBytes<?>) o;
return response != null ? response.equals(that.response) : that.response == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (response != null ? response.hashCode() : 0);
return result;
}
}
| 2,049 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.util.Optional;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* The base class for all SDK requests.
* <p>
* Implementations must ensure the class is immutable.
* </p>
* @see SdkResponse
*/
@Immutable
@SdkPublicApi
public abstract class SdkRequest implements SdkPojo {
/**
* @return The optional client configuration overrides for this request.
*/
public abstract Optional<? extends RequestOverrideConfiguration> overrideConfiguration();
/**
* Used to retrieve the value of a field from any class that extends {@link SdkRequest}. The field name
* specified should match the member name from the corresponding service-2.json model specified in the
* codegen-resources folder for a given service. The class specifies what class to cast the returned value to.
* If the returned value is also a modeled class, the {@link #getValueForField(String, Class)} method will
* again be available.
*
* @param fieldName The name of the member to be retrieved.
* @param clazz The class to cast the returned object to.
* @return Optional containing the casted return value
*/
public <T> Optional<T> getValueForField(String fieldName, Class<T> clazz) {
return Optional.empty();
}
public abstract Builder toBuilder();
public interface Builder {
RequestOverrideConfiguration overrideConfiguration();
SdkRequest build();
}
}
| 2,050 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkResponse.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.SdkHttpResponse;
/**
* The base class for all SDK responses.
*
* @see SdkRequest
*/
@Immutable
@SdkPublicApi
public abstract class SdkResponse implements SdkPojo {
private final SdkHttpResponse sdkHttpResponse;
protected SdkResponse(Builder builder) {
this.sdkHttpResponse = builder.sdkHttpResponse();
}
/**
* @return HTTP response data returned from the service.
*
* @see SdkHttpResponse
*/
public SdkHttpResponse sdkHttpResponse() {
return sdkHttpResponse;
}
/**
* Used to retrieve the value of a field from any class that extends {@link SdkResponse}. The field name
* specified should match the member name from the corresponding service-2.json model specified in the
* codegen-resources folder for a given service. The class specifies what class to cast the returned value to.
* If the returned value is also a modeled class, the {@link #getValueForField(String, Class)} method will
* again be available.
*
* @param fieldName The name of the member to be retrieved.
* @param clazz The class to cast the returned object to.
* @return Optional containing the casted return value
*/
public <T> Optional<T> getValueForField(String fieldName, Class<T> clazz) {
return Optional.empty();
}
public abstract Builder toBuilder();
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SdkResponse that = (SdkResponse) o;
return Objects.equals(sdkHttpResponse, that.sdkHttpResponse);
}
@Override
public int hashCode() {
return Objects.hashCode(sdkHttpResponse);
}
public interface Builder {
Builder sdkHttpResponse(SdkHttpResponse sdkHttpResponse);
SdkHttpResponse sdkHttpResponse();
SdkResponse build();
}
protected abstract static class BuilderImpl implements Builder {
private SdkHttpResponse sdkHttpResponse;
protected BuilderImpl() {
}
protected BuilderImpl(SdkResponse response) {
this.sdkHttpResponse = response.sdkHttpResponse();
}
@Override
public Builder sdkHttpResponse(SdkHttpResponse sdkHttpResponse) {
this.sdkHttpResponse = sdkHttpResponse;
return this;
}
@Override
public SdkHttpResponse sdkHttpResponse() {
return sdkHttpResponse;
}
}
}
| 2,051 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/RequestOverrideConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.TreeMap;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPreviewApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.endpoints.EndpointProvider;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.utils.CollectionUtils;
import software.amazon.awssdk.utils.Validate;
/**
* Base per-request override configuration for all SDK requests.
*/
@Immutable
@SdkPublicApi
public abstract class RequestOverrideConfiguration {
private final Map<String, List<String>> headers;
private final Map<String, List<String>> rawQueryParameters;
private final List<ApiName> apiNames;
private final Duration apiCallTimeout;
private final Duration apiCallAttemptTimeout;
private final Signer signer;
private final List<MetricPublisher> metricPublishers;
private final ExecutionAttributes executionAttributes;
private final EndpointProvider endpointProvider;
private final CompressionConfiguration compressionConfiguration;
private final List<SdkPlugin> plugins;
protected RequestOverrideConfiguration(Builder<?> builder) {
this.headers = CollectionUtils.deepUnmodifiableMap(builder.headers(), () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER));
this.rawQueryParameters = CollectionUtils.deepUnmodifiableMap(builder.rawQueryParameters());
this.apiNames = Collections.unmodifiableList(new ArrayList<>(builder.apiNames()));
this.apiCallTimeout = Validate.isPositiveOrNull(builder.apiCallTimeout(), "apiCallTimeout");
this.apiCallAttemptTimeout = Validate.isPositiveOrNull(builder.apiCallAttemptTimeout(), "apiCallAttemptTimeout");
this.signer = builder.signer();
this.metricPublishers = Collections.unmodifiableList(new ArrayList<>(builder.metricPublishers()));
this.executionAttributes = ExecutionAttributes.unmodifiableExecutionAttributes(builder.executionAttributes());
this.endpointProvider = builder.endpointProvider();
this.compressionConfiguration = builder.compressionConfiguration();
this.plugins = Collections.unmodifiableList(new ArrayList<>(builder.plugins()));
}
/**
* Optional additional headers to be added to the HTTP request.
*
* @return The optional additional headers.
*/
public Map<String, List<String>> headers() {
return headers;
}
/**
* Optional additional query parameters to be added to the HTTP request.
*
* @return The optional additional query parameters.
*/
public Map<String, List<String>> rawQueryParameters() {
return rawQueryParameters;
}
/**
* The optional names of the higher level libraries that constructed the request.
*
* @return The names of the libraries.
*/
public List<ApiName> apiNames() {
return apiNames;
}
/**
* The amount of time to allow the client to complete the execution of an API call. This timeout covers the entire client
* execution except for marshalling. This includes request handler execution, all HTTP requests including retries,
* unmarshalling, etc. This value should always be positive, if present.
*
* <p>The api call timeout feature doesn't have strict guarantees on how quickly a request is aborted when the
* timeout is breached. The typical case aborts the request within a few milliseconds but there may occasionally be
* requests that don't get aborted until several seconds after the timer has been breached. Because of this, the client
* execution timeout feature should not be used when absolute precision is needed.
*
* <p>This may be used together with {@link #apiCallAttemptTimeout()} to enforce both a timeout on each individual HTTP
* request (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time).
*
* @see Builder#apiCallTimeout(Duration)
*/
public Optional<Duration> apiCallTimeout() {
return Optional.ofNullable(apiCallTimeout);
}
/**
* The amount of time to wait for the http request to complete before giving up and timing out. This value should always be
* positive, if present.
*
* <p>The request timeout feature doesn't have strict guarantees on how quickly a request is aborted when the timeout is
* breached. The typical case aborts the request within a few milliseconds but there may occasionally be requests that
* don't get aborted until several seconds after the timer has been breached. Because of this, the request timeout
* feature should not be used when absolute precision is needed.
*
* <p>This may be used together with {@link #apiCallTimeout()} to enforce both a timeout on each individual HTTP
* request
* (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time).
*
* @see Builder#apiCallAttemptTimeout(Duration)
*/
public Optional<Duration> apiCallAttemptTimeout() {
return Optional.ofNullable(apiCallAttemptTimeout);
}
/**
* @return the signer for signing the request. This signer get priority over the signer set on the client while
* signing the requests. If this value is not set, then the client level signer is used for signing the request.
*/
public Optional<Signer> signer() {
return Optional.ofNullable(signer);
}
/**
* Return the metric publishers for publishing the metrics collected for this request. This list supersedes the
* metric publishers set on the client.
*/
public List<MetricPublisher> metricPublishers() {
return metricPublishers;
}
/**
* Return the plugins that will be used to update the configuration used by the request.
*/
@SdkPreviewApi
public List<SdkPlugin> plugins() {
return plugins;
}
/**
* Returns the additional execution attributes to be added to this request.
* This collection of attributes is added in addition to the attributes set on the client.
* An attribute value added on the client within the collection of attributes is superseded by an
* attribute value added on the request.
*/
public ExecutionAttributes executionAttributes() {
return executionAttributes;
}
/**
* Returns the endpoint provider for resolving the endpoint for this request. This supersedes the
* endpoint provider set on the client.
*/
public Optional<EndpointProvider> endpointProvider() {
return Optional.ofNullable(endpointProvider);
}
/**
* Returns the compression configuration object, if present, which includes options to enable/disable compression and set
* the minimum compression threshold. This compression config object supersedes the compression config object set on the
* client.
*/
public Optional<CompressionConfiguration> compressionConfiguration() {
return Optional.ofNullable(compressionConfiguration);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RequestOverrideConfiguration that = (RequestOverrideConfiguration) o;
return Objects.equals(headers, that.headers) &&
Objects.equals(rawQueryParameters, that.rawQueryParameters) &&
Objects.equals(apiNames, that.apiNames) &&
Objects.equals(apiCallTimeout, that.apiCallTimeout) &&
Objects.equals(apiCallAttemptTimeout, that.apiCallAttemptTimeout) &&
Objects.equals(signer, that.signer) &&
Objects.equals(metricPublishers, that.metricPublishers) &&
Objects.equals(executionAttributes, that.executionAttributes) &&
Objects.equals(endpointProvider, that.endpointProvider) &&
Objects.equals(compressionConfiguration, that.compressionConfiguration) &&
Objects.equals(plugins, that.plugins);
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(headers);
hashCode = 31 * hashCode + Objects.hashCode(rawQueryParameters);
hashCode = 31 * hashCode + Objects.hashCode(apiNames);
hashCode = 31 * hashCode + Objects.hashCode(apiCallTimeout);
hashCode = 31 * hashCode + Objects.hashCode(apiCallAttemptTimeout);
hashCode = 31 * hashCode + Objects.hashCode(signer);
hashCode = 31 * hashCode + Objects.hashCode(metricPublishers);
hashCode = 31 * hashCode + Objects.hashCode(executionAttributes);
hashCode = 31 * hashCode + Objects.hashCode(endpointProvider);
hashCode = 31 * hashCode + Objects.hashCode(compressionConfiguration);
hashCode = 31 * hashCode + Objects.hashCode(plugins);
return hashCode;
}
/**
* Create a {@link Builder} initialized with the properties of this {@code SdkRequestOverrideConfiguration}.
*
* @return A new builder intialized with this config's properties.
*/
public abstract Builder<? extends Builder> toBuilder();
public interface Builder<B extends Builder> {
/**
* Optional additional headers to be added to the HTTP request.
*
* @return The optional additional headers.
*/
Map<String, List<String>> headers();
/**
* Add a single header to be set on the HTTP request.
* <p>
* This overrides any values for the given header set on the request by default by the SDK, as well as header
* overrides set at the client level using
* {@link software.amazon.awssdk.core.client.config.ClientOverrideConfiguration}.
*
* <p>
* This overrides any values already configured with this header name in the builder.
*
* @param name The name of the header.
* @param value The value of the header.
* @return This object for method chaining.
*/
default B putHeader(String name, String value) {
putHeader(name, Collections.singletonList(value));
return (B) this;
}
/**
* Add a single header with multiple values to be set on the HTTP request.
* <p>
* This overrides any values for the given header set on the request by default by the SDK, as well as header
* overrides set at the client level using
* {@link software.amazon.awssdk.core.client.config.ClientOverrideConfiguration}.
*
* <p>
* This overrides any values already configured with this header name in the builder.
*
* @param name The name of the header.
* @param values The values of the header.
* @return This object for method chaining.
*/
B putHeader(String name, List<String> values);
/**
* Add additional headers to be set on the HTTP request.
* <p>
* This overrides any values for the given headers set on the request by default by the SDK, as well as header
* overrides set at the client level using
* {@link software.amazon.awssdk.core.client.config.ClientOverrideConfiguration}.
*
* <p>
* This completely overrides any values currently configured in the builder.
*
* @param headers The set of additional headers.
* @return This object for method chaining.
*/
B headers(Map<String, List<String>> headers);
/**
* Optional additional query parameters to be added to the HTTP request.
*
* @return The optional additional query parameters.
*/
Map<String, List<String>> rawQueryParameters();
/**
* Add a single query parameter to be set on the HTTP request.
*
* <p>
* This overrides any values already configured with this query name in the builder.
*
* @param name The query parameter name.
* @param value The query parameter value.
* @return This object for method chaining.
*/
default B putRawQueryParameter(String name, String value) {
putRawQueryParameter(name, Collections.singletonList(value));
return (B) this;
}
/**
* Add a single query parameter with multiple values to be set on the HTTP request.
*
* <p>
* This overrides any values already configured with this query name in the builder.
*
* @param name The query parameter name.
* @param values The query parameter values.
* @return This object for method chaining.
*/
B putRawQueryParameter(String name, List<String> values);
/**
* Configure query parameters to be set on the HTTP request.
*
* <p>
* This completely overrides any query parameters currently configured in the builder.
*
* @param rawQueryParameters The set of additional query parameters.
* @return This object for method chaining.
*/
B rawQueryParameters(Map<String, List<String>> rawQueryParameters);
/**
* The optional names of the higher level libraries that constructed the request.
*
* @return The names of the libraries.
*/
List<ApiName> apiNames();
/**
* Set the optional name of the higher level library that constructed the request.
*
* @param apiName The name of the library.
*
* @return This object for method chaining.
*/
B addApiName(ApiName apiName);
/**
* Set the optional name of the higher level library that constructed the request.
*
* @param apiNameConsumer A {@link Consumer} that accepts a {@link ApiName.Builder}.
*
* @return This object for method chaining.
*/
B addApiName(Consumer<ApiName.Builder> apiNameConsumer);
/**
* Configure the amount of time to allow the client to complete the execution of an API call. This timeout covers the
* entire client execution except for marshalling. This includes request handler execution, all HTTP requests including
* retries, unmarshalling, etc. This value should always be positive, if present.
*
* <p>The api call timeout feature doesn't have strict guarantees on how quickly a request is aborted when the
* timeout is breached. The typical case aborts the request within a few milliseconds but there may occasionally be
* requests that don't get aborted until several seconds after the timer has been breached. Because of this, the client
* execution timeout feature should not be used when absolute precision is needed.
*
* <p>This may be used together with {@link #apiCallAttemptTimeout()} to enforce both a timeout on each individual HTTP
* request (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time).
*
* <p>
* Note that this timeout takes precedence over the value configured at client level via
* {@link ClientOverrideConfiguration.Builder#apiCallTimeout(Duration)}.
*
* @see RequestOverrideConfiguration#apiCallTimeout()
*/
B apiCallTimeout(Duration apiCallTimeout);
Duration apiCallTimeout();
/**
* Configure the amount of time to wait for the http request to complete before giving up and timing out. This value
* should always be positive, if present.
*
* <p>The request timeout feature doesn't have strict guarantees on how quickly a request is aborted when the timeout is
* breached. The typical case aborts the request within a few milliseconds but there may occasionally be requests that
* don't get aborted until several seconds after the timer has been breached. Because of this, the request timeout
* feature should not be used when absolute precision is needed.
*
* <p>This may be used together with {@link #apiCallTimeout()} to enforce both a timeout on each individual HTTP
* request (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time).
*
* <p>
* Note that this timeout takes precedence over the value configured at client level via
* {@link ClientOverrideConfiguration.Builder#apiCallAttemptTimeout(Duration)}.
*
* @see RequestOverrideConfiguration#apiCallAttemptTimeout()
*/
B apiCallAttemptTimeout(Duration apiCallAttemptTimeout);
Duration apiCallAttemptTimeout();
/**
* Sets the signer to use for signing the request. This signer get priority over the signer set on the client while
* signing the requests. If this value is null, then the client level signer is used for signing the request.
*
* @param signer Signer for signing the request
* @return This object for method chaining
*/
B signer(Signer signer);
Signer signer();
/**
* Sets the metric publishers for publishing the metrics collected for this request. This list supersedes
* the metric publisher set on the client.
*
* @param metricPublisher The list metric publisher for this request.
* @return This object for method chaining.
*/
B metricPublishers(List<MetricPublisher> metricPublisher);
/**
* Add a metric publisher to the existing list of previously set publishers to be used for publishing metrics
* for this request.
*
* @param metricPublisher The metric publisher to add.
*/
B addMetricPublisher(MetricPublisher metricPublisher);
List<MetricPublisher> metricPublishers();
/**
* Sets the additional execution attributes collection for this request.
* @param executionAttributes Execution attributes for this request
* @return This object for method chaining.
*/
B executionAttributes(ExecutionAttributes executionAttributes);
/**
* Add an execution attribute to the existing collection of execution attributes.
* @param attribute The execution attribute object
* @param value The value of the execution attribute.
*/
<T> B putExecutionAttribute(ExecutionAttribute<T> attribute, T value);
ExecutionAttributes executionAttributes();
/**
* Sets the endpointProvider to use for resolving the endpoint of the request. This endpointProvider gets priority
* over the endpointProvider set on the client while resolving the endpoint for the requests.
* If this value is null, then the client level endpointProvider is used for resolving the endpoint.
*
* @param endpointProvider Endpoint Provider that will override the resolving the endpoint for the request.
* @return This object for method chaining
*/
B endpointProvider(EndpointProvider endpointProvider);
EndpointProvider endpointProvider();
/**
* Sets the {@link CompressionConfiguration} for this request. The order of precedence, from highest to lowest,
* for this setting is: 1) Per request configuration 2) Client configuration 3) Environment variables 4) Profile setting.
*
* @param compressionConfiguration Request compression configuration object for this request.
*/
B compressionConfiguration(CompressionConfiguration compressionConfiguration);
/**
* Sets the {@link CompressionConfiguration} for this request. The order of precedence, from highest to lowest,
* for this setting is: 1) Per request configuration 2) Client configuration 3) Environment variables 4) Profile setting.
*
* @param compressionConfigurationConsumer A {@link Consumer} that accepts a {@link CompressionConfiguration.Builder}
*
* @return This object for method chaining
*/
B compressionConfiguration(Consumer<CompressionConfiguration.Builder> compressionConfigurationConsumer);
CompressionConfiguration compressionConfiguration();
/**
* Sets the plugins used to update the configuration used by this request.
*
* @param plugins The list of plugins for this request.
* @return This object for method chaining.
*/
@SdkPreviewApi
B plugins(List<SdkPlugin> plugins);
/**
* Add a plugin used to update the configuration used by this request.
*
* @param plugin The plugin to add.
*/
@SdkPreviewApi
B addPlugin(SdkPlugin plugin);
/**
* Returns the list of registered plugins
*/
@SdkPreviewApi
List<SdkPlugin> plugins();
/**
* Create a new {@code SdkRequestOverrideConfiguration} with the properties set on this builder.
*
* @return The new {@code SdkRequestOverrideConfiguration}.
*/
RequestOverrideConfiguration build();
}
protected abstract static class BuilderImpl<B extends Builder> implements Builder<B> {
private Map<String, List<String>> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
private Map<String, List<String>> rawQueryParameters = new HashMap<>();
private List<ApiName> apiNames = new ArrayList<>();
private Duration apiCallTimeout;
private Duration apiCallAttemptTimeout;
private Signer signer;
private List<MetricPublisher> metricPublishers = new ArrayList<>();
private ExecutionAttributes.Builder executionAttributesBuilder = ExecutionAttributes.builder();
private EndpointProvider endpointProvider;
private CompressionConfiguration compressionConfiguration;
private List<SdkPlugin> plugins = new ArrayList<>();
protected BuilderImpl() {
}
protected BuilderImpl(RequestOverrideConfiguration sdkRequestOverrideConfig) {
headers(sdkRequestOverrideConfig.headers);
rawQueryParameters(sdkRequestOverrideConfig.rawQueryParameters);
sdkRequestOverrideConfig.apiNames.forEach(this::addApiName);
apiCallTimeout(sdkRequestOverrideConfig.apiCallTimeout);
apiCallAttemptTimeout(sdkRequestOverrideConfig.apiCallAttemptTimeout);
signer(sdkRequestOverrideConfig.signer().orElse(null));
metricPublishers(sdkRequestOverrideConfig.metricPublishers());
executionAttributes(sdkRequestOverrideConfig.executionAttributes());
endpointProvider(sdkRequestOverrideConfig.endpointProvider);
compressionConfiguration(sdkRequestOverrideConfig.compressionConfiguration);
plugins(sdkRequestOverrideConfig.plugins);
}
@Override
public Map<String, List<String>> headers() {
return CollectionUtils.unmodifiableMapOfLists(headers);
}
@Override
public B putHeader(String name, List<String> values) {
Validate.paramNotNull(values, "values");
headers.put(name, new ArrayList<>(values));
return (B) this;
}
@Override
@SuppressWarnings("unchecked")
public B headers(Map<String, List<String>> headers) {
Validate.paramNotNull(headers, "headers");
this.headers = CollectionUtils.deepCopyMap(headers);
return (B) this;
}
@Override
public Map<String, List<String>> rawQueryParameters() {
return CollectionUtils.unmodifiableMapOfLists(rawQueryParameters);
}
@Override
public B putRawQueryParameter(String name, List<String> values) {
Validate.paramNotNull(name, "name");
Validate.paramNotNull(values, "values");
rawQueryParameters.put(name, new ArrayList<>(values));
return (B) this;
}
@Override
@SuppressWarnings("unchecked")
public B rawQueryParameters(Map<String, List<String>> rawQueryParameters) {
Validate.paramNotNull(rawQueryParameters, "rawQueryParameters");
this.rawQueryParameters = CollectionUtils.deepCopyMap(rawQueryParameters);
return (B) this;
}
@Override
public List<ApiName> apiNames() {
return Collections.unmodifiableList(apiNames);
}
@Override
@SuppressWarnings("unchecked")
public B addApiName(ApiName apiName) {
this.apiNames.add(apiName);
return (B) this;
}
@Override
@SuppressWarnings("unchecked")
public B addApiName(Consumer<ApiName.Builder> apiNameConsumer) {
ApiName.Builder b = ApiName.builder();
apiNameConsumer.accept(b);
addApiName(b.build());
return (B) this;
}
@Override
public B apiCallTimeout(Duration apiCallTimeout) {
this.apiCallTimeout = apiCallTimeout;
return (B) this;
}
public void setApiCallTimeout(Duration apiCallTimeout) {
apiCallTimeout(apiCallTimeout);
}
@Override
public Duration apiCallTimeout() {
return apiCallTimeout;
}
@Override
public B apiCallAttemptTimeout(Duration apiCallAttemptTimeout) {
this.apiCallAttemptTimeout = apiCallAttemptTimeout;
return (B) this;
}
public void setApiCallAttemptTimeout(Duration apiCallAttemptTimeout) {
apiCallAttemptTimeout(apiCallAttemptTimeout);
}
@Override
public Duration apiCallAttemptTimeout() {
return apiCallAttemptTimeout;
}
@Override
public B signer(Signer signer) {
this.signer = signer;
return (B) this;
}
public void setSigner(Signer signer) {
signer(signer);
}
@Override
public Signer signer() {
return signer;
}
@Override
public B metricPublishers(List<MetricPublisher> metricPublishers) {
Validate.paramNotNull(metricPublishers, "metricPublishers");
this.metricPublishers = new ArrayList<>(metricPublishers);
return (B) this;
}
@Override
public B addMetricPublisher(MetricPublisher metricPublisher) {
Validate.paramNotNull(metricPublisher, "metricPublisher");
this.metricPublishers.add(metricPublisher);
return (B) this;
}
public void setMetricPublishers(List<MetricPublisher> metricPublishers) {
metricPublishers(metricPublishers);
}
@Override
public List<MetricPublisher> metricPublishers() {
return metricPublishers;
}
@Override
public B executionAttributes(ExecutionAttributes executionAttributes) {
Validate.paramNotNull(executionAttributes, "executionAttributes");
this.executionAttributesBuilder = executionAttributes.toBuilder();
return (B) this;
}
@Override
public <T> B putExecutionAttribute(ExecutionAttribute<T> executionAttribute, T value) {
this.executionAttributesBuilder.put(executionAttribute, value);
return (B) this;
}
@Override
public ExecutionAttributes executionAttributes() {
return executionAttributesBuilder.build();
}
public void setExecutionAttributes(ExecutionAttributes executionAttributes) {
executionAttributes(executionAttributes);
}
@Override
public B endpointProvider(EndpointProvider endpointProvider) {
this.endpointProvider = endpointProvider;
return (B) this;
}
public void setEndpointProvider(EndpointProvider endpointProvider) {
endpointProvider(endpointProvider);
}
@Override
public EndpointProvider endpointProvider() {
return endpointProvider;
}
@Override
public B compressionConfiguration(CompressionConfiguration compressionConfiguration) {
this.compressionConfiguration = compressionConfiguration;
return (B) this;
}
@Override
public B compressionConfiguration(Consumer<CompressionConfiguration.Builder> compressionConfigurationConsumer) {
CompressionConfiguration.Builder b = CompressionConfiguration.builder();
compressionConfigurationConsumer.accept(b);
compressionConfiguration(b.build());
return (B) this;
}
@Override
public CompressionConfiguration compressionConfiguration() {
return compressionConfiguration;
}
@Override
public B plugins(List<SdkPlugin> plugins) {
this.plugins = new ArrayList<>(plugins);
return (B) this;
}
@Override
public B addPlugin(SdkPlugin plugin) {
this.plugins.add(plugin);
return (B) this;
}
@Override
public List<SdkPlugin> plugins() {
return Collections.unmodifiableList(plugins);
}
}
}
| 2,052 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkGlobalTime.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Used for clock skew adjustment between the client JVM where the SDK is run,
* and the server side.
*/
@SdkProtectedApi
public final class SdkGlobalTime {
/**
* globalTimeOffset is a time difference in seconds between the running JVM
* and AWS. Used to globally adjust the client clock skew. Java SDK already
* provides timeOffset and accessor methods in <code>Request</code> class but
* those are used per request, whereas this variable will adjust clock skew
* globally. Java SDK detects clock skew errors and adjusts global clock
* skew automatically.
*/
private static volatile int globalTimeOffset;
private SdkGlobalTime() {
}
/**
* Gets the global time difference in seconds between the running JVM and
* AWS. See <code>Request#getTimeOffset()</code> if global time offset is
* not set.
*/
public static int getGlobalTimeOffset() {
return globalTimeOffset;
}
/**
* Sets the global time difference in seconds between the running JVM and
* AWS. If this value is set then all the subsequent instantiation of an
* <code>AmazonHttpClient</code> will start using this
* value to generate timestamps.
*
* @param timeOffset
* the time difference in seconds between the running JVM and AWS
*/
public static void setGlobalTimeOffset(int timeOffset) {
globalTimeOffset = timeOffset;
}
}
| 2,053 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/RequestOption.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Client option defaults for individual {@link SdkRequest}s.
*/
@SdkProtectedApi
public final class RequestOption {
private RequestOption() {
}
}
| 2,054 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkPojo.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.util.List;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Interface to provide the list of {@link SdkField}s in a POJO. {@link SdkField} contains
* metadata about how a field should be marshalled/unmarshalled and allows for generic
* accessing/setting/creating of that field on an object.
*/
@SdkProtectedApi
public interface SdkPojo {
/**
* @return List of {@link SdkField} in this POJO. May be empty list but should never be null.
*/
List<SdkField<?>> sdkFields();
/**
* Indicates whether some other object is "equal to" this one by SDK fields.
* An SDK field is a modeled, non-inherited field in an {@link SdkPojo} class,
* and is generated based on a service model.
*
* <p>
* If an {@link SdkPojo} class does not have any inherited fields, {@code equalsBySdkFields}
* and {@code equals} are essentially the same.
*
* @param other the object to be compared with
* @return true if the other object equals to this object by sdk fields, false otherwise.
*/
default boolean equalsBySdkFields(Object other) {
throw new UnsupportedOperationException();
}
}
| 2,055 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/ApiName.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import static software.amazon.awssdk.utils.Validate.notNull;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* Encapsulates the API name and version of a library built using the AWS SDK.
*
* See {@link RequestOverrideConfiguration.Builder#addApiName(ApiName)}.
*/
@SdkPublicApi
public final class ApiName {
private final String name;
private final String version;
private ApiName(BuilderImpl b) {
this.name = notNull(b.name, "name must not be null");
this.version = notNull(b.version, "version must not be null");
}
public String name() {
return name;
}
public String version() {
return version;
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
/**
* Set the name of the API.
*
* @param name The name.
*
* @return This object for method chaining.
*/
Builder name(String name);
/**
* Set the version of the API.
*
* @param version The version.
*
* @return This object for method chaining.
*/
Builder version(String version);
ApiName build();
}
private static final class BuilderImpl implements Builder {
private String name;
private String version;
@Override
public Builder name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
name(name);
}
@Override
public Builder version(String version) {
this.version = version;
return this;
}
public void setVersion(String version) {
version(version);
}
@Override
public ApiName build() {
return new ApiName(this);
}
}
}
| 2,056 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkRequestOverrideConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* Base per-request override configuration for all SDK requests.
*/
@Immutable
@SdkPublicApi
public final class SdkRequestOverrideConfiguration extends RequestOverrideConfiguration {
private SdkRequestOverrideConfiguration(Builder builder) {
super(builder);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder extends RequestOverrideConfiguration.Builder<Builder> {
@Override
SdkRequestOverrideConfiguration build();
}
private static final class BuilderImpl extends RequestOverrideConfiguration.BuilderImpl<Builder> implements Builder {
private BuilderImpl() {
}
private BuilderImpl(SdkRequestOverrideConfiguration sdkRequestOverrideConfig) {
super(sdkRequestOverrideConfig);
}
@Override
public SdkRequestOverrideConfiguration build() {
return new SdkRequestOverrideConfiguration(this);
}
}
}
| 2,057 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkField.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.core.traits.DefaultValueTrait;
import software.amazon.awssdk.core.traits.LocationTrait;
import software.amazon.awssdk.core.traits.Trait;
/**
* Metadata about a member in an {@link SdkPojo}. Contains information about how to marshall/unmarshall.
*
* @param <TypeT> Java Type of member.
*/
@SdkProtectedApi
public final class SdkField<TypeT> {
private final String memberName;
private final MarshallingType<? super TypeT> marshallingType;
private final MarshallLocation location;
private final String locationName;
private final String unmarshallLocationName;
private final Supplier<SdkPojo> constructor;
private final BiConsumer<Object, TypeT> setter;
private final Function<Object, TypeT> getter;
private final Map<Class<? extends Trait>, Trait> traits;
private SdkField(Builder<TypeT> builder) {
this.memberName = builder.memberName;
this.marshallingType = builder.marshallingType;
this.traits = new HashMap<>(builder.traits);
this.constructor = builder.constructor;
this.setter = builder.setter;
this.getter = builder.getter;
// Eagerly dereference location trait since it's so commonly used.
LocationTrait locationTrait = getTrait(LocationTrait.class);
this.location = locationTrait.location();
this.locationName = locationTrait.locationName();
this.unmarshallLocationName = locationTrait.unmarshallLocationName();
}
public String memberName() {
return memberName;
}
/**
* @return MarshallingType of member. Used primarily for marshaller/unmarshaller lookups.
*/
public MarshallingType<? super TypeT> marshallingType() {
return marshallingType;
}
/**
* @return Location the member should be marshalled into (i.e. headers/query/path/payload).
*/
public MarshallLocation location() {
return location;
}
/**
* @return The location name to use when marshalling. I.E. the field name of the JSON document, or the header name, etc.
*/
public String locationName() {
return locationName;
}
/**
* @return The location name to use when unmarshalling. This is only needed for AWS/Query or EC2 services. All
* other services should use {@link #locationName} for both marshalling and unmarshalling.
*/
public String unmarshallLocationName() {
return unmarshallLocationName;
}
public Supplier<SdkPojo> constructor() {
return constructor;
}
/**
* Gets the trait of the specified class if available.
*
* @param clzz Trait class to get.
* @param <T> Type of trait.
* @return Trait instance or null if trait is not present.
*/
@SuppressWarnings("unchecked")
public <T extends Trait> T getTrait(Class<T> clzz) {
return (T) traits.get(clzz);
}
/**
* Gets the trait of the specified class if available.
*
* @param clzz Trait class to get.
* @param <T> Type of trait.
* @return Optional of trait instance.
*/
@SuppressWarnings("unchecked")
public <T extends Trait> Optional<T> getOptionalTrait(Class<T> clzz) {
return Optional.ofNullable((T) traits.get(clzz));
}
/**
* Gets the trait of the specified class, or throw {@link IllegalStateException} if not available.
*
* @param clzz Trait class to get.
* @param <T> Type of trait.
* @return Trait instance.
* @throws IllegalStateException if trait is not present.
*/
@SuppressWarnings("unchecked")
public <T extends Trait> T getRequiredTrait(Class<T> clzz) throws IllegalStateException {
T trait = (T) traits.get(clzz);
if (trait == null) {
throw new IllegalStateException(memberName + " member is missing " + clzz.getSimpleName());
}
return trait;
}
/**
* Checks if a given {@link Trait} is present on the field.
*
* @param clzz Trait class to check.
* @return True if trait is present, false if not.
*/
public boolean containsTrait(Class<? extends Trait> clzz) {
return traits.containsKey(clzz);
}
/**
* Retrieves the current value of 'this' field from the given POJO. Uses the getter passed into the {@link Builder}.
*
* @param pojo POJO to retrieve value from.
* @return Current value of 'this' field in the POJO.
*/
private TypeT get(Object pojo) {
return getter.apply(pojo);
}
/**
* Retrieves the current value of 'this' field from the given POJO. Uses the getter passed into the {@link Builder}. If the
* current value is null this method will look for the {@link DefaultValueTrait} on the field and attempt to resolve a default
* value. If the {@link DefaultValueTrait} is not present this just returns null.
*
* @param pojo POJO to retrieve value from.
* @return Current value of 'this' field in the POJO or default value if current value is null.
*/
public TypeT getValueOrDefault(Object pojo) {
TypeT val = this.get(pojo);
DefaultValueTrait trait = getTrait(DefaultValueTrait.class);
return (trait == null ? val : (TypeT) trait.resolveValue(val));
}
/**
* Sets the given value on the POJO via the setter passed into the {@link Builder}.
*
* @param pojo POJO containing field to set.
* @param val Value of field.
*/
@SuppressWarnings("unchecked")
public void set(Object pojo, Object val) {
setter.accept(pojo, (TypeT) val);
}
/**
* Creates a new instance of {@link Builder} bound to the specified type.
*
* @param marshallingType Type of field.
* @param <TypeT> Type of field. Must be a subtype of the {@link MarshallingType} type param.
* @return New builder instance.
*/
public static <TypeT> Builder<TypeT> builder(MarshallingType<? super TypeT> marshallingType) {
return new Builder<>(marshallingType);
}
/**
* Builder for {@link SdkField}.
*
* @param <TypeT> Java type of field.
*/
public static final class Builder<TypeT> {
private final MarshallingType<? super TypeT> marshallingType;
private String memberName;
private Supplier<SdkPojo> constructor;
private BiConsumer<Object, TypeT> setter;
private Function<Object, TypeT> getter;
private final Map<Class<? extends Trait>, Trait> traits = new HashMap<>();
private Builder(MarshallingType<? super TypeT> marshallingType) {
this.marshallingType = marshallingType;
}
public Builder<TypeT> memberName(String memberName) {
this.memberName = memberName;
return this;
}
/**
* Sets a {@link Supplier} which will create a new <b>MUTABLE</b> instance of the POJO. I.E. this will
* create the Builder for a given POJO and not the immutable POJO itself.
*
* @param constructor Supplier method to create the mutable POJO.
* @return This object for method chaining.
*/
public Builder<TypeT> constructor(Supplier<SdkPojo> constructor) {
this.constructor = constructor;
return this;
}
/**
* Sets the {@link BiConsumer} which will accept an object and a value and set that value on the appropriate
* member of the object. This requires a <b>MUTABLE</b> pojo so thus this setter will be on the Builder
* for the given POJO.
*
* @param setter Setter method.
* @return This object for method chaining.
*/
public Builder<TypeT> setter(BiConsumer<Object, TypeT> setter) {
this.setter = setter;
return this;
}
/**
* Sets the {@link Function} that will accept an object and return the current value of 'this' field on that object.
* This will typically be a getter on the immutable representation of the POJO and is used mostly during marshalling.
*
* @param getter Getter method.
* @return This object for method chaining.
*/
public Builder<TypeT> getter(Function<Object, TypeT> getter) {
this.getter = getter;
return this;
}
/**
* Attaches one or more traits to the {@link SdkField}. Traits can have additional metadata and behavior that
* influence how a field is marshalled/unmarshalled.
*
* @param traits Traits to attach.
* @return This object for method chaining.
*/
public Builder<TypeT> traits(Trait... traits) {
Arrays.stream(traits).forEach(t -> this.traits.put(t.getClass(), t));
return this;
}
/**
* @return An immutable {@link SdkField}.
*/
public SdkField<TypeT> build() {
return new SdkField<>(this);
}
}
}
| 2,058 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/ClientType.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* Enum that represents the type of client being used.
*/
@SdkPublicApi
public enum ClientType {
ASYNC("Async"),
SYNC("Sync"),
UNKNOWN("Unknown");
private final String clientType;
ClientType(String clientType) {
this.clientType = clientType;
}
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return clientType;
}
}
| 2,059 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkServiceClientConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.net.URI;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.endpoints.EndpointProvider;
import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme;
/**
* Class to expose SDK service client settings to the user, e.g., ClientOverrideConfiguration
*/
@SdkPublicApi
public abstract class SdkServiceClientConfiguration {
private final ClientOverrideConfiguration overrideConfiguration;
private final URI endpointOverride;
private final EndpointProvider endpointProvider;
private final Map<String, AuthScheme<?>> authSchemes;
protected SdkServiceClientConfiguration(Builder builder) {
this.overrideConfiguration = builder.overrideConfiguration();
this.endpointOverride = builder.endpointOverride();
this.endpointProvider = builder.endpointProvider();
this.authSchemes = builder.authSchemes();
}
/**
*
* @return The ClientOverrideConfiguration of the SdkClient. If this is not set, an ClientOverrideConfiguration object will
* still be returned, with empty fields
*/
public ClientOverrideConfiguration overrideConfiguration() {
return this.overrideConfiguration;
}
/**
*
* @return The configured endpoint override of the SdkClient. If the endpoint was not overridden, an empty Optional will be
* returned
*/
public Optional<URI> endpointOverride() {
return Optional.ofNullable(this.endpointOverride);
}
/**
*
* @return The configured endpoint provider of the SdkClient. If the endpoint provider was not configured, the default
* endpoint provider will be returned.
*/
public Optional<EndpointProvider> endpointProvider() {
return Optional.ofNullable(this.endpointProvider);
}
/**
* @return The configured map of auth schemes.
*/
public Map<String, AuthScheme<?>> authSchemes() {
return authSchemes;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SdkServiceClientConfiguration serviceClientConfiguration = (SdkServiceClientConfiguration) o;
return Objects.equals(overrideConfiguration, serviceClientConfiguration.overrideConfiguration())
&& Objects.equals(endpointOverride, serviceClientConfiguration.endpointOverride().orElse(null))
&& Objects.equals(endpointProvider, serviceClientConfiguration.endpointProvider().orElse(null))
&& Objects.equals(authSchemes, serviceClientConfiguration.authSchemes);
}
@Override
public int hashCode() {
int result = overrideConfiguration != null ? overrideConfiguration.hashCode() : 0;
result = 31 * result + (endpointOverride != null ? endpointOverride.hashCode() : 0);
result = 31 * result + (endpointProvider != null ? endpointProvider.hashCode() : 0);
result = 31 * result + (authSchemes != null ? authSchemes.hashCode() : 0);
return result;
}
/**
* The base interface for all SDK service client configuration builders
*/
public interface Builder {
/**
* Return the client override configuration
*/
default ClientOverrideConfiguration overrideConfiguration() {
throw new UnsupportedOperationException();
}
/**
* Return the endpoint override
*/
default URI endpointOverride() {
throw new UnsupportedOperationException();
}
default EndpointProvider endpointProvider() {
throw new UnsupportedOperationException();
}
/**
* Configure the client override configuration
*/
default Builder overrideConfiguration(ClientOverrideConfiguration clientOverrideConfiguration) {
throw new UnsupportedOperationException();
}
default Builder overrideConfiguration(Consumer<ClientOverrideConfiguration.Builder> consumer) {
ClientOverrideConfiguration overrideConfiguration = overrideConfiguration();
ClientOverrideConfiguration.Builder builder;
if (overrideConfiguration != null) {
builder = overrideConfiguration.toBuilder();
} else {
builder = ClientOverrideConfiguration.builder();
}
consumer.accept(builder);
return overrideConfiguration(builder.build());
}
/**
* Configure the endpoint override
*/
default Builder endpointOverride(URI endpointOverride) {
throw new UnsupportedOperationException();
}
default Builder endpointProvider(EndpointProvider endpointProvider) {
throw new UnsupportedOperationException();
}
/**
* Adds the given auth scheme. Replaces an existing auth scheme with the same id.
*/
default Builder putAuthScheme(AuthScheme<?> authScheme) {
throw new UnsupportedOperationException();
}
/**
* Returns the configured map of auth schemes.
*/
default Map<String, AuthScheme<?>> authSchemes() {
throw new UnsupportedOperationException();
}
/**
* Build the service client configuration using the configuration on this builder
*/
SdkServiceClientConfiguration build();
}
}
| 2,060 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/BytesWrapper.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.Arrays;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
/**
* A base class for {@link SdkBytes} and {@link ResponseBytes} that enables retrieving an underlying byte array as multiple
* different types, like a byte buffer (via {@link #asByteBuffer()}, or a string (via {@link #asUtf8String()}.
*/
@SdkPublicApi
public abstract class BytesWrapper {
private final byte[] bytes;
// Needed for serialization
@SdkInternalApi
BytesWrapper() {
this(new byte[0]);
}
@SdkInternalApi
BytesWrapper(byte[] bytes) {
this.bytes = Validate.paramNotNull(bytes, "bytes");
}
/**
* @return The output as a read-only byte buffer.
*/
public final ByteBuffer asByteBuffer() {
return ByteBuffer.wrap(bytes).asReadOnlyBuffer();
}
/**
* @return A copy of the output as a byte array.
* @see #asByteBuffer() to prevent creating an additional array copy.
*/
public final byte[] asByteArray() {
return Arrays.copyOf(bytes, bytes.length);
}
/**
* @return The output as a byte array. This <b>does not</b> create a copy of the underlying byte array. This introduces
* concurrency risks, allowing: (1) the caller to modify the byte array stored in this object implementation AND
* (2) the original creator of this object, if they created it using the unsafe method.
*
* <p>Consider using {@link #asByteBuffer()}, which is a safer method to avoid an additional array copy because it does not
* provide a way to modify the underlying buffer. As the method name implies, this is unsafe. If you're not sure, don't use
* this. The only guarantees given to the user of this method is that the SDK itself won't modify the underlying byte
* array.</p>
*
* @see #asByteBuffer() to prevent creating an additional array copy safely.
*/
public final byte[] asByteArrayUnsafe() {
return bytes;
}
/**
* Retrieve the output as a string.
*
* @param charset The charset of the string.
* @return The output as a string.
* @throws UncheckedIOException with a {@link CharacterCodingException} as the cause if the bytes cannot be encoded using the
* provided charset
*/
public final String asString(Charset charset) throws UncheckedIOException {
return StringUtils.fromBytes(bytes, charset);
}
/**
* @return The output as a utf-8 encoded string.
* @throws UncheckedIOException with a {@link CharacterCodingException} as the cause if the bytes cannot be encoded as UTF-8.
*/
public final String asUtf8String() throws UncheckedIOException {
return asString(UTF_8);
}
/**
* @return The output as an input stream. This stream will not need to be closed.
*/
public final InputStream asInputStream() {
return new ByteArrayInputStream(bytes);
}
/**
* @return The output as a {@link ContentStreamProvider}.
*/
public final ContentStreamProvider asContentStreamProvider() {
return this::asInputStream;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BytesWrapper sdkBytes = (BytesWrapper) o;
return Arrays.equals(bytes, sdkBytes.bytes);
}
@Override
public int hashCode() {
return Arrays.hashCode(bytes);
}
}
| 2,061 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkPojoBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.Buildable;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A builder for an immutable {@link SdkPojo} with no fields.
*
* <p>
* This is useful for {@code SdkPojo} implementations that don't have their own builders, but need to be passed to something
* that assumes they already have a builder. For example, marshallers expect all {@code SdkPojo} implementations to have a
* builder. In the cases that they do not, this can be used as their builder.
*
* <p>
* This currently only supports {@code SdkPojo}s without any fields (because it has no way to set them). It also does not support
* {@code SdkPojo}s that already have or are a builder (that builder should be used instead).
*/
@SdkProtectedApi
public final class SdkPojoBuilder<T extends SdkPojo> implements SdkPojo, Buildable {
private final T delegate;
public SdkPojoBuilder(T delegate) {
Validate.isTrue(delegate.sdkFields().isEmpty(), "Delegate must be empty.");
Validate.isTrue(!(delegate instanceof ToCopyableBuilder), "Delegate already has a builder.");
Validate.isTrue(!(delegate instanceof Buildable), "Delegate is already a builder.");
this.delegate = delegate;
}
@Override
public List<SdkField<?>> sdkFields() {
return Collections.emptyList();
}
@Override
public boolean equalsBySdkFields(Object other) {
return delegate.equalsBySdkFields(other);
}
@Override
public T build() {
return delegate;
}
}
| 2,062 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/HttpChecksumConstant.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.internal.signer.SigningMethod;
/**
* Defines all the constants that are used while adding and validating Http checksum for an operation.
*/
@SdkInternalApi
public final class HttpChecksumConstant {
public static final String HTTP_CHECKSUM_HEADER_PREFIX = "x-amz-checksum";
public static final String X_AMZ_TRAILER = "x-amz-trailer";
public static final String CONTENT_SHA_256_FOR_UNSIGNED_TRAILER = "STREAMING-UNSIGNED-PAYLOAD-TRAILER";
public static final String AWS_CHUNKED_HEADER = "aws-chunked";
public static final ExecutionAttribute<String> HTTP_CHECKSUM_VALUE =
new ExecutionAttribute<>("HttpChecksumValue");
public static final ExecutionAttribute<SigningMethod> SIGNING_METHOD =
new ExecutionAttribute<>("SigningMethod");
public static final String HEADER_FOR_TRAILER_REFERENCE = "x-amz-trailer";
/**
* Default chunk size for Async trailer based checksum data transfer*
*/
public static final int DEFAULT_ASYNC_CHUNK_SIZE = 16 * 1024;
private HttpChecksumConstant() {
}
}
| 2,063 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkProtocolMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Interface to hold protocol-specific information.
*/
@SdkProtectedApi
public interface SdkProtocolMetadata {
String serviceProtocol();
}
| 2,064 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* All SDK service client interfaces should extend this interface.
*/
@SdkPublicApi
@ThreadSafe
public interface SdkClient extends SdkAutoCloseable {
/**
* The name of the service.
*
* @return name for this service.
*/
String serviceName();
/**
* The SDK service client configuration exposes client settings to the user, e.g., ClientOverrideConfiguration
*
* @return SdkServiceClientConfiguration
*/
default SdkServiceClientConfiguration serviceClientConfiguration() {
throw new UnsupportedOperationException();
}
}
| 2,065 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/metrics/CoreMetric.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.metrics;
import java.net.URI;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.metrics.MetricCategory;
import software.amazon.awssdk.metrics.MetricLevel;
import software.amazon.awssdk.metrics.SdkMetric;
@SdkPublicApi
public final class CoreMetric {
/**
* The unique ID for the service. This is present for all API call metrics.
*/
public static final SdkMetric<String> SERVICE_ID =
metric("ServiceId", String.class, MetricLevel.ERROR);
/**
* The name of the service operation being invoked. This is present for all
* API call metrics.
*/
public static final SdkMetric<String> OPERATION_NAME =
metric("OperationName", String.class, MetricLevel.ERROR);
/**
* True if the API call succeeded, false otherwise.
*/
public static final SdkMetric<Boolean> API_CALL_SUCCESSFUL =
metric("ApiCallSuccessful", Boolean.class, MetricLevel.ERROR);
/**
* The number of retries that the SDK performed in the execution of the request. 0 implies that the request worked the first
* time, and no retries were attempted.
*/
public static final SdkMetric<Integer> RETRY_COUNT =
metric("RetryCount", Integer.class, MetricLevel.ERROR);
/**
* The endpoint for the service.
*/
public static final SdkMetric<URI> SERVICE_ENDPOINT =
metric("ServiceEndpoint", URI.class, MetricLevel.ERROR);
/**
* The duration of the API call. This includes all call attempts made.
*
* <p>{@code API_CALL_DURATION ~= CREDENTIALS_FETCH_DURATION + MARSHALLING_DURATION + SUM_ALL(BACKOFF_DELAY_DURATION) +
* SUM_ALL(SIGNING_DURATION) + SUM_ALL(SERVICE_CALL_DURATION) + SUM_ALL(UNMARSHALLING_DURATION)}
*/
public static final SdkMetric<Duration> API_CALL_DURATION =
metric("ApiCallDuration", Duration.class, MetricLevel.INFO);
/**
* The duration of time taken to fetch signing credentials for the API call.
*/
public static final SdkMetric<Duration> CREDENTIALS_FETCH_DURATION =
metric("CredentialsFetchDuration", Duration.class, MetricLevel.INFO);
/**
* The duration of time taken to fetch signing credentials for the API call.
*/
public static final SdkMetric<Duration> TOKEN_FETCH_DURATION =
metric("TokenFetchDuration", Duration.class, MetricLevel.INFO);
/**
* The duration of time that the SDK has waited before this API call attempt, based on the
* {@link RetryPolicy#backoffStrategy()}.
*/
public static final SdkMetric<Duration> BACKOFF_DELAY_DURATION =
metric("BackoffDelayDuration", Duration.class, MetricLevel.INFO);
/**
* The duration of time taken to marshall the SDK request to an HTTP request.
*/
public static final SdkMetric<Duration> MARSHALLING_DURATION =
metric("MarshallingDuration", Duration.class, MetricLevel.INFO);
/**
* The duration of time taken to sign the HTTP request.
*/
public static final SdkMetric<Duration> SIGNING_DURATION =
metric("SigningDuration", Duration.class, MetricLevel.INFO);
/**
* The duration of time taken to connect to the service (or acquire a connection from the connection pool), send the
* serialized request and receive the initial response (e.g. HTTP status code and headers). This DOES NOT include the time
* taken to read the entire response from the service.
*/
public static final SdkMetric<Duration> SERVICE_CALL_DURATION =
metric("ServiceCallDuration", Duration.class, MetricLevel.INFO);
/**
* The duration of time taken to unmarshall the HTTP response to an SDK response.
*
* <p>Note: For streaming operations, this does not include the time to read the response payload.
*/
public static final SdkMetric<Duration> UNMARSHALLING_DURATION =
metric("UnmarshallingDuration", Duration.class, MetricLevel.INFO);
/**
* The request ID of the service request.
*/
public static final SdkMetric<String> AWS_REQUEST_ID =
metric("AwsRequestId", String.class, MetricLevel.INFO);
/**
* The extended request ID of the service request.
*/
public static final SdkMetric<String> AWS_EXTENDED_REQUEST_ID =
metric("AwsExtendedRequestId", String.class, MetricLevel.INFO);
/**
* The type of error that occurred for a call attempt.
* <p>
* The following are possible values:
* <ul>
* <li>Throttling - The service responded with a throttling error.</li>
* <li>ServerError - The service responded with an error other than throttling.</li>
* <li>ClientTimeout - A client timeout occurred, either at the API call level, or API call attempt level.</li>
* <li>IO - An I/O error occurred.</li>
* <li>Other - Catch-all for other errors that don't fall into the above categories.</li>
* </ul>
* <p>
*/
public static final SdkMetric<String> ERROR_TYPE =
metric("ErrorType", String.class, MetricLevel.INFO);
private CoreMetric() {
}
private static <T> SdkMetric<T> metric(String name, Class<T> clzz, MetricLevel level) {
return SdkMetric.create(name, clzz, level, MetricCategory.CORE);
}
}
| 2,066 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/signer/AsyncRequestBodySigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.signer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Interface for the signer used for signing the async requests.
*/
@SdkPublicApi
@FunctionalInterface
public interface AsyncRequestBodySigner {
/**
* Method that takes in an signed request and async request body provider,
* and returns a transformed version the request body provider.
*
* @param request The signed request (with Authentication header)
* @param asyncRequestBody Data publisher of the request body
* @param executionAttributes Contains the attributes required for signing the request
* @return The transformed request body provider (with singing operator)
*/
AsyncRequestBody signAsyncRequestBody(SdkHttpFullRequest request, AsyncRequestBody asyncRequestBody,
ExecutionAttributes executionAttributes);
}
| 2,067 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/signer/AsyncSigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.signer;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* A signer capable of including the contents of the asynchronous body into the request calculation.
*/
@SdkPublicApi
public interface AsyncSigner {
/**
* Sign the request, including the contents of the body into the signature calculation.
*
* @param request The HTTP request.
* @param requestBody The body of the request.
* @param executionAttributes The execution attributes that contains information information used to sign the
* request.
* @return A future containing the signed request.
*/
CompletableFuture<SdkHttpFullRequest> sign(SdkHttpFullRequest request, AsyncRequestBody requestBody,
ExecutionAttributes executionAttributes);
}
| 2,068 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/signer/Presigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.signer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Interface for the signer used for pre-signing the requests. All SDK signer implementations that support pre-signing
* will implement this interface.
*/
@SdkPublicApi
@FunctionalInterface
public interface Presigner {
/**
* Method that takes in an request and returns a pre signed version of the request.
*
* @param request The request to presign
* @param executionAttributes Contains the attributes required for pre signing the request
* @return A pre signed version of the input request
*/
SdkHttpFullRequest presign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes);
}
| 2,069 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/signer/NoOpSigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.signer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* A No op implementation of Signer and Presigner interfaces that returns the
* input {@link SdkHttpFullRequest} without modifications.
*/
@SdkPublicApi
public final class NoOpSigner implements Signer, Presigner {
@Override
public SdkHttpFullRequest presign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
return request;
}
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
return request;
}
}
| 2,070 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/signer/Signer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.signer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.CredentialType;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Interface for the signer used for signing the requests. All SDK signer implementations will implement this interface.
*/
@SdkPublicApi
@FunctionalInterface
public interface Signer {
/**
* Method that takes in an request and returns a signed version of the request.
*
* @param request The request to sign
* @param executionAttributes Contains the attributes required for signing the request
* @return A signed version of the input request
*/
SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes);
/**
* Method that retrieves {@link CredentialType} i.e. the type of Credentials used by the Signer while authorizing a request.
*
* @return null by default else return {@link CredentialType} as defined by the signer implementation.
*/
default CredentialType credentialType() {
return null;
}
}
| 2,071 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/async/PaginationSubscription.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.async;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public abstract class PaginationSubscription<ResponseT> implements Subscription {
protected AtomicLong outstandingRequests = new AtomicLong(0);
protected final Subscriber subscriber;
protected final AsyncPageFetcher<ResponseT> nextPageFetcher;
protected volatile ResponseT currentPage;
// boolean indicating whether subscription is terminated
private AtomicBoolean isTerminated = new AtomicBoolean(false);
// boolean indicating whether task to handle requests is running
private AtomicBoolean isTaskRunning = new AtomicBoolean(false);
protected PaginationSubscription(BuilderImpl builder) {
this.subscriber = builder.subscriber;
this.nextPageFetcher = builder.nextPageFetcher;
}
@Override
public void request(long n) {
if (isTerminated()) {
return;
}
if (n <= 0) {
subscriber.onError(new IllegalArgumentException("Non-positive request signals are illegal"));
}
AtomicBoolean startTask = new AtomicBoolean(false);
synchronized (this) {
outstandingRequests.addAndGet(n);
startTask.set(startTask());
}
if (startTask.get()) {
handleRequests();
}
}
/**
* Recursive method to deal with requests until there are no outstandingRequests or
* no more pages.
*/
protected abstract void handleRequests();
@Override
public void cancel() {
cleanup();
}
protected boolean hasNextPage() {
return currentPage == null || nextPageFetcher.hasNextPage(currentPage);
}
protected void completeSubscription() {
if (!isTerminated()) {
subscriber.onComplete();
cleanup();
}
}
private void terminate() {
isTerminated.compareAndSet(false, true);
}
protected boolean isTerminated() {
return isTerminated.get();
}
protected void stopTask() {
isTaskRunning.set(false);
}
private synchronized boolean startTask() {
return !isTerminated() && isTaskRunning.compareAndSet(false, true);
}
protected synchronized void cleanup() {
terminate();
stopTask();
}
public interface Builder<TypeToBuildT extends PaginationSubscription, BuilderT extends Builder> {
BuilderT subscriber(Subscriber subscriber);
BuilderT nextPageFetcher(AsyncPageFetcher nextPageFetcher);
TypeToBuildT build();
}
protected abstract static class BuilderImpl<TypeToBuildT extends PaginationSubscription, BuilderT extends Builder>
implements Builder<TypeToBuildT, BuilderT> {
private Subscriber subscriber;
private AsyncPageFetcher nextPageFetcher;
@Override
public BuilderT subscriber(Subscriber subscriber) {
this.subscriber = subscriber;
return (BuilderT) this;
}
@Override
public BuilderT nextPageFetcher(AsyncPageFetcher nextPageFetcher) {
this.nextPageFetcher = nextPageFetcher;
return (BuilderT) this;
}
}
}
| 2,072 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/async/EmptySubscription.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.async;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A NoOp implementation of {@link Subscription} interface.
*
* This subscription calls {@link Subscriber#onComplete()} on first request for data and then terminates the subscription.
*/
@SdkProtectedApi
public final class EmptySubscription implements Subscription {
private final AtomicBoolean isTerminated = new AtomicBoolean(false);
private final Subscriber subscriber;
public EmptySubscription(Subscriber subscriber) {
this.subscriber = subscriber;
}
@Override
public void request(long n) {
if (isTerminated()) {
return;
}
if (n <= 0) {
throw new IllegalArgumentException("Non-positive request signals are illegal");
}
if (terminate()) {
subscriber.onComplete();
}
}
@Override
public void cancel() {
terminate();
}
private boolean terminate() {
return isTerminated.compareAndSet(false, true);
}
private boolean isTerminated() {
return isTerminated.get();
}
}
| 2,073 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/async/ResponsesSubscription.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.async;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* An implementation of the {@link Subscription} interface that can be used to signal and cancel demand for
* paginated response pages.
*
* @param <ResponseT> The type of a single response page
*/
@SdkProtectedApi
public final class ResponsesSubscription<ResponseT> extends PaginationSubscription<ResponseT> {
private ResponsesSubscription(BuilderImpl builder) {
super(builder);
}
/**
* Create a builder for creating a {@link ResponsesSubscription}.
*/
public static Builder builder() {
return new BuilderImpl();
}
@Override
protected void handleRequests() {
if (!hasNextPage()) {
completeSubscription();
return;
}
synchronized (this) {
if (outstandingRequests.get() <= 0) {
stopTask();
return;
}
}
if (!isTerminated()) {
outstandingRequests.getAndDecrement();
nextPageFetcher.nextPage(currentPage)
.whenComplete(((response, error) -> {
if (response != null) {
currentPage = response;
subscriber.onNext(response);
handleRequests();
}
if (error != null) {
subscriber.onError(error);
cleanup();
}
}));
}
}
public interface Builder extends PaginationSubscription.Builder<ResponsesSubscription, Builder> {
@Override
ResponsesSubscription build();
}
private static final class BuilderImpl extends PaginationSubscription.BuilderImpl<ResponsesSubscription, Builder>
implements Builder {
@Override
public ResponsesSubscription build() {
return new ResponsesSubscription(this);
}
}
}
| 2,074 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/async/PaginatedItemsPublisher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.async;
import java.util.Iterator;
import java.util.function.Function;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.internal.pagination.async.ItemsSubscription;
/**
* A publisher to request for a stream of paginated items. The class can be used to request data for paginated items
* across multiple pages.
*
* @param <ResponseT> The type of a single response page
* @param <ItemT> The type of paginated member in a response page
*/
@SdkProtectedApi
public final class PaginatedItemsPublisher<ResponseT, ItemT> implements SdkPublisher<ItemT> {
private final AsyncPageFetcher<ResponseT> nextPageFetcher;
private final Function<ResponseT, Iterator<ItemT>> getIteratorFunction;
private final boolean isLastPage;
private PaginatedItemsPublisher(BuilderImpl builder) {
this.nextPageFetcher = builder.nextPageFetcher;
this.getIteratorFunction = builder.iteratorFunction;
this.isLastPage = builder.isLastPage;
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public void subscribe(Subscriber<? super ItemT> subscriber) {
subscriber.onSubscribe(isLastPage ? new EmptySubscription(subscriber)
: ItemsSubscription.builder()
.subscriber(subscriber)
.nextPageFetcher(nextPageFetcher)
.iteratorFunction(getIteratorFunction)
.build());
}
public interface Builder {
Builder nextPageFetcher(AsyncPageFetcher nextPageFetcher);
Builder iteratorFunction(Function iteratorFunction);
Builder isLastPage(boolean isLastPage);
PaginatedItemsPublisher build();
}
private static final class BuilderImpl implements Builder {
private AsyncPageFetcher nextPageFetcher;
private Function iteratorFunction;
private boolean isLastPage;
@Override
public Builder nextPageFetcher(AsyncPageFetcher nextPageFetcher) {
this.nextPageFetcher = nextPageFetcher;
return this;
}
@Override
public Builder iteratorFunction(Function iteratorFunction) {
this.iteratorFunction = iteratorFunction;
return this;
}
@Override
public Builder isLastPage(boolean isLastPage) {
this.isLastPage = isLastPage;
return this;
}
@Override
public PaginatedItemsPublisher build() {
return new PaginatedItemsPublisher(this);
}
}
}
| 2,075 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/async/AsyncPageFetcher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.async;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Interface to deal with async paginated responses.
* @param <ResponseT> Type of Response
*/
@SdkProtectedApi
public interface AsyncPageFetcher<ResponseT> {
/**
* Returns a boolean value indicating if a next page is available.
*
* @param oldPage last page sent by service in a paginated operation
* @return True if there is a next page available. Otherwise false.
*/
boolean hasNextPage(ResponseT oldPage);
/**
* Method that uses the information in #oldPage and returns a
* completable future for the next page. This method makes service calls.
*
* @param oldPage last page sent by service in a paginated operation
* @return A CompletableFuture that can be used to get the next response page
*/
CompletableFuture<ResponseT> nextPage(ResponseT oldPage);
}
| 2,076 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/sync/SyncPageFetcher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.sync;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public interface SyncPageFetcher<ResponseT> {
/**
* Returns a boolean value indicating if a next page is available.
*
* @param oldPage last page sent by service in a paginated operation
* @return True if there is a next page available. Otherwise false.
*/
boolean hasNextPage(ResponseT oldPage);
/**
* Method that uses the information in #oldPage and returns the
* next page if available by making a service call.
*
* @param oldPage last page sent by service in a paginated operation
* @return the next page if available. Otherwise returns null.
*/
ResponseT nextPage(ResponseT oldPage);
}
| 2,077 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/sync/PaginatedItemsIterable.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.sync;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Iterable for the paginated items. This class can be used through iterate through
* all the items across multiple pages until there is no more response from the service.
*
* @param <ResponseT> The type of a single response page
* @param <ItemT> The type of paginated member in a response page
*/
@SdkProtectedApi
public final class PaginatedItemsIterable<ResponseT, ItemT> implements SdkIterable<ItemT> {
private final SdkIterable<ResponseT> pagesIterable;
private final Function<ResponseT, Iterator<ItemT>> getItemIterator;
private PaginatedItemsIterable(BuilderImpl<ResponseT, ItemT> builder) {
this.pagesIterable = builder.pagesIterable;
this.getItemIterator = builder.itemIteratorFunction;
}
public static <R, T> Builder<R, T> builder() {
return new BuilderImpl<>();
}
@Override
public Iterator<ItemT> iterator() {
return new ItemsIterator(pagesIterable.iterator());
}
private class ItemsIterator implements Iterator<ItemT> {
private final Iterator<ResponseT> pagesIterator;
private Iterator<ItemT> singlePageItemsIterator;
ItemsIterator(final Iterator<ResponseT> pagesIterator) {
this.pagesIterator = pagesIterator;
this.singlePageItemsIterator = pagesIterator.hasNext() ? getItemIterator.apply(pagesIterator.next())
: Collections.emptyIterator();
}
@Override
public boolean hasNext() {
while (!hasMoreItems() && pagesIterator.hasNext()) {
singlePageItemsIterator = getItemIterator.apply(pagesIterator.next());
}
if (hasMoreItems()) {
return true;
}
return false;
}
@Override
public ItemT next() {
if (!hasNext()) {
throw new NoSuchElementException("No more elements left");
}
return singlePageItemsIterator.next();
}
private boolean hasMoreItems() {
return singlePageItemsIterator.hasNext();
}
}
public interface Builder<ResponseT, ItemT> {
Builder<ResponseT, ItemT> pagesIterable(SdkIterable<ResponseT> sdkIterable);
Builder<ResponseT, ItemT> itemIteratorFunction(Function<ResponseT, Iterator<ItemT>> itemIteratorFunction);
PaginatedItemsIterable<ResponseT, ItemT> build();
}
private static final class BuilderImpl<ResponseT, ItemT> implements Builder<ResponseT, ItemT> {
private SdkIterable<ResponseT> pagesIterable;
private Function<ResponseT, Iterator<ItemT>> itemIteratorFunction;
private BuilderImpl() {
}
@Override
public Builder<ResponseT, ItemT> pagesIterable(SdkIterable<ResponseT> pagesIterable) {
this.pagesIterable = pagesIterable;
return this;
}
@Override
public Builder<ResponseT, ItemT> itemIteratorFunction(Function<ResponseT, Iterator<ItemT>> itemIteratorFunction) {
this.itemIteratorFunction = itemIteratorFunction;
return this;
}
@Override
public PaginatedItemsIterable<ResponseT, ItemT> build() {
return new PaginatedItemsIterable<>(this);
}
}
}
| 2,078 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/sync/SdkIterable.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.sync;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A custom iterable used in paginated responses.
*
* This interface has a default stream() method which creates a stream from
* spliterator method.
*
* @param <T> the type of elements returned by the iterator
*/
@SdkPublicApi
public interface SdkIterable<T> extends Iterable<T> {
default Stream<T> stream() {
return StreamSupport.stream(spliterator(), false);
}
}
| 2,079 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/sync/PaginatedResponsesIterator.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.sync;
import java.util.Iterator;
import java.util.NoSuchElementException;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Iterator for all response pages in a paginated operation.
*
* This class is used to iterate through all the pages of an operation.
* SDK makes service calls to retrieve the next page when next() method is called.
*
* @param <ResponseT> The type of a single response page
*/
@SdkProtectedApi
public final class PaginatedResponsesIterator<ResponseT> implements Iterator<ResponseT> {
private final SyncPageFetcher<ResponseT> nextPageFetcher;
// This is null when the object is created. It gets initialized in next() method
// where SDK make service calls.
private ResponseT oldResponse;
private PaginatedResponsesIterator(BuilderImpl builder) {
this.nextPageFetcher = builder.nextPageFetcher;
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public boolean hasNext() {
return oldResponse == null || nextPageFetcher.hasNextPage(oldResponse);
}
@Override
public ResponseT next() {
if (!hasNext()) {
throw new NoSuchElementException("No more pages left");
}
oldResponse = nextPageFetcher.nextPage(oldResponse);
return oldResponse;
}
public interface Builder {
Builder nextPageFetcher(SyncPageFetcher nextPageFetcher);
PaginatedResponsesIterator build();
}
private static final class BuilderImpl implements Builder {
private SyncPageFetcher nextPageFetcher;
protected BuilderImpl() {
}
@Override
public Builder nextPageFetcher(SyncPageFetcher nextPageFetcher) {
this.nextPageFetcher = nextPageFetcher;
return this;
}
@Override
public PaginatedResponsesIterator build() {
return new PaginatedResponsesIterator(this);
}
}
}
| 2,080 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/RetryUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.http.HttpStatusCode;
@SdkProtectedApi
public final class RetryUtils {
private RetryUtils() {
}
/**
* Returns true if the specified exception is a request entity too large error.
*
* @param exception The exception to test.
* @return True if the exception resulted from a request entity too large error message from a service, otherwise false.
*/
public static boolean isRequestEntityTooLargeException(SdkException exception) {
return isServiceException(exception) && toServiceException(exception).statusCode() == HttpStatusCode.REQUEST_TOO_LONG;
}
public static boolean isServiceException(SdkException e) {
return e instanceof SdkServiceException;
}
public static SdkServiceException toServiceException(SdkException e) {
if (!(e instanceof SdkServiceException)) {
throw new IllegalStateException("Received non-SdkServiceException where one was expected.", e);
}
return (SdkServiceException) e;
}
/**
* Returns true if the specified exception is a clock skew error.
*
* @param exception The exception to test.
* @return True if the exception resulted from a clock skews error message from a service, otherwise false.
*/
public static boolean isClockSkewException(SdkException exception) {
return isServiceException(exception) && toServiceException(exception).isClockSkewException();
}
/**
* Returns true if the specified exception is a throttling error.
*
* @param exception The exception to test.
* @return True if the exception resulted from a throttling error message from a service, otherwise false.
*/
public static boolean isThrottlingException(SdkException exception) {
return isServiceException(exception) && toServiceException(exception).isThrottlingException();
}
}
| 2,081 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/RetryPolicy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry;
import java.util.Objects;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ToBuilderIgnoreField;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting;
import software.amazon.awssdk.core.retry.backoff.BackoffStrategy;
import software.amazon.awssdk.core.retry.conditions.AndRetryCondition;
import software.amazon.awssdk.core.retry.conditions.MaxNumberOfRetriesCondition;
import software.amazon.awssdk.core.retry.conditions.RetryCondition;
import software.amazon.awssdk.core.retry.conditions.TokenBucketRetryCondition;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Interface for specifying a retry policy to use when evaluating whether or not a request should be retried. The
* {@link #builder()}} can be used to construct a retry policy from SDK provided policies or policies that directly implement
* {@link BackoffStrategy} and/or {@link RetryCondition}. This is configured on a client via
* {@link ClientOverrideConfiguration.Builder#retryPolicy}.
*
* When using the {@link #builder()} the SDK will use default values for fields that are not provided. The default number of
* retries and condition is based on the current {@link RetryMode}.
*
* @see RetryCondition for a list of SDK provided retry condition strategies
* @see BackoffStrategy for a list of SDK provided backoff strategies
*/
@Immutable
@SdkPublicApi
public final class RetryPolicy implements ToCopyableBuilder<RetryPolicy.Builder, RetryPolicy> {
private final boolean additionalRetryConditionsAllowed;
private final RetryMode retryMode;
private final BackoffStrategy backoffStrategy;
private final BackoffStrategy throttlingBackoffStrategy;
private final Integer numRetries;
private final RetryCondition retryCondition;
private final RetryCondition retryCapacityCondition;
private final RetryCondition aggregateRetryCondition;
private Boolean fastFailRateLimiting;
private RetryPolicy(BuilderImpl builder) {
this.additionalRetryConditionsAllowed = builder.additionalRetryConditionsAllowed;
this.retryMode = builder.retryMode;
this.backoffStrategy = builder.backoffStrategy;
this.throttlingBackoffStrategy = builder.throttlingBackoffStrategy;
this.numRetries = builder.numRetries;
this.retryCondition = builder.retryCondition;
this.retryCapacityCondition = builder.retryCapacityCondition;
this.aggregateRetryCondition = generateAggregateRetryCondition();
this.fastFailRateLimiting = builder.isFastFailRateLimiting();
validateFastFailRateLimiting();
}
/**
* Create a {@link RetryPolicy} using the {@link RetryMode#defaultRetryMode()} defaults.
*/
public static RetryPolicy defaultRetryPolicy() {
return forRetryMode(RetryMode.defaultRetryMode());
}
/**
* Create a {@link RetryPolicy} using the provided {@link RetryMode} defaults.
*/
public static RetryPolicy forRetryMode(RetryMode retryMode) {
return RetryPolicy.builder(retryMode).build();
}
/**
* Create a {@link RetryPolicy} that will NEVER retry.
*/
public static RetryPolicy none() {
return RetryPolicy.builder()
.numRetries(0)
.backoffStrategy(BackoffStrategy.none())
.throttlingBackoffStrategy(BackoffStrategy.none())
.retryCondition(RetryCondition.none())
.additionalRetryConditionsAllowed(false)
.build();
}
/**
* Create a {@link RetryPolicy.Builder} populated with the defaults from the {@link RetryMode#defaultRetryMode()}.
*/
public static Builder builder() {
return new BuilderImpl(RetryMode.defaultRetryMode());
}
/**
* Create a {@link RetryPolicy.Builder} populated with the defaults from the provided {@link RetryMode}.
*/
public static Builder builder(RetryMode retryMode) {
Validate.paramNotNull(retryMode, "The retry mode cannot be set as null. If you don't want to set the retry mode,"
+ " please use the other builder method without setting retry mode, and the default retry"
+ " mode will be used.");
return new BuilderImpl(retryMode);
}
/**
* Retrieve the {@link RetryMode} that was used to determine the defaults for this retry policy.
*/
public RetryMode retryMode() {
return retryMode;
}
/**
* When using {@link RetryMode#ADAPTIVE} retry mode, this controls the client should immediately fail the request when not
* enough capacity is immediately available from the rate limiter to execute the request, instead of waiting for capacity
* to be available.
*/
public Boolean isFastFailRateLimiting() {
return fastFailRateLimiting;
}
/**
* Returns true if service-specific conditions are allowed on this policy (e.g. more conditions may be added by the SDK if
* they are recommended).
*/
public boolean additionalRetryConditionsAllowed() {
return additionalRetryConditionsAllowed;
}
/**
* Retrieve the retry condition that aggregates the {@link Builder#retryCondition(RetryCondition)},
* {@link Builder#numRetries(Integer)} and {@link Builder#retryCapacityCondition(RetryCondition)} configured on the builder.
*/
public RetryCondition aggregateRetryCondition() {
return aggregateRetryCondition;
}
/**
* Retrieve the {@link Builder#retryCondition(RetryCondition)} configured on the builder.
*/
public RetryCondition retryCondition() {
return retryCondition;
}
/**
* Retrieve the {@link Builder#backoffStrategy(BackoffStrategy)} configured on the builder.
*/
public BackoffStrategy backoffStrategy() {
return backoffStrategy;
}
/**
* Retrieve the {@link Builder#throttlingBackoffStrategy(BackoffStrategy)} configured on the builder.
*/
public BackoffStrategy throttlingBackoffStrategy() {
return throttlingBackoffStrategy;
}
/**
* Retrieve the {@link Builder#numRetries(Integer)} configured on the builder.
*/
public Integer numRetries() {
return numRetries;
}
private RetryCondition generateAggregateRetryCondition() {
RetryCondition aggregate = AndRetryCondition.create(MaxNumberOfRetriesCondition.create(numRetries),
retryCondition);
if (retryCapacityCondition != null) {
return AndRetryCondition.create(aggregate, retryCapacityCondition);
}
return aggregate;
}
@Override
@ToBuilderIgnoreField("retryMode")
public Builder toBuilder() {
return builder(retryMode).additionalRetryConditionsAllowed(additionalRetryConditionsAllowed)
.numRetries(numRetries)
.retryCondition(retryCondition)
.backoffStrategy(backoffStrategy)
.throttlingBackoffStrategy(throttlingBackoffStrategy)
.retryCapacityCondition(retryCapacityCondition)
.fastFailRateLimiting(fastFailRateLimiting);
}
@Override
public String toString() {
return ToString.builder("RetryPolicy")
.add("additionalRetryConditionsAllowed", additionalRetryConditionsAllowed)
.add("aggregateRetryCondition", aggregateRetryCondition)
.add("backoffStrategy", backoffStrategy)
.add("throttlingBackoffStrategy", throttlingBackoffStrategy)
.add("fastFailRateLimiting", fastFailRateLimiting)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RetryPolicy that = (RetryPolicy) o;
if (additionalRetryConditionsAllowed != that.additionalRetryConditionsAllowed) {
return false;
}
if (!aggregateRetryCondition.equals(that.aggregateRetryCondition)) {
return false;
}
if (!backoffStrategy.equals(that.backoffStrategy)) {
return false;
}
if (!throttlingBackoffStrategy.equals(that.throttlingBackoffStrategy)) {
return false;
}
return Objects.equals(fastFailRateLimiting, that.fastFailRateLimiting);
}
@Override
public int hashCode() {
int result = aggregateRetryCondition.hashCode();
result = 31 * result + Boolean.hashCode(additionalRetryConditionsAllowed);
result = 31 * result + backoffStrategy.hashCode();
result = 31 * result + throttlingBackoffStrategy.hashCode();
result = 31 * result + Objects.hashCode(fastFailRateLimiting);
return result;
}
private void validateFastFailRateLimiting() {
if (fastFailRateLimiting == null) {
return;
}
Validate.isTrue(RetryMode.ADAPTIVE == retryMode,
"FastFailRateLimiting is enabled, but this setting is only valid for the ADAPTIVE retry mode. The "
+ "configured mode is %s.", retryMode.name());
}
public interface Builder extends CopyableBuilder<Builder, RetryPolicy> {
/**
* Configure whether further conditions can be added to this policy after it is created. This may include service-
* specific retry conditions that may not otherwise be covered by the {@link RetryCondition#defaultRetryCondition()}.
*
* <p>
* By default, this is true.
*/
Builder additionalRetryConditionsAllowed(boolean additionalRetryConditionsAllowed);
/**
* @see #additionalRetryConditionsAllowed(boolean)
*/
boolean additionalRetryConditionsAllowed();
/**
* Configure the backoff strategy that should be used for waiting in between retry attempts. If the retry is because of
* throttling reasons, the {@link #throttlingBackoffStrategy(BackoffStrategy)} is used instead.
*/
Builder backoffStrategy(BackoffStrategy backoffStrategy);
/**
* @see #backoffStrategy(BackoffStrategy)
*/
BackoffStrategy backoffStrategy();
/**
* Configure the backoff strategy that should be used for waiting in between retry attempts after a throttling error
* is encountered. If the retry is not because of throttling reasons, the {@link #backoffStrategy(BackoffStrategy)} is
* used instead.
*/
Builder throttlingBackoffStrategy(BackoffStrategy backoffStrategy);
/**
* @see #throttlingBackoffStrategy(BackoffStrategy)
*/
BackoffStrategy throttlingBackoffStrategy();
/**
* Configure the condition under which the request should be retried.
*
* <p>
* While this can be any interface that implements {@link RetryCondition}, it is encouraged to use
* {@link #numRetries(Integer)} when attempting to limit the number of times the SDK will retry an attempt or the
* {@link #retryCapacityCondition(RetryCondition)} when attempting to configure the throttling of retries. This guidance
* is because the SDK uses the {@link #aggregateRetryCondition()} when determining whether or not to retry a request,
* and the {@code aggregateRetryCondition} includes the {@code numRetries} and {@code retryCapacityCondition} in its
* determination.
*/
Builder retryCondition(RetryCondition retryCondition);
/**
* @see #retryCondition(RetryCondition)
*/
RetryCondition retryCondition();
/**
* Configure the {@link RetryCondition} that should be used to throttle the number of retries attempted by the SDK client
* as a whole.
*
* <p>
* While any {@link RetryCondition} (or null) can be used, by convention these conditions are usually stateful and work
* globally for the whole client to limit the overall capacity of the client to execute retries.
*
* <p>
* By default the {@link TokenBucketRetryCondition} is used. This can be disabled by setting the value to {@code null}
* (not {@code RetryPolicy#none()}, which would completely disable retries).
*/
Builder retryCapacityCondition(RetryCondition retryCapacityCondition);
/**
* @see #retryCapacityCondition(RetryCondition)
*/
RetryCondition retryCapacityCondition();
/**
* Configure the maximum number of times that a single request should be retried, assuming it fails for a retryable error.
*/
Builder numRetries(Integer numRetries);
/**
* @see #numRetries(Integer)
*/
Integer numRetries();
/**
* Whether the client should immediately fail the request when not enough capacity is immediately available from the
* rate limiter to execute the request, instead of waiting for capacity to be available.
*
* @param fastFailRateLimiting Whether to fast fail.
*/
Builder fastFailRateLimiting(Boolean fastFailRateLimiting);
/**
* Whether the client should immediately fail the request when not enough capacity is immediately available from the
* rate limiter to execute the request, instead of waiting for capacity to be available.
*/
Boolean isFastFailRateLimiting();
@Override
RetryPolicy build();
}
/**
* Builder for a {@link RetryPolicy}.
*/
private static final class BuilderImpl implements Builder {
private final RetryMode retryMode;
private boolean additionalRetryConditionsAllowed;
private Integer numRetries;
private BackoffStrategy backoffStrategy;
private BackoffStrategy throttlingBackoffStrategy;
private RetryCondition retryCondition;
private RetryCondition retryCapacityCondition;
private Boolean fastFailRateLimiting;
private BuilderImpl(RetryMode retryMode) {
this.retryMode = retryMode;
this.numRetries = SdkDefaultRetrySetting.maxAttempts(retryMode) - 1;
this.additionalRetryConditionsAllowed = true;
this.backoffStrategy = BackoffStrategy.defaultStrategy(retryMode);
this.throttlingBackoffStrategy = BackoffStrategy.defaultThrottlingStrategy(retryMode);
this.retryCondition = RetryCondition.defaultRetryCondition();
this.retryCapacityCondition = TokenBucketRetryCondition.forRetryMode(retryMode);
}
@Override
public Builder additionalRetryConditionsAllowed(boolean additionalRetryConditionsAllowed) {
this.additionalRetryConditionsAllowed = additionalRetryConditionsAllowed;
return this;
}
public void setadditionalRetryConditionsAllowed(boolean additionalRetryConditionsAllowed) {
additionalRetryConditionsAllowed(additionalRetryConditionsAllowed);
}
@Override
public boolean additionalRetryConditionsAllowed() {
return additionalRetryConditionsAllowed;
}
@Override
public Builder numRetries(Integer numRetries) {
this.numRetries = numRetries;
return this;
}
public void setNumRetries(Integer numRetries) {
numRetries(numRetries);
}
@Override
public Integer numRetries() {
return numRetries;
}
@Override
public Builder fastFailRateLimiting(Boolean fastFailRateLimiting) {
this.fastFailRateLimiting = fastFailRateLimiting;
return this;
}
@Override
public Boolean isFastFailRateLimiting() {
return fastFailRateLimiting;
}
@Override
public Builder backoffStrategy(BackoffStrategy backoffStrategy) {
this.backoffStrategy = backoffStrategy;
return this;
}
public void setBackoffStrategy(BackoffStrategy backoffStrategy) {
backoffStrategy(backoffStrategy);
}
@Override
public BackoffStrategy backoffStrategy() {
return backoffStrategy;
}
@Override
public Builder throttlingBackoffStrategy(BackoffStrategy throttlingBackoffStrategy) {
this.throttlingBackoffStrategy = throttlingBackoffStrategy;
return this;
}
@Override
public BackoffStrategy throttlingBackoffStrategy() {
return throttlingBackoffStrategy;
}
public void setThrottlingBackoffStrategy(BackoffStrategy throttlingBackoffStrategy) {
this.throttlingBackoffStrategy = throttlingBackoffStrategy;
}
@Override
public Builder retryCondition(RetryCondition retryCondition) {
this.retryCondition = retryCondition;
return this;
}
public void setRetryCondition(RetryCondition retryCondition) {
retryCondition(retryCondition);
}
@Override
public RetryCondition retryCondition() {
return retryCondition;
}
@Override
public Builder retryCapacityCondition(RetryCondition retryCapacityCondition) {
this.retryCapacityCondition = retryCapacityCondition;
return this;
}
public void setRetryCapacityCondition(RetryCondition retryCapacityCondition) {
retryCapacityCondition(retryCapacityCondition);
}
@Override
public RetryCondition retryCapacityCondition() {
return this.retryCapacityCondition;
}
@Override
public RetryPolicy build() {
return new RetryPolicy(this);
}
}
}
| 2,082 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/RetryMode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.retry.conditions.TokenBucketRetryCondition;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.utils.OptionalUtils;
import software.amazon.awssdk.utils.StringUtils;
/**
* A retry mode is a collection of retry behaviors encoded under a single value. For example, the {@link #LEGACY} retry mode will
* retry up to three times, and the {@link #STANDARD} will retry up to two times.
*
* <p>
* While the {@link #LEGACY} retry mode is specific to Java, the {@link #STANDARD} retry mode is standardized across all of the
* AWS SDKs.
*
* <p>
* The retry mode can be configured:
* <ol>
* <li>Directly on a client via {@link ClientOverrideConfiguration.Builder#retryPolicy(RetryMode)}.</li>
* <li>Directly on a client via a combination of {@link RetryPolicy#builder(RetryMode)} or
* {@link RetryPolicy#forRetryMode(RetryMode)}, and {@link ClientOverrideConfiguration.Builder#retryPolicy(RetryPolicy)}</li>
* <li>On a configuration profile via the "retry_mode" profile file property.</li>
* <li>Globally via the "aws.retryMode" system property.</li>
* <li>Globally via the "AWS_RETRY_MODE" environment variable.</li>
* </ol>
*/
@SdkPublicApi
public enum RetryMode {
/**
* The LEGACY retry mode, specific to the Java SDK, and characterized by:
* <ol>
* <li>Up to 3 retries, or more for services like DynamoDB (which has up to 8).</li>
* <li>Zero token are subtracted from the {@link TokenBucketRetryCondition} when throttling exceptions are encountered.
* </li>
* </ol>
*
* <p>
* This is the retry mode that is used when no other mode is configured.
*/
LEGACY,
/**
* The STANDARD retry mode, shared by all AWS SDK implementations, and characterized by:
* <ol>
* <li>Up to 2 retries, regardless of service.</li>
* <li>Throttling exceptions are treated the same as other exceptions for the purposes of the
* {@link TokenBucketRetryCondition}.</li>
* </ol>
*/
STANDARD,
/**
* Adaptive retry mode builds on {@code STANDARD} mode.
* <p>
* Adaptive retry mode dynamically limits the rate of AWS requests to maximize success rate. This may be at the
* expense of request latency. Adaptive retry mode is not recommended when predictable latency is important.
* <p>
* <b>Warning:</b> Adaptive retry mode assumes that the client is working against a single resource (e.g. one
* DynamoDB Table or one S3 Bucket). If you use a single client for multiple resources, throttling or outages
* associated with one resource will result in increased latency and failures when accessing all other resources via
* the same client. When using adaptive retry mode, we recommend using a single client per resource.
*
* @see RetryPolicy#isFastFailRateLimiting()
*/
ADAPTIVE,
;
/**
* Retrieve the default retry mode by consulting the locations described in {@link RetryMode}, or LEGACY if no value is
* configured.
*/
public static RetryMode defaultRetryMode() {
return resolver().resolve();
}
/**
* Create a {@link Resolver} that allows customizing the variables used during determination of a {@link RetryMode}.
*/
public static Resolver resolver() {
return new Resolver();
}
/**
* Allows customizing the variables used during determination of a {@link RetryMode}. Created via {@link #resolver()}.
*/
public static class Resolver {
private static final RetryMode SDK_DEFAULT_RETRY_MODE = LEGACY;
private Supplier<ProfileFile> profileFile;
private String profileName;
private RetryMode defaultRetryMode;
private Resolver() {
}
/**
* Configure the profile file that should be used when determining the {@link RetryMode}. The supplier is only consulted
* if a higher-priority determinant (e.g. environment variables) does not find the setting.
*/
public Resolver profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
/**
* Configure the profile file name should be used when determining the {@link RetryMode}.
*/
public Resolver profileName(String profileName) {
this.profileName = profileName;
return this;
}
/**
* Configure the {@link RetryMode} that should be used if the mode is not specified anywhere else.
*/
public Resolver defaultRetryMode(RetryMode defaultRetryMode) {
this.defaultRetryMode = defaultRetryMode;
return this;
}
/**
* Resolve which retry mode should be used, based on the configured values.
*/
public RetryMode resolve() {
return OptionalUtils.firstPresent(Resolver.fromSystemSettings(), () -> fromProfileFile(profileFile, profileName))
.orElseGet(this::fromDefaultMode);
}
private static Optional<RetryMode> fromSystemSettings() {
return SdkSystemSetting.AWS_RETRY_MODE.getStringValue()
.flatMap(Resolver::fromString);
}
private static Optional<RetryMode> fromProfileFile(Supplier<ProfileFile> profileFile, String profileName) {
profileFile = profileFile != null ? profileFile : ProfileFile::defaultProfileFile;
profileName = profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow();
return profileFile.get()
.profile(profileName)
.flatMap(p -> p.property(ProfileProperty.RETRY_MODE))
.flatMap(Resolver::fromString);
}
private static Optional<RetryMode> fromString(String string) {
if (string == null || string.isEmpty()) {
return Optional.empty();
}
switch (StringUtils.lowerCase(string)) {
case "legacy":
return Optional.of(LEGACY);
case "standard":
return Optional.of(STANDARD);
case "adaptive":
return Optional.of(ADAPTIVE);
default:
throw new IllegalStateException("Unsupported retry policy mode configured: " + string);
}
}
private RetryMode fromDefaultMode() {
return defaultRetryMode != null ? defaultRetryMode : SDK_DEFAULT_RETRY_MODE;
}
}
}
| 2,083 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/RetryPolicyContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Contains useful information about a failed request that can be used to make retry and backoff decisions. See {@link
* RetryPolicy}.
*/
@Immutable
@SdkPublicApi
public final class RetryPolicyContext implements ToCopyableBuilder<RetryPolicyContext.Builder, RetryPolicyContext> {
private final SdkRequest originalRequest;
private final SdkHttpFullRequest request;
private final SdkException exception;
private final ExecutionAttributes executionAttributes;
private final int retriesAttempted;
private final Integer httpStatusCode;
private RetryPolicyContext(Builder builder) {
this.originalRequest = builder.originalRequest;
this.request = builder.request;
this.exception = builder.exception;
this.executionAttributes = builder.executionAttributes;
this.retriesAttempted = builder.retriesAttempted;
this.httpStatusCode = builder.httpStatusCode;
}
public static Builder builder() {
return new Builder();
}
/**
* @return The original request passed to the client method for an operation.
*/
public SdkRequest originalRequest() {
return this.originalRequest;
}
/**
* @return The marshalled request.
*/
public SdkHttpFullRequest request() {
return this.request;
}
/**
* @return The last seen exception for the request.
*/
public SdkException exception() {
return this.exception;
}
/**
* @return Mutable execution context.
*/
public ExecutionAttributes executionAttributes() {
return this.executionAttributes;
}
/**
* @return Number of retries attempted thus far.
*/
public int retriesAttempted() {
return this.retriesAttempted;
}
/**
* @return The total number of requests made thus far.
*/
public int totalRequests() {
return this.retriesAttempted + 1;
}
/**
* @return HTTP status code of response. May be null if no response was received from the service.
*/
public Integer httpStatusCode() {
return this.httpStatusCode;
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
@SdkPublicApi
public static final class Builder implements CopyableBuilder<Builder, RetryPolicyContext> {
private SdkRequest originalRequest;
private SdkHttpFullRequest request;
private SdkException exception;
private ExecutionAttributes executionAttributes;
private int retriesAttempted;
private Integer httpStatusCode;
private Builder() {
}
private Builder(RetryPolicyContext copy) {
this.originalRequest = copy.originalRequest;
this.request = copy.request;
this.exception = copy.exception;
this.executionAttributes = copy.executionAttributes;
this.retriesAttempted = copy.retriesAttempted;
this.httpStatusCode = copy.httpStatusCode;
}
public Builder originalRequest(SdkRequest originalRequest) {
this.originalRequest = originalRequest;
return this;
}
public Builder request(SdkHttpFullRequest request) {
this.request = request;
return this;
}
public Builder exception(SdkException exception) {
this.exception = exception;
return this;
}
public Builder executionAttributes(ExecutionAttributes executionAttributes) {
this.executionAttributes = executionAttributes;
return this;
}
public Builder retriesAttempted(int retriesAttempted) {
this.retriesAttempted = retriesAttempted;
return this;
}
public Builder httpStatusCode(Integer httpStatusCode) {
this.httpStatusCode = httpStatusCode;
return this;
}
@Override
public RetryPolicyContext build() {
return new RetryPolicyContext(this);
}
}
}
| 2,084 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/ClockSkew.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.internal.http.HttpClientDependencies;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.utils.DateUtils;
import software.amazon.awssdk.utils.Logger;
/**
* Utility methods for checking and reacting to the current client-side clock being different from the service-side clock.
*/
@ThreadSafe
@SdkProtectedApi
public final class ClockSkew {
private static final Logger log = Logger.loggerFor(ClockSkew.class);
/**
* When we get an error that may be due to a clock skew error, and our clock is different than the service clock, this is
* the difference threshold beyond which we will recommend a clock skew adjustment.
*/
private static final Duration CLOCK_SKEW_ADJUST_THRESHOLD = Duration.ofMinutes(4);
private ClockSkew() {
}
/**
* Determine whether the request-level client time was sufficiently skewed from the server time as to possibly cause a
* clock skew error.
*/
public static boolean isClockSkewed(Instant clientTime, Instant serverTime) {
Duration requestClockSkew = getClockSkew(clientTime, serverTime);
return requestClockSkew.abs().compareTo(CLOCK_SKEW_ADJUST_THRESHOLD) >= 0;
}
/**
* Calculate the time skew between a client and server date. This value has the same semantics of
* {@link HttpClientDependencies#timeOffset()}. Positive values imply the client clock is "fast" and negative values imply
* the client clock is "slow".
*/
public static Duration getClockSkew(Instant clientTime, Instant serverTime) {
if (clientTime == null || serverTime == null) {
// If we do not have a client or server time, 0 is the safest skew to apply
return Duration.ZERO;
}
return Duration.between(serverTime, clientTime);
}
/**
* Get the server time from the service response, or empty if the time could not be determined.
*/
public static Optional<Instant> getServerTime(SdkHttpResponse serviceResponse) {
Optional<String> responseDateHeader = serviceResponse.firstMatchingHeader("Date");
if (responseDateHeader.isPresent()) {
String serverDate = responseDateHeader.get();
log.debug(() -> "Reported service date: " + serverDate);
try {
return Optional.of(DateUtils.parseRfc822Date(serverDate));
} catch (RuntimeException e) {
log.warn(() -> "Unable to parse clock skew offset from response: " + serverDate, e);
return Optional.empty();
}
}
log.debug(() -> "Service did not return a Date header, so clock skew adjustments will not be applied.");
return Optional.empty();
}
}
| 2,085 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/backoff/EqualJitterBackoffStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.backoff;
import static software.amazon.awssdk.utils.NumericUtils.min;
import static software.amazon.awssdk.utils.Validate.isNotNegative;
import java.time.Duration;
import java.util.Random;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Backoff strategy that uses equal jitter for computing the delay before the next retry. An equal jitter
* backoff strategy will first compute an exponential delay based on the current number of retries, base delay
* and max delay. The final computed delay before the next retry will keep half of this computed delay plus
* a random delay computed as a random number between 0 and half of the exponential delay plus one.
*
* For example, using a base delay of 100, a max backoff time of 10000 an exponential delay of 400 is computed
* for a second retry attempt. The final computed delay before the next retry will be half of the computed exponential
* delay, in this case 200, plus a random number between 0 and 201. Therefore the range for delay would be between
* 200 and 401.
*
* This is in contrast to {@link FullJitterBackoffStrategy} where the final computed delay before the next retry will be
* between 0 and the computed exponential delay.
*/
@SdkPublicApi
public final class EqualJitterBackoffStrategy implements BackoffStrategy,
ToCopyableBuilder<EqualJitterBackoffStrategy.Builder,
EqualJitterBackoffStrategy> {
private static final Duration BASE_DELAY_CEILING = Duration.ofMillis(Integer.MAX_VALUE); // Around 24 days
private static final Duration MAX_BACKOFF_CEILING = Duration.ofMillis(Integer.MAX_VALUE); // Around 24 days
private final Duration baseDelay;
private final Duration maxBackoffTime;
private final Random random;
private EqualJitterBackoffStrategy(BuilderImpl builder) {
this(builder.baseDelay, builder.maxBackoffTime, new Random());
}
EqualJitterBackoffStrategy(final Duration baseDelay, final Duration maxBackoffTime, final Random random) {
this.baseDelay = min(isNotNegative(baseDelay, "baseDelay"), BASE_DELAY_CEILING);
this.maxBackoffTime = min(isNotNegative(maxBackoffTime, "maxBackoffTime"), MAX_BACKOFF_CEILING);
this.random = random;
}
@Override
public Duration computeDelayBeforeNextRetry(RetryPolicyContext context) {
int ceil = calculateExponentialDelay(context.retriesAttempted(), baseDelay, maxBackoffTime);
return Duration.ofMillis((ceil / 2) + random.nextInt((ceil / 2) + 1));
}
@Override
public Builder toBuilder() {
return builder().baseDelay(baseDelay).maxBackoffTime(maxBackoffTime);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder extends CopyableBuilder<EqualJitterBackoffStrategy.Builder, EqualJitterBackoffStrategy> {
Builder baseDelay(Duration baseDelay);
Duration baseDelay();
Builder maxBackoffTime(Duration maxBackoffTime);
Duration maxBackoffTime();
@Override
EqualJitterBackoffStrategy build();
}
private static final class BuilderImpl implements Builder {
private Duration baseDelay;
private Duration maxBackoffTime;
private BuilderImpl() {
}
@Override
public Builder baseDelay(Duration baseDelay) {
this.baseDelay = baseDelay;
return this;
}
public void setBaseDelay(Duration baseDelay) {
baseDelay(baseDelay);
}
@Override
public Duration baseDelay() {
return baseDelay;
}
@Override
public Builder maxBackoffTime(Duration maxBackoffTime) {
this.maxBackoffTime = maxBackoffTime;
return this;
}
public void setMaxBackoffTime(Duration maxBackoffTime) {
maxBackoffTime(maxBackoffTime);
}
@Override
public Duration maxBackoffTime() {
return maxBackoffTime;
}
@Override
public EqualJitterBackoffStrategy build() {
return new EqualJitterBackoffStrategy(this);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EqualJitterBackoffStrategy that = (EqualJitterBackoffStrategy) o;
if (!baseDelay.equals(that.baseDelay)) {
return false;
}
return maxBackoffTime.equals(that.maxBackoffTime);
}
@Override
public int hashCode() {
int result = baseDelay.hashCode();
result = 31 * result + maxBackoffTime.hashCode();
return result;
}
@Override
public String toString() {
return ToString.builder("EqualJitterBackoffStrategy")
.add("baseDelay", baseDelay)
.add("maxBackoffTime", maxBackoffTime)
.build();
}
}
| 2,086 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/backoff/FullJitterBackoffStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.backoff;
import static software.amazon.awssdk.utils.NumericUtils.min;
import static software.amazon.awssdk.utils.Validate.isNotNegative;
import java.time.Duration;
import java.util.Random;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Backoff strategy that uses a full jitter strategy for computing the next backoff delay. A full jitter
* strategy will always compute a new random delay between 0 and the computed exponential backoff for each
* subsequent request.
*
* For example, using a base delay of 100, a max backoff time of 10000 an exponential delay of 400 is computed
* for a second retry attempt. The final computed delay before the next retry will then be in the range of 0 to 400.
*
* This is in contrast to {@link EqualJitterBackoffStrategy} that computes a new random delay where the final
* computed delay before the next retry will be at least half of the computed exponential delay.
*/
@SdkPublicApi
public final class FullJitterBackoffStrategy implements BackoffStrategy,
ToCopyableBuilder<FullJitterBackoffStrategy.Builder,
FullJitterBackoffStrategy> {
private static final Duration BASE_DELAY_CEILING = Duration.ofMillis(Integer.MAX_VALUE); // Around 24 days
private static final Duration MAX_BACKOFF_CEILING = Duration.ofMillis(Integer.MAX_VALUE); // Around 24 days
private final Duration baseDelay;
private final Duration maxBackoffTime;
private final Random random;
private FullJitterBackoffStrategy(BuilderImpl builder) {
this(builder.baseDelay, builder.maxBackoffTime, new Random());
}
FullJitterBackoffStrategy(final Duration baseDelay, final Duration maxBackoffTime, final Random random) {
this.baseDelay = min(isNotNegative(baseDelay, "baseDelay"), BASE_DELAY_CEILING);
this.maxBackoffTime = min(isNotNegative(maxBackoffTime, "maxBackoffTime"), MAX_BACKOFF_CEILING);
this.random = random;
}
@Override
public Duration computeDelayBeforeNextRetry(RetryPolicyContext context) {
int ceil = calculateExponentialDelay(context.retriesAttempted(), baseDelay, maxBackoffTime);
// Minimum of 1 ms (consistent with BackoffStrategy.none()'s behavior)
return Duration.ofMillis(random.nextInt(ceil) + 1L);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder extends CopyableBuilder<Builder, FullJitterBackoffStrategy> {
Builder baseDelay(Duration baseDelay);
Duration baseDelay();
Builder maxBackoffTime(Duration maxBackoffTime);
Duration maxBackoffTime();
@Override
FullJitterBackoffStrategy build();
}
private static final class BuilderImpl implements Builder {
private Duration baseDelay;
private Duration maxBackoffTime;
private BuilderImpl() {
}
private BuilderImpl(FullJitterBackoffStrategy strategy) {
this.baseDelay = strategy.baseDelay;
this.maxBackoffTime = strategy.maxBackoffTime;
}
@Override
public Builder baseDelay(Duration baseDelay) {
this.baseDelay = baseDelay;
return this;
}
public void setBaseDelay(Duration baseDelay) {
baseDelay(baseDelay);
}
@Override
public Duration baseDelay() {
return baseDelay;
}
@Override
public Builder maxBackoffTime(Duration maxBackoffTime) {
this.maxBackoffTime = maxBackoffTime;
return this;
}
public void setMaxBackoffTime(Duration maxBackoffTime) {
maxBackoffTime(maxBackoffTime);
}
@Override
public Duration maxBackoffTime() {
return maxBackoffTime;
}
@Override
public FullJitterBackoffStrategy build() {
return new FullJitterBackoffStrategy(this);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FullJitterBackoffStrategy that = (FullJitterBackoffStrategy) o;
if (!baseDelay.equals(that.baseDelay)) {
return false;
}
return maxBackoffTime.equals(that.maxBackoffTime);
}
@Override
public int hashCode() {
int result = baseDelay.hashCode();
result = 31 * result + maxBackoffTime.hashCode();
return result;
}
@Override
public String toString() {
return ToString.builder("FullJitterBackoffStrategy")
.add("baseDelay", baseDelay)
.add("maxBackoffTime", maxBackoffTime)
.build();
}
}
| 2,087 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/backoff/BackoffStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.backoff;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
@SdkPublicApi
@FunctionalInterface
public interface BackoffStrategy {
/**
* Max permitted retry times. To prevent exponentialDelay from overflow, there must be 2 ^ retriesAttempted
* <= 2 ^ 31 - 1, which means retriesAttempted <= 30, so that is the ceil for retriesAttempted.
*/
int RETRIES_ATTEMPTED_CEILING = (int) Math.floor(Math.log(Integer.MAX_VALUE) / Math.log(2));
/**
* Compute the delay before the next retry request. This strategy is only consulted when there will be a next retry.
*
* @param context Context about the state of the last request and information about the number of requests made.
* @return Amount of time in milliseconds to wait before the next attempt. Must be non-negative (can be zero).
*/
Duration computeDelayBeforeNextRetry(RetryPolicyContext context);
default int calculateExponentialDelay(int retriesAttempted, Duration baseDelay, Duration maxBackoffTime) {
int cappedRetries = Math.min(retriesAttempted, RETRIES_ATTEMPTED_CEILING);
return (int) Math.min(baseDelay.multipliedBy(1L << cappedRetries).toMillis(), maxBackoffTime.toMillis());
}
static BackoffStrategy defaultStrategy() {
return defaultStrategy(RetryMode.defaultRetryMode());
}
static BackoffStrategy defaultStrategy(RetryMode retryMode) {
return FullJitterBackoffStrategy.builder()
.baseDelay(SdkDefaultRetrySetting.baseDelay(retryMode))
.maxBackoffTime(SdkDefaultRetrySetting.MAX_BACKOFF)
.build();
}
static BackoffStrategy defaultThrottlingStrategy() {
return defaultThrottlingStrategy(RetryMode.defaultRetryMode());
}
static BackoffStrategy defaultThrottlingStrategy(RetryMode retryMode) {
switch (retryMode) {
case LEGACY:
return EqualJitterBackoffStrategy.builder()
.baseDelay(SdkDefaultRetrySetting.throttledBaseDelay(retryMode))
.maxBackoffTime(SdkDefaultRetrySetting.MAX_BACKOFF)
.build();
case ADAPTIVE:
case STANDARD:
return FullJitterBackoffStrategy.builder()
.baseDelay(SdkDefaultRetrySetting.throttledBaseDelay(retryMode))
.maxBackoffTime(SdkDefaultRetrySetting.MAX_BACKOFF)
.build();
default:
throw new IllegalStateException("Unsupported RetryMode: " + retryMode);
}
}
static BackoffStrategy none() {
return FixedDelayBackoffStrategy.create(Duration.ofMillis(1));
}
}
| 2,088 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/backoff/FixedDelayBackoffStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.backoff;
import static software.amazon.awssdk.utils.Validate.isNotNegative;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
/**
* Simple backoff strategy that always uses a fixed delay for the delay before the next retry attempt.
*/
@SdkPublicApi
public final class FixedDelayBackoffStrategy implements BackoffStrategy {
private final Duration fixedBackoff;
private FixedDelayBackoffStrategy(Duration fixedBackoff) {
this.fixedBackoff = isNotNegative(fixedBackoff, "fixedBackoff");
}
@Override
public Duration computeDelayBeforeNextRetry(RetryPolicyContext context) {
return fixedBackoff;
}
public static FixedDelayBackoffStrategy create(Duration fixedBackoff) {
return new FixedDelayBackoffStrategy(fixedBackoff);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FixedDelayBackoffStrategy that = (FixedDelayBackoffStrategy) o;
return fixedBackoff.equals(that.fixedBackoff);
}
@Override
public int hashCode() {
return fixedBackoff.hashCode();
}
@Override
public String toString() {
return ToString.builder("FixedDelayBackoffStrategy")
.add("fixedBackoff", fixedBackoff)
.build();
}
}
| 2,089 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/TokenBucketRetryCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.conditions;
import static software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting.TOKEN_BUCKET_SIZE;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.internal.capacity.TokenBucket;
import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* A {@link RetryCondition} that limits the number of retries made by the SDK using a token bucket algorithm. "Tokens" are
* acquired from the bucket whenever {@link #shouldRetry} returns true, and are released to the bucket whenever
* {@link #requestSucceeded} or {@link #requestWillNotBeRetried} are invoked.
*
* <p>
* If "tokens" cannot be acquired from the bucket, it means too many requests have failed and the request will not be allowed
* to retry until we start to see initial non-retried requests succeed via {@link #requestSucceeded(RetryPolicyContext)}.
*
* <p>
* This prevents the client from holding the calling thread to retry when it's likely that it will fail anyway.
*
* <p>
* This is currently included in the default {@link RetryPolicy#aggregateRetryCondition()}, but can be disabled by setting the
* {@link RetryPolicy.Builder#retryCapacityCondition} to null.
*/
@SdkPublicApi
public class TokenBucketRetryCondition implements RetryCondition {
private static final Logger log = Logger.loggerFor(TokenBucketRetryCondition.class);
private static final ExecutionAttribute<Capacity> LAST_ACQUIRED_CAPACITY =
new ExecutionAttribute<>("TokenBucketRetryCondition.LAST_ACQUIRED_CAPACITY");
private static final ExecutionAttribute<Integer> RETRY_COUNT_OF_LAST_CAPACITY_ACQUISITION =
new ExecutionAttribute<>("TokenBucketRetryCondition.RETRY_COUNT_OF_LAST_CAPACITY_ACQUISITION");
private final TokenBucket capacity;
private final TokenBucketExceptionCostFunction exceptionCostFunction;
private TokenBucketRetryCondition(Builder builder) {
this.capacity = new TokenBucket(Validate.notNull(builder.tokenBucketSize, "tokenBucketSize"));
this.exceptionCostFunction = Validate.notNull(builder.exceptionCostFunction, "exceptionCostFunction");
}
/**
* Create a condition using the {@link RetryMode#defaultRetryMode()}. This is equivalent to
* {@code forRetryMode(RetryMode.defaultRetryMode())}.
*
* <p>
* For more detailed control, see {@link #builder()}.
*/
public static TokenBucketRetryCondition create() {
return forRetryMode(RetryMode.defaultRetryMode());
}
/**
* Create a condition using the configured {@link RetryMode}. The {@link RetryMode#LEGACY} does not subtract tokens from
* the token bucket when throttling exceptions are encountered. The {@link RetryMode#STANDARD} treats throttling and non-
* throttling exceptions as the same cost.
*
* <p>
* For more detailed control, see {@link #builder()}.
*/
public static TokenBucketRetryCondition forRetryMode(RetryMode retryMode) {
return TokenBucketRetryCondition.builder()
.tokenBucketSize(TOKEN_BUCKET_SIZE)
.exceptionCostFunction(SdkDefaultRetrySetting.tokenCostFunction(retryMode))
.build();
}
/**
* Create a builder that allows fine-grained control over the token policy of this condition.
*/
public static Builder builder() {
return new Builder();
}
/**
* If {@link #shouldRetry(RetryPolicyContext)} returned true for the provided execution, this method returns the
* {@link Capacity} consumed by the request.
*/
public static Optional<Capacity> getCapacityForExecution(ExecutionAttributes attributes) {
return Optional.ofNullable(attributes.getAttribute(LAST_ACQUIRED_CAPACITY));
}
/**
* Retrieve the number of tokens currently available in the token bucket. This is a volatile snapshot of the current value.
* See {@link #getCapacityForExecution(ExecutionAttributes)} to see how much capacity was left in the bucket after a specific
* execution was considered.
*/
public int tokensAvailable() {
return capacity.currentCapacity();
}
@Override
public boolean shouldRetry(RetryPolicyContext context) {
int costOfFailure = exceptionCostFunction.apply(context.exception());
Validate.isTrue(costOfFailure >= 0, "Cost of failure must not be negative, but was " + costOfFailure);
Optional<Capacity> capacity = this.capacity.tryAcquire(costOfFailure);
capacity.ifPresent(c -> {
context.executionAttributes().putAttribute(LAST_ACQUIRED_CAPACITY, c);
context.executionAttributes().putAttribute(RETRY_COUNT_OF_LAST_CAPACITY_ACQUISITION,
context.retriesAttempted());
log.trace(() -> "Successfully acquired token bucket capacity to retry this request. "
+ "Acquired: " + c.capacityAcquired + ". Remaining: " + c.capacityRemaining);
});
boolean hasCapacity = capacity.isPresent();
if (!hasCapacity) {
log.debug(() -> "This request will not be retried because the client has experienced too many recent call failures.");
}
return hasCapacity;
}
@Override
public void requestWillNotBeRetried(RetryPolicyContext context) {
Integer lastAcquisitionRetryCount = context.executionAttributes().getAttribute(RETRY_COUNT_OF_LAST_CAPACITY_ACQUISITION);
if (lastAcquisitionRetryCount != null && context.retriesAttempted() == lastAcquisitionRetryCount) {
// We said yes to "should-retry", but something else caused it not to retry
Capacity lastAcquiredCapacity = context.executionAttributes().getAttribute(LAST_ACQUIRED_CAPACITY);
Validate.validState(lastAcquiredCapacity != null, "Last acquired capacity should not be null.");
capacity.release(lastAcquiredCapacity.capacityAcquired());
}
}
@Override
public void requestSucceeded(RetryPolicyContext context) {
Capacity lastAcquiredCapacity = context.executionAttributes().getAttribute(LAST_ACQUIRED_CAPACITY);
if (lastAcquiredCapacity == null || lastAcquiredCapacity.capacityAcquired() == 0) {
capacity.release(1);
} else {
capacity.release(lastAcquiredCapacity.capacityAcquired());
}
}
@Override
public String toString() {
return ToString.builder("TokenBucketRetryCondition")
.add("capacity", capacity.currentCapacity() + "/" + capacity.maxCapacity())
.add("exceptionCostFunction", exceptionCostFunction)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TokenBucketRetryCondition that = (TokenBucketRetryCondition) o;
if (!capacity.equals(that.capacity)) {
return false;
}
return exceptionCostFunction.equals(that.exceptionCostFunction);
}
@Override
public int hashCode() {
int result = capacity.hashCode();
result = 31 * result + exceptionCostFunction.hashCode();
return result;
}
/**
* Configure and create a {@link TokenBucketRetryCondition}.
*/
public static final class Builder {
private Integer tokenBucketSize;
private TokenBucketExceptionCostFunction exceptionCostFunction;
/**
* Create using {@link TokenBucketRetryCondition#builder()}.
*/
private Builder() {
}
/**
* Specify the maximum number of tokens in the token bucket. This is also used as the initial value for the number of
* tokens in the bucket.
*/
public Builder tokenBucketSize(int tokenBucketSize) {
this.tokenBucketSize = tokenBucketSize;
return this;
}
/**
* Configure a {@link TokenBucketExceptionCostFunction} that is used to calculate the number of tokens that should be
* taken out of the bucket for each specific exception. These tokens will be returned in case of successful retries.
*/
public Builder exceptionCostFunction(TokenBucketExceptionCostFunction exceptionCostFunction) {
this.exceptionCostFunction = exceptionCostFunction;
return this;
}
/**
* Build a {@link TokenBucketRetryCondition} using the provided configuration.
*/
public TokenBucketRetryCondition build() {
return new TokenBucketRetryCondition(this);
}
}
/**
* The number of tokens in the token bucket after a specific token acquisition succeeds. This can be retrieved via
* {@link #getCapacityForExecution(ExecutionAttributes)}.
*/
public static final class Capacity {
private final int capacityAcquired;
private final int capacityRemaining;
private Capacity(Builder builder) {
this.capacityAcquired = Validate.notNull(builder.capacityAcquired, "capacityAcquired");
this.capacityRemaining = Validate.notNull(builder.capacityRemaining, "capacityRemaining");
}
public static Builder builder() {
return new Builder();
}
/**
* The number of tokens acquired by the last token acquisition.
*/
public int capacityAcquired() {
return capacityAcquired;
}
/**
* The number of tokens in the token bucket.
*/
public int capacityRemaining() {
return capacityRemaining;
}
public static class Builder {
private Integer capacityAcquired;
private Integer capacityRemaining;
private Builder() {
}
public Builder capacityAcquired(Integer capacityAcquired) {
this.capacityAcquired = capacityAcquired;
return this;
}
public Builder capacityRemaining(Integer capacityRemaining) {
this.capacityRemaining = capacityRemaining;
return this;
}
public Capacity build() {
return new Capacity(this);
}
}
}
}
| 2,090 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/AndRetryCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.conditions;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Composite {@link RetryCondition} that evaluates to true when all contained retry conditions evaluate to true.
*/
@SdkPublicApi
public final class AndRetryCondition implements RetryCondition {
private final Set<RetryCondition> conditions = new LinkedHashSet<>();
private AndRetryCondition(RetryCondition... conditions) {
Collections.addAll(this.conditions, Validate.notEmpty(conditions, "%s cannot be empty.", "conditions"));
}
public static AndRetryCondition create(RetryCondition... conditions) {
return new AndRetryCondition(conditions);
}
/**
* @return True if all conditions are true, false otherwise.
*/
@Override
public boolean shouldRetry(RetryPolicyContext context) {
return conditions.stream().allMatch(r -> r.shouldRetry(context));
}
@Override
public void requestWillNotBeRetried(RetryPolicyContext context) {
conditions.forEach(c -> c.requestWillNotBeRetried(context));
}
@Override
public void requestSucceeded(RetryPolicyContext context) {
conditions.forEach(c -> c.requestSucceeded(context));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AndRetryCondition that = (AndRetryCondition) o;
return conditions.equals(that.conditions);
}
@Override
public int hashCode() {
return conditions.hashCode();
}
@Override
public String toString() {
return ToString.builder("AndRetryCondition")
.add("conditions", conditions)
.build();
}
}
| 2,091 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/SdkRetryCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.conditions;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting;
import software.amazon.awssdk.core.retry.RetryUtils;
/**
* Contains predefined {@link RetryCondition} provided by SDK.
*/
@SdkProtectedApi
public final class SdkRetryCondition {
public static final RetryCondition DEFAULT = OrRetryCondition.create(
RetryOnStatusCodeCondition.create(SdkDefaultRetrySetting.RETRYABLE_STATUS_CODES),
RetryOnExceptionsCondition.create(SdkDefaultRetrySetting.RETRYABLE_EXCEPTIONS),
c -> RetryUtils.isClockSkewException(c.exception()),
c -> RetryUtils.isThrottlingException(c.exception()));
public static final RetryCondition NONE = MaxNumberOfRetriesCondition.create(0);
private SdkRetryCondition() {
}
}
| 2,092 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/TokenBucketExceptionCostFunction.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.conditions;
import java.util.function.Function;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.internal.retry.DefaultTokenBucketExceptionCostFunction;
/**
* A function used by {@link TokenBucketRetryCondition} to determine how many tokens should be removed from the bucket when an
* exception is encountered. This can be implemented directly, or using the helper methods provided by the {@link #builder()}.
*/
@SdkPublicApi
@FunctionalInterface
@ThreadSafe
public interface TokenBucketExceptionCostFunction extends Function<SdkException, Integer> {
/**
* Create an exception cost function using exception type matchers built into the SDK. This interface may be implemented
* directly, or created via a builder.
*/
static Builder builder() {
return new DefaultTokenBucketExceptionCostFunction.Builder();
}
/**
* A helper that can be used to assign exception costs to specific exception types, created via {@link #builder()}.
*/
@NotThreadSafe
interface Builder {
/**
* Specify the number of tokens that should be removed from the token bucket when throttling exceptions (e.g. HTTP status
* code 429) are encountered.
*/
Builder throttlingExceptionCost(int cost);
/**
* Specify the number of tokens that should be removed from the token bucket when no other exception type in this
* function is matched. This field is required.
*/
Builder defaultExceptionCost(int cost);
/**
* Create a {@link TokenBucketExceptionCostFunction} using the values configured on this builder.
*/
TokenBucketExceptionCostFunction build();
}
}
| 2,093 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/RetryOnThrottlingCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.conditions;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.core.retry.RetryUtils;
import software.amazon.awssdk.utils.ToString;
/**
* A {@link RetryCondition} that will return true if the provided exception seems to be due to a throttling error from the
* service to the client.
*/
@SdkPublicApi
public final class RetryOnThrottlingCondition implements RetryCondition {
private RetryOnThrottlingCondition() {
}
public static RetryOnThrottlingCondition create() {
return new RetryOnThrottlingCondition();
}
@Override
public boolean shouldRetry(RetryPolicyContext context) {
return RetryUtils.isThrottlingException(context.exception());
}
@Override
public String toString() {
return ToString.create("RetryOnThrottlingCondition");
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
return o != null && getClass() == o.getClass();
}
@Override
public int hashCode() {
return 0;
}
}
| 2,094 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/RetryCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.conditions;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
@SdkPublicApi
@FunctionalInterface
public interface RetryCondition {
/**
* Determine whether a request should or should not be retried.
*
* @param context Context about the state of the last request and information about the number of requests made.
* @return True if the request should be retried, false if not.
*/
boolean shouldRetry(RetryPolicyContext context);
/**
* Called by the SDK to notify this condition that the provided request will not be retried, because some retry condition
* determined that it shouldn't be retried.
*/
default void requestWillNotBeRetried(RetryPolicyContext context) {
}
/**
* Called by the SDK to notify this condition that the provided request succeeded. This method is invoked even if the
* execution never failed before ({@link RetryPolicyContext#retriesAttempted()} is zero).
*/
default void requestSucceeded(RetryPolicyContext context) {
}
static RetryCondition defaultRetryCondition() {
return OrRetryCondition.create(
RetryOnStatusCodeCondition.create(SdkDefaultRetrySetting.RETRYABLE_STATUS_CODES),
RetryOnExceptionsCondition.create(SdkDefaultRetrySetting.RETRYABLE_EXCEPTIONS),
RetryOnClockSkewCondition.create(),
RetryOnThrottlingCondition.create());
}
/**
* A retry condition that will NEVER allow retries.
*/
static RetryCondition none() {
return MaxNumberOfRetriesCondition.create(0);
}
}
| 2,095 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/RetryOnClockSkewCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.conditions;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.core.retry.RetryUtils;
import software.amazon.awssdk.utils.ToString;
/**
* A {@link RetryCondition} that will return true if the provided exception seems to be due to a clock skew between the
* client and service.
*/
@SdkPublicApi
public final class RetryOnClockSkewCondition implements RetryCondition {
private RetryOnClockSkewCondition() {
}
public static RetryOnClockSkewCondition create() {
return new RetryOnClockSkewCondition();
}
@Override
public boolean shouldRetry(RetryPolicyContext context) {
return RetryUtils.isClockSkewException(context.exception());
}
@Override
public String toString() {
return ToString.create("RetryOnClockSkewCondition");
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
return o != null && getClass() == o.getClass();
}
@Override
public int hashCode() {
return 0;
}
}
| 2,096 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/RetryOnStatusCodeCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.conditions;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Retry condition implementation that retries if the HTTP status code matches one of the provided status codes.
*/
@SdkPublicApi
public final class RetryOnStatusCodeCondition implements RetryCondition {
private final Set<Integer> statusCodesToRetryOn;
private RetryOnStatusCodeCondition(Set<Integer> statusCodesToRetryOn) {
this.statusCodesToRetryOn = new HashSet<>(
Validate.paramNotNull(statusCodesToRetryOn, "statusCodesToRetryOn"));
}
/**
* @param context Context about the state of the last request and information about the number of requests made.
* @return True if the HTTP status code matches one of the provided status codes. False if it doesn't match or the request
* failed for reasons other than an exceptional HTTP response (i.e. IOException).
*/
@Override
public boolean shouldRetry(RetryPolicyContext context) {
return Optional.ofNullable(context.httpStatusCode()).map(s ->
statusCodesToRetryOn.stream().anyMatch(code -> code.equals(s))).orElse(false);
}
public static RetryOnStatusCodeCondition create(Set<Integer> statusCodesToRetryOn) {
return new RetryOnStatusCodeCondition(statusCodesToRetryOn);
}
public static RetryOnStatusCodeCondition create(Integer... statusCodesToRetryOn) {
return new RetryOnStatusCodeCondition(Arrays.stream(statusCodesToRetryOn).collect(Collectors.toSet()));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RetryOnStatusCodeCondition that = (RetryOnStatusCodeCondition) o;
return statusCodesToRetryOn.equals(that.statusCodesToRetryOn);
}
@Override
public int hashCode() {
return statusCodesToRetryOn.hashCode();
}
@Override
public String toString() {
return ToString.builder("RetryOnStatusCodeCondition")
.add("statusCodesToRetryOn", statusCodesToRetryOn)
.build();
}
}
| 2,097 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/RetryOnExceptionsCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.conditions;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
/**
* Retry condition implementation that retries if the exception or the cause of the exception matches the classes defined.
*/
@SdkPublicApi
public final class RetryOnExceptionsCondition implements RetryCondition {
private final Set<Class<? extends Exception>> exceptionsToRetryOn;
/**
* @param exceptionsToRetryOn Exception classes to retry on.
*/
private RetryOnExceptionsCondition(Set<Class<? extends Exception>> exceptionsToRetryOn) {
this.exceptionsToRetryOn = new HashSet<>(exceptionsToRetryOn);
}
/**
* @param context Context about the state of the last request and information about the number of requests made.
* @return True if the exception class or the cause of the exception matches one of the exceptions supplied at
* initialization time.
*/
@Override
public boolean shouldRetry(RetryPolicyContext context) {
SdkException exception = context.exception();
if (exception == null) {
return false;
}
Predicate<Class<? extends Exception>> isRetryableException =
ex -> ex.isAssignableFrom(exception.getClass());
Predicate<Class<? extends Exception>> hasRetryableCause =
ex -> exception.getCause() != null && ex.isAssignableFrom(exception.getCause().getClass());
return exceptionsToRetryOn.stream().anyMatch(isRetryableException.or(hasRetryableCause));
}
/**
* @param exceptionsToRetryOn Exception classes to retry on.
*/
public static RetryOnExceptionsCondition create(Set<Class<? extends Exception>> exceptionsToRetryOn) {
return new RetryOnExceptionsCondition(exceptionsToRetryOn);
}
/**
* @param exceptionsToRetryOn Exception classes to retry on.
*/
public static RetryOnExceptionsCondition create(Class<? extends Exception>... exceptionsToRetryOn) {
return new RetryOnExceptionsCondition(Arrays.stream(exceptionsToRetryOn).collect(Collectors.toSet()));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RetryOnExceptionsCondition that = (RetryOnExceptionsCondition) o;
return exceptionsToRetryOn.equals(that.exceptionsToRetryOn);
}
@Override
public int hashCode() {
return exceptionsToRetryOn.hashCode();
}
@Override
public String toString() {
return ToString.builder("RetryOnExceptionsCondition")
.add("exceptionsToRetryOn", exceptionsToRetryOn)
.build();
}
}
| 2,098 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/OrRetryCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.retry.conditions;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
/**
* Composite retry condition that evaluates to true if any containing condition evaluates to true.
*/
@SdkPublicApi
public final class OrRetryCondition implements RetryCondition {
private final Set<RetryCondition> conditions = new LinkedHashSet<>();
private OrRetryCondition(RetryCondition... conditions) {
Collections.addAll(this.conditions, conditions);
}
public static OrRetryCondition create(RetryCondition... conditions) {
return new OrRetryCondition(conditions);
}
/**
* @return True if any condition returns true. False otherwise.
*/
@Override
public boolean shouldRetry(RetryPolicyContext context) {
return conditions.stream().anyMatch(r -> r.shouldRetry(context));
}
@Override
public void requestWillNotBeRetried(RetryPolicyContext context) {
conditions.forEach(c -> c.requestWillNotBeRetried(context));
}
@Override
public void requestSucceeded(RetryPolicyContext context) {
conditions.forEach(c -> c.requestSucceeded(context));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrRetryCondition that = (OrRetryCondition) o;
return conditions.equals(that.conditions);
}
@Override
public int hashCode() {
return conditions.hashCode();
}
@Override
public String toString() {
return ToString.builder("OrRetryCondition")
.add("conditions", conditions)
.build();
}
}
| 2,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.