src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
IntermediateModel { public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } IntermediateModel(); IntermediateModel(Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig); IntermediateModel(
Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig,
OperationModel endpointOperation,
Map<String, AuthorizerModel> customAuthorizers,
Map<String, PaginatorDefinition> paginators,
NamingStrategy namingStrategy,
Map<String, WaiterDefinition> waiters); Metadata getMetadata(); void setMetadata(Metadata metadata); Map<String, OperationModel> getOperations(); void setOperations(Map<String, OperationModel> operations); OperationModel getOperation(String operationName); Map<String, ShapeModel> getShapes(); void setShapes(Map<String, ShapeModel> shapes); ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName); CustomizationConfig getCustomizationConfig(); void setCustomizationConfig(CustomizationConfig customizationConfig); Map<String, PaginatorDefinition> getPaginators(); Map<String, WaiterDefinition> getWaiters(); void setPaginators(Map<String, PaginatorDefinition> paginators); NamingStrategy getNamingStrategy(); void setNamingStrategy(NamingStrategy namingStrategy); String getCustomRetryPolicy(); String getSdkModeledExceptionBaseFqcn(); String getSdkModeledExceptionBaseClassName(); String getSdkRequestBaseClassName(); String getSdkResponseBaseClassName(); String getFileHeader(); String getSdkBaseResponseFqcn(); @JsonIgnore List<OperationModel> simpleMethodsRequiringTesting(); Map<String, AuthorizerModel> getCustomAuthorizers(); void setCustomAuthorizers(Map<String, AuthorizerModel> customAuthorizers); Optional<OperationModel> getEndpointOperation(); void setEndpointOperation(OperationModel endpointOperation); boolean hasPaginators(); boolean hasWaiters(); boolean containsRequestSigners(); boolean containsRequestEventStreams(); } | @Test public void cannotFindShapeWhenNoShapesExist() { ServiceMetadata metadata = new ServiceMetadata(); metadata.setProtocol(Protocol.REST_JSON.getValue()); metadata.setServiceId("empty-service"); metadata.setSignatureVersion("V4"); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(new ServiceModel(metadata, Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap())) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertThatThrownBy(() -> testModel.getShapeByNameAndC2jName("AnyShape", "AnyShape")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("C2J shape AnyShape with shape name AnyShape does not exist in the intermediate model."); }
@Test public void getShapeByNameAndC2jNameVerifiesC2JName() { final File modelFile = new File(IntermediateModelTest.class .getResource("../../poet/client/c2j/shared-output/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertThatThrownBy(() -> testModel.getShapeByNameAndC2jName("PingResponse", "AnyShape")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("C2J shape AnyShape with shape name PingResponse does not exist in the intermediate model."); } |
DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | @Test public void canConvertStringsWithNonAlphasToClassNames() { String anInvalidClassName = "a phrase-With_other.delimiters"; assertThat(strat.getJavaClassName(anInvalidClassName)).isEqualTo("APhraseWithOtherDelimiters"); }
@Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithUnderscore() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("_MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); }
@Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithDoubleUnderscore() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("__MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); }
@Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithDoublePeriods() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("..MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); }
@Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithDoubleDashes() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("--MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); }
@Test public void getJavaClassName_ReturnsSanitizedName_DoubleUnderscoresInClass() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("My__Class"); assertThat(javaClassName).isEqualTo("MyClass"); }
@Test public void getJavaClassName_ReturnsSanitizedName_DoublePeriodsInClass() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("My..Class"); assertThat(javaClassName).isEqualTo("MyClass"); }
@Test public void getJavaClassName_ReturnsSanitizedName_DoubleDashesInClass() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("My--Class"); assertThat(javaClassName).isEqualTo("MyClass"); } |
DefaultNamingStrategy implements NamingStrategy { @Override public String getAuthorizerClassName(String shapeName) { String converted = getJavaClassName(shapeName); if (converted.length() > 0 && !Character.isLetter(converted.charAt(0))) { return AUTHORIZER_NAME_PREFIX + converted; } return converted; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | @Test public void canConvertAuthorizerStartingWithNumber() { String anInvalidClassName = "35-authorizer-implementation"; assertThat(strat.getAuthorizerClassName(anInvalidClassName)).isEqualTo("I35AuthorizerImplementation"); } |
DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | @Test public void test_GetFluentSetterMethodName_NoEnum() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShape.getEnumValues()).thenReturn(null); when(mockShape.getType()).thenReturn("foo"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethod"); }
@Test public void test_GetFluentSetterMethodName_NoEnum_WithList() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShapeMap.get(eq("MockShape"))).thenReturn(mockShape); when(mockShapeMap.get(eq("MockStringShape"))).thenReturn(mockStringShape); when(mockShape.getEnumValues()).thenReturn(null); when(mockShape.getType()).thenReturn("list"); when(mockShape.getListMember()).thenReturn(member); when(mockStringShape.getEnumValues()).thenReturn(null); when(mockStringShape.getType()).thenReturn("string"); when(member.getShape()).thenReturn("MockStringShape"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethod"); }
@Test public void test_GetFluentSetterMethodName_WithEnumShape_NoListOrMap() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShapeMap.get(any())).thenReturn(mockShape); when(mockShape.getEnumValues()).thenReturn(new ArrayList<>()); when(mockShape.getType()).thenReturn("foo"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethod"); }
@Test public void test_GetFluentSetterMethodName_WithEnumShape_WithList() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShapeMap.get(eq("MockShape"))).thenReturn(mockShape); when(mockShapeMap.get(eq("MockStringShape"))).thenReturn(mockStringShape); when(mockShape.getEnumValues()).thenReturn(null); when(mockShape.getType()).thenReturn("list"); when(mockShape.getListMember()).thenReturn(member); when(mockStringShape.getEnumValues()).thenReturn(Arrays.asList("Enum1", "Enum2")); when(mockStringShape.getType()).thenReturn("string"); when(member.getShape()).thenReturn("MockStringShape"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethodWithStrings"); } |
AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } | @Test public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); PutObjectResponse response = PutObjectResponse.builder() .eTag(VALID_CHECKSUM) .build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder() .build(); SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.PUT) .build(); Context.AfterUnmarshalling afterUnmarshallingContext = InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse); interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum()); }
@Test public void afterUnmarshalling_putObjectRequest_with_SSE_shouldNotValidateChecksum() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); PutObjectResponse response = PutObjectResponse.builder() .eTag(INVALID_CHECKSUM) .build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder().build(); SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder() .putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString()) .putHeader("x-amz-server-side-encryption-aws-kms-key-id", ENABLE_MD5_CHECKSUM_HEADER_VALUE) .uri(URI.create("http: .method(SdkHttpMethod.PUT) .build(); Context.AfterUnmarshalling afterUnmarshallingContext = InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse); interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum()); } |
DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | @Test public void getServiceName_Uses_ServiceId() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn("Foo"); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); assertThat(strat.getServiceName()).isEqualTo("Foo"); }
@Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdIsNull() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(null); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); strat.getServiceName(); }
@Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdIsEmpty() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(""); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); strat.getServiceName(); }
@Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdHasWhiteSpace() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(" "); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); strat.getServiceName(); } |
DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | @Test public void getSdkFieldFieldName_SingleWord() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("foo"))) .isEqualTo("FOO_FIELD"); }
@Test public void getSdkFieldFieldName_CamalCaseConvertedToScreamCase() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("fooBar"))) .isEqualTo("FOO_BAR_FIELD"); }
@Test public void getSdkFieldFieldName_PascalCaseConvertedToScreamCase() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("FooBar"))) .isEqualTo("FOO_BAR_FIELD"); } |
IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); IntermediateModel build(); CustomizationConfig getCustomConfig(); ServiceModel getService(); NamingStrategy getNamingStrategy(); TypeUtils getTypeUtils(); Paginators getPaginators(); } | @Test public void testServiceAndShapeNameCollisions() throws Exception { final File modelFile = new File(IntermediateModelBuilderTest.class .getResource("poet/client/c2j/collision/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertThat(testModel.getShapes().values()) .extracting(ShapeModel::getShapeName) .containsExactlyInAnyOrder("DefaultCollisionException", "DefaultCollisionRequest", "DefaultCollisionResponse"); }
@Test public void sharedOutputShapesLinkCorrectlyToOperationOutputs() { final File modelFile = new File(IntermediateModelBuilderTest.class .getResource("poet/client/c2j/shared-output/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertEquals("PingResponse", testModel.getOperation("Ping").getOutputShape().getShapeName()); assertEquals("SecurePingResponse", testModel.getOperation("SecurePing").getOutputShape().getShapeName()); }
@Test public void defaultEndpointDiscovery_true() { final File modelFile = new File(IntermediateModelBuilderTest.class .getResource("poet/client/c2j/endpointdiscovery/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertTrue(testModel.getEndpointOperation().get().isEndpointCacheRequired()); }
@Test public void defaultEndpointDiscovery_false() { final File modelFile = new File(IntermediateModelBuilderTest.class .getResource("poet/client/c2j/endpointdiscoveryoptional/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertFalse(testModel.getEndpointOperation().get().isEndpointCacheRequired()); } |
PutObjectInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof PutObjectRequest) { return context.httpRequest().toBuilder().putHeader("Expect", "100-continue").build(); } return context.httpRequest(); } @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); } | @Test public void modifyHttpRequest_setsExpect100Continue_whenSdkRequestIsPutObject() { final SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext(PutObjectRequest.builder().build()), new ExecutionAttributes()); assertThat(modifiedRequest.firstMatchingHeader("Expect")).hasValue("100-continue"); }
@Test public void modifyHttpRequest_doesNotSetExpect_whenSdkRequestIsNotPutObject() { final SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext(GetObjectRequest.builder().build()), new ExecutionAttributes()); assertThat(modifiedRequest.firstMatchingHeader("Expect")).isNotPresent(); } |
DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } private DocumentationUtils(); static String stripHtmlTags(String documentation); static String escapeIllegalCharacters(String documentation); static String createLinkToServiceDocumentation(Metadata metadata, String name); static String createLinkToServiceDocumentation(Metadata metadata, ShapeModel shapeModel); static String removeFromEnd(String string, String stringToRemove); static String defaultSetter(); static String defaultSetterParam(); static String defaultGetter(); static String defaultGetterParam(); static String defaultFluentReturn(); static String defaultExistenceCheck(); } | @Test public void strip_html_tags_null_or_empty_input_returns_empty_string() { Assert.assertThat(DocumentationUtils.stripHtmlTags(null), Matchers .isEmptyString()); Assert.assertThat(DocumentationUtils.stripHtmlTags(""), Matchers .isEmptyString()); }
@Test public void html_tags_at_start_of_string_are_removed() { Assert.assertEquals("foo", DocumentationUtils.stripHtmlTags ("<bar>foo</bar>")); }
@Test public void empty_html_tags_at_start_are_removed() { Assert.assertThat(DocumentationUtils.stripHtmlTags("<p></p>"), Matchers .isEmptyString()); Assert.assertThat(DocumentationUtils.stripHtmlTags("<p/>"), Matchers .isEmptyString()); } |
Utils { public static String unCapitalize(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } StringBuilder sb = new StringBuilder(name.length()); int i = 0; do { sb.append(Character.toLowerCase(name.charAt(i++))); } while ((i < name.length() && Character.isUpperCase(name.charAt(i))) && !(i < name.length() - 1 && Character.isLowerCase(name.charAt(i + 1)))); sb.append(name.substring(i)); return sb.toString(); } private Utils(); static boolean isScalar(Shape shape); static boolean isStructure(Shape shape); static boolean isListShape(Shape shape); static boolean isMapShape(Shape shape); static boolean isEnumShape(Shape shape); static boolean isExceptionShape(Shape shape); static boolean isOrContainsEnumShape(Shape shape, Map<String, Shape> allShapes); static boolean isOrContainsEnum(MemberModel member); static boolean isListWithEnumShape(MemberModel member); static boolean isMapWithEnumShape(MemberModel member); static boolean isMapKeyWithEnumShape(MapModel mapModel); static boolean isMapValueWithEnumShape(MapModel mapModel); static String unCapitalize(String name); static String capitalize(String name); static String removeLeading(String str, String toRemove); static String removeTrailing(String str, String toRemove); static String getFileNamePrefix(ServiceModel serviceModel); static String directoryToPackage(String directoryPath); static String packageToDirectory(String packageName); static String getDefaultEndpointWithoutHttpProtocol(String endpoint); static File createDirectory(String path); static void createDirectory(File dir); static File createFile(String dir, String fileName); static boolean isNullOrEmpty(String str); static void closeQuietly(Closeable closeable); static InputStream getRequiredResourceAsStream(Class<?> clzz, String location); static ShapeModel findShapeModelByC2jName(IntermediateModel intermediateModel, String shapeC2jName); static ShapeModel findShapeModelByC2jNameIfExists(IntermediateModel intermediateModel, String shapeC2jName); static ShapeModel findMemberShapeModelByC2jNameIfExists(IntermediateModel intermediateModel, String shapeC2jName); static List<ShapeModel> findShapesByC2jName(IntermediateModel intermediateModel, String shapeC2jName); static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation); } | @Test public void testUnCapitalize() { capitalizedToUncapitalized.forEach((capitalized,unCapitalized) -> assertThat(Utils.unCapitalize(capitalized), is(equalTo(unCapitalized)))); } |
UnusedImportRemover implements CodeTransformer { @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } @Override String apply(String content); } | @Test public void unusedImportsAreRemoved() throws Exception { String content = loadFileContents(FILE_WITH_UNUSED_IMPORTS_JAVA); String expected = loadFileContents(FILE_WITHOUT_UNUSED_IMPORTS_JAVA); String result = sut.apply(content); assertThat(result, equalToIgnoringWhiteSpace(expected)); }
@Test public void nonJavaContentIsIgnored() throws Exception { String jsonContent = "{ \"SomeKey\": 4, \"ADict\": { \"SubKey\": \"Subvalue\" } }"; String result = sut.apply(jsonContent); assertThat(result, equalTo(jsonContent)); } |
ResponseMetadataSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } ResponseMetadataSpec(IntermediateModel model); @Override TypeSpec poetSpec(); @Override ClassName className(); } | @Test public void responseMetadataGeneration() { ResponseMetadataSpec spec = new ResponseMetadataSpec(model); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); AwsServiceBaseResponseSpec responseSpec = new AwsServiceBaseResponseSpec(model); assertThat(responseSpec, generatesTo(responseSpec.className().simpleName().toLowerCase() + ".java")); }
@Test public void customResponseMetadataGeneration() { ResponseMetadataSpec spec = new ResponseMetadataSpec(modelWithCustomizedResponseMetadata); assertThat(spec, generatesTo("./customresponsemetadata/" + spec.className().simpleName().toLowerCase() + ".java")); AwsServiceBaseResponseSpec responseSpec = new AwsServiceBaseResponseSpec(modelWithCustomizedResponseMetadata); assertThat(responseSpec, generatesTo("./customresponsemetadata/" + responseSpec.className().simpleName().toLowerCase() + ".java")); } |
AwsServiceBaseResponseSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getModelClass(intermediateModel.getSdkResponseBaseClassName()); } AwsServiceBaseResponseSpec(IntermediateModel intermediateModel); @Override TypeSpec poetSpec(); @Override ClassName className(); } | @Test public void testGeneration() { AwsServiceBaseResponseSpec spec = new AwsServiceBaseResponseSpec(intermediateModel); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); } |
AwsServiceBaseRequestSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getModelClass(intermediateModel.getSdkRequestBaseClassName()); } AwsServiceBaseRequestSpec(IntermediateModel intermediateModel); @Override TypeSpec poetSpec(); @Override ClassName className(); } | @Test public void testGeneration() { AwsServiceBaseRequestSpec spec = new AwsServiceBaseRequestSpec(intermediateModel); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); } |
PoetCollectors { public static Collector<CodeBlock, ?, CodeBlock> toCodeBlock() { return Collector.of(CodeBlock::builder, CodeBlock.Builder::add, PoetCollectors::parallelNotSupported, CodeBlock.Builder::build); } private PoetCollectors(); static Collector<CodeBlock, ?, CodeBlock> toCodeBlock(); static Collector<CodeBlock, ?, CodeBlock> toDelimitedCodeBlock(String delimiter); } | @Test public void emptyCollectIsEmptyCodeBlock() { CodeBlock result = Stream.<CodeBlock>of().collect(PoetCollectors.toCodeBlock()); assertThat(result).isEqualTo(CodeBlock.builder().build()); }
@Test public void codeBlocksJoined() { CodeBlock a = CodeBlock.of("a"); CodeBlock b = CodeBlock.of("b"); CodeBlock ab = CodeBlock.builder().add(a).add(b).build(); CodeBlock result = Stream.of(a, b).collect(PoetCollectors.toCodeBlock()); assertThat(result).isEqualTo(ab); } |
PoetCollectors { public static Collector<CodeBlock, ?, CodeBlock> toDelimitedCodeBlock(String delimiter) { return Collector.of(() -> new CodeBlockJoiner(delimiter), CodeBlockJoiner::add, PoetCollectors::parallelNotSupported, CodeBlockJoiner::join); } private PoetCollectors(); static Collector<CodeBlock, ?, CodeBlock> toCodeBlock(); static Collector<CodeBlock, ?, CodeBlock> toDelimitedCodeBlock(String delimiter); } | @Test public void emptyDelimitedCollectIsEmptyCodeBlock() { CodeBlock result = Stream.<CodeBlock>of().collect(PoetCollectors.toDelimitedCodeBlock(",")); assertThat(result).isEqualTo(CodeBlock.builder().build()); }
@Test public void delimitedCodeBlocksJoined() { CodeBlock a = CodeBlock.of("a"); CodeBlock b = CodeBlock.of("b"); CodeBlock delimeter = CodeBlock.of(","); CodeBlock ab = CodeBlock.builder().add(a).add(delimeter).add(b).build(); CodeBlock result = Stream.of(a, b).collect(PoetCollectors.toDelimitedCodeBlock(",")); assertThat(result).isEqualTo(ab); } |
EndpointDiscoveryCacheLoaderGenerator implements ClassSpec { private MethodSpec create() { return MethodSpec.methodBuilder("create") .addModifiers(STATIC, PUBLIC) .returns(className()) .addParameter(poetExtensions.getClientClass(model.getMetadata().getSyncInterface()), CLIENT_FIELD) .addStatement("return new $T($L)", className(), CLIENT_FIELD) .build(); } EndpointDiscoveryCacheLoaderGenerator(GeneratorTaskParams generatorTaskParams); @Override TypeSpec poetSpec(); @Override ClassName className(); } | @Test public void syncEndpointDiscoveryCacheLoaderGenerator() { IntermediateModel model = ClientTestModels.endpointDiscoveryModels(); GeneratorTaskParams dependencies = GeneratorTaskParams.create(model, "sources/", "tests/"); EndpointDiscoveryCacheLoaderGenerator cacheLoader = new EndpointDiscoveryCacheLoaderGenerator(dependencies); assertThat(cacheLoader, generatesTo("test-sync-cache-loader.java")); }
@Test public void asyncEndpointDiscoveryCacheLoaderGenerator() { IntermediateModel model = ClientTestModels.endpointDiscoveryModels(); GeneratorTaskParams dependencies = GeneratorTaskParams.create(model, "sources/", "tests/"); EndpointDiscoveryAsyncCacheLoaderGenerator cacheLoader = new EndpointDiscoveryAsyncCacheLoaderGenerator(dependencies); assertThat(cacheLoader, generatesTo("test-async-cache-loader.java")); } |
Crc32Validation { public static SdkHttpFullResponse validate(boolean calculateCrc32FromCompressedData, SdkHttpFullResponse httpResponse) { if (!httpResponse.content().isPresent()) { return httpResponse; } return httpResponse.toBuilder().content( process(calculateCrc32FromCompressedData, httpResponse, httpResponse.content().get())).build(); } private Crc32Validation(); static SdkHttpFullResponse validate(boolean calculateCrc32FromCompressedData,
SdkHttpFullResponse httpResponse); } | @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 = getField(adapted.content().get(), "in"); assertThat(in).isInstanceOf((GZIPInputStream.class)); } } |
IdempotentUtils { @Deprecated @SdkProtectedApi public static String resolveString(String token) { return token != null ? token : generator.get(); } private IdempotentUtils(); @Deprecated @SdkProtectedApi static String resolveString(String token); @SdkProtectedApi static Supplier<String> getGenerator(); @SdkTestInternalApi static void setGenerator(Supplier<String> newGenerator); } | @Test public void resolveString_returns_givenString_when_nonnullString_is_passed() { String idempotencyToken = "120c7d4a-e982-4323-a53e-28989a0a9f26"; assertEquals(idempotencyToken, IdempotentUtils.resolveString(idempotencyToken)); }
@Test public void resolveString_returns_emptyString_when_emptyString_is_passed() { String idempotencyToken = ""; assertEquals(idempotencyToken, IdempotentUtils.resolveString(idempotencyToken)); }
@Test public void resolveString_returns_newUniqueToken_when_nullString_is_passed() { assertNotNull(IdempotentUtils.resolveString(null)); } |
GetBucketPolicyInterceptor implements ExecutionInterceptor { @Override public Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (INTERCEPTOR_CONTEXT_PREDICATE.test(context)) { String policy = context.responseBody() .map(r -> invokeSafely(() -> IoUtils.toUtf8String(r))) .orElse(null); if (policy != null) { String xml = XML_ENVELOPE_PREFIX + policy + XML_ENVELOPE_SUFFIX; return Optional.of(AbortableInputStream.create(new StringInputStream(xml))); } } return context.responseBody(); } @Override Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); } | @Test public void getBucketPolicy_shouldModifyResponseContent() { GetBucketPolicyRequest request = GetBucketPolicyRequest.builder().build(); Context.ModifyHttpResponse context = modifyHttpResponseContent(request, SdkHttpResponse.builder() .statusCode(200) .build()); Optional<InputStream> inputStream = interceptor.modifyHttpResponseContent(context, new ExecutionAttributes()); assertThat(inputStream).isNotEqualTo(context.responseBody()); }
@Test public void nonGetBucketPolicyResponse_ShouldNotModifyResponse() { GetObjectRequest request = GetObjectRequest.builder().build(); Context.ModifyHttpResponse context = modifyHttpResponseContent(request, SdkHttpResponse.builder().statusCode(200).build()); Optional<InputStream> inputStream = interceptor.modifyHttpResponseContent(context, new ExecutionAttributes()); assertThat(inputStream).isEqualTo(context.responseBody()); }
@Test public void errorResponseShouldNotModifyResponse() { GetBucketPolicyRequest request = GetBucketPolicyRequest.builder().build(); Context.ModifyHttpResponse context = modifyHttpResponseContent(request, SdkHttpResponse.builder().statusCode(404).build()); Optional<InputStream> inputStream = interceptor.modifyHttpResponseContent(context, new ExecutionAttributes()); assertThat(inputStream).isEqualTo(context.responseBody()); } |
DefaultSdkAutoConstructList implements SdkAutoConstructList<T> { @Override public boolean equals(Object o) { return impl.equals(o); } private DefaultSdkAutoConstructList(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructList<T> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<T> iterator(); @Override Object[] toArray(); @Override T1[] toArray(T1[] a); @Override boolean add(T t); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean addAll(int index, Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override T get(int index); @Override T set(int index, T element); @Override void add(int index, T element); @Override T remove(int index); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override ListIterator<T> listIterator(); @Override ListIterator<T> listIterator(int index); @Override List<T> subList(int fromIndex, int toIndex); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void equals_emptyList() { assertThat(INSTANCE.equals(new LinkedList<>())).isTrue(); } |
DefaultSdkAutoConstructList implements SdkAutoConstructList<T> { @Override public int hashCode() { return impl.hashCode(); } private DefaultSdkAutoConstructList(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructList<T> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<T> iterator(); @Override Object[] toArray(); @Override T1[] toArray(T1[] a); @Override boolean add(T t); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean addAll(int index, Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override T get(int index); @Override T set(int index, T element); @Override void add(int index, T element); @Override T remove(int index); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override ListIterator<T> listIterator(); @Override ListIterator<T> listIterator(int index); @Override List<T> subList(int fromIndex, int toIndex); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void hashCode_sameAsEmptyList() { assertThat(INSTANCE.hashCode()).isEqualTo(new LinkedList<>().hashCode()); assertThat(INSTANCE.hashCode()).isEqualTo(1); } |
DefaultSdkAutoConstructList implements SdkAutoConstructList<T> { @Override public String toString() { return impl.toString(); } private DefaultSdkAutoConstructList(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructList<T> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<T> iterator(); @Override Object[] toArray(); @Override T1[] toArray(T1[] a); @Override boolean add(T t); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean addAll(int index, Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override T get(int index); @Override T set(int index, T element); @Override void add(int index, T element); @Override T remove(int index); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override ListIterator<T> listIterator(); @Override ListIterator<T> listIterator(int index); @Override List<T> subList(int fromIndex, int toIndex); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void toString_emptyList() { assertThat(INSTANCE.toString()).isEqualTo("[]"); } |
DefaultSdkAutoConstructMap implements SdkAutoConstructMap<K, V> { @Override public boolean equals(Object o) { return impl.equals(o); } private DefaultSdkAutoConstructMap(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructMap<K, V> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override V put(K key, V value); @Override V remove(Object key); @Override void putAll(Map<? extends K, ? extends V> m); @Override void clear(); @Override Set<K> keySet(); @Override Collection<V> values(); @Override Set<Entry<K, V>> entrySet(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void equal_emptyMap() { assertThat(AUTO_CONSTRUCT_MAP.equals(new HashMap<>())).isTrue(); } |
DefaultSdkAutoConstructMap implements SdkAutoConstructMap<K, V> { @Override public int hashCode() { return impl.hashCode(); } private DefaultSdkAutoConstructMap(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructMap<K, V> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override V put(K key, V value); @Override V remove(Object key); @Override void putAll(Map<? extends K, ? extends V> m); @Override void clear(); @Override Set<K> keySet(); @Override Collection<V> values(); @Override Set<Entry<K, V>> entrySet(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void hashCode_sameAsEmptyMap() { assertThat(AUTO_CONSTRUCT_MAP.hashCode()).isEqualTo(new HashMap<>().hashCode()); assertThat(AUTO_CONSTRUCT_MAP.hashCode()).isEqualTo(0); } |
DefaultSdkAutoConstructMap implements SdkAutoConstructMap<K, V> { @Override public String toString() { return impl.toString(); } private DefaultSdkAutoConstructMap(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructMap<K, V> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override V put(K key, V value); @Override V remove(Object key); @Override void putAll(Map<? extends K, ? extends V> m); @Override void clear(); @Override Set<K> keySet(); @Override Collection<V> values(); @Override Set<Entry<K, V>> entrySet(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void toString_emptyMap() { assertThat(AUTO_CONSTRUCT_MAP.toString()).isEqualTo("{}"); } |
PaginatorUtils { public static <T> boolean isOutputTokenAvailable(T outputToken) { if (outputToken == null) { return false; } if (outputToken instanceof String) { return !((String) outputToken).isEmpty(); } if (outputToken instanceof Map) { return !((Map) outputToken).isEmpty(); } if (outputToken instanceof Collection) { return !((Collection) outputToken).isEmpty(); } return true; } private PaginatorUtils(); static boolean isOutputTokenAvailable(T outputToken); } | @Test public void nullOutputToken_shouldReturnFalse() { assertFalse(PaginatorUtils.isOutputTokenAvailable(null)); }
@Test public void nonNullString_shouldReturnTrue() { assertTrue(PaginatorUtils.isOutputTokenAvailable("next")); }
@Test public void nonNullInteger_shouldReturnTrue() { assertTrue(PaginatorUtils.isOutputTokenAvailable(12)); }
@Test public void emptyCollection_shouldReturnFalse() { assertFalse(PaginatorUtils.isOutputTokenAvailable(new ArrayList<>())); }
@Test public void nonEmptyCollection_shouldReturnTrue() { assertTrue(PaginatorUtils.isOutputTokenAvailable(Arrays.asList("foo", "bar"))); }
@Test public void emptyMap_shouldReturnFalse() { assertFalse(PaginatorUtils.isOutputTokenAvailable(new HashMap<>())); }
@Test public void nonEmptyMap_shouldReturnTrue() { HashMap<String, String> outputTokens = new HashMap<>(); outputTokens.put("foo", "bar"); assertTrue(PaginatorUtils.isOutputTokenAvailable(outputTokens)); }
@Test public void sdkAutoConstructList_shouldReturnFalse() { assertFalse(PaginatorUtils.isOutputTokenAvailable(DefaultSdkAutoConstructList.getInstance())); }
@Test public void sdkAutoConstructMap_shouldReturnFalse() { assertFalse(PaginatorUtils.isOutputTokenAvailable(DefaultSdkAutoConstructMap.getInstance())); } |
RequestOverrideConfiguration { public Map<String, List<String>> headers() { return headers; } protected RequestOverrideConfiguration(Builder<?> builder); Map<String, List<String>> headers(); Map<String, List<String>> rawQueryParameters(); List<ApiName> apiNames(); Optional<Duration> apiCallTimeout(); Optional<Duration> apiCallAttemptTimeout(); Optional<Signer> signer(); List<MetricPublisher> metricPublishers(); @Override boolean equals(Object o); @Override int hashCode(); abstract Builder<? extends Builder> toBuilder(); } | @Test public void addSameItemAfterSetCollection_shouldOverride() { ImmutableMap<String, List<String>> map = ImmutableMap.of(HEADER, Arrays.asList("hello", "world")); RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .headers(map) .putHeader(HEADER, "blah") .build(); assertThat(configuration.headers().get(HEADER)).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); SdkRequestOverrideConfiguration.Builder configurationBuilder = SdkRequestOverrideConfiguration.builder().headers(headers); headerValues.add("test"); headers.put("new header", Collections.singletonList("new value")); assertThat(configurationBuilder.headers().size()).isEqualTo(1); assertThat(configurationBuilder.headers().get("foo")).containsExactly("bar"); } |
RequestOverrideConfiguration { public List<MetricPublisher> metricPublishers() { return metricPublishers; } protected RequestOverrideConfiguration(Builder<?> builder); Map<String, List<String>> headers(); Map<String, List<String>> rawQueryParameters(); List<ApiName> apiNames(); Optional<Duration> apiCallTimeout(); Optional<Duration> apiCallAttemptTimeout(); Optional<Signer> signer(); List<MetricPublisher> metricPublishers(); @Override boolean equals(Object o); @Override int hashCode(); abstract Builder<? extends Builder> toBuilder(); } | @Test public void metricPublishers_createsCopy() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); List<MetricPublisher> toModify = new ArrayList<>(publishers); SdkRequestOverrideConfiguration overrideConfig = SdkRequestOverrideConfiguration.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)); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); publishers.forEach(builder::addMetricPublisher); SdkRequestOverrideConfiguration 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)); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.addMetricPublisher(firstAdded); builder.metricPublishers(publishers); SdkRequestOverrideConfiguration 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); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.metricPublishers(publishers); builder.addMetricPublisher(thirdAdded); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).containsExactly(publishers.get(0), publishers.get(1), thirdAdded); } |
AsyncStreamingRequestMarshaller extends AbstractStreamingRequestMarshaller<T> { @Override public SdkHttpFullRequest marshall(T in) { SdkHttpFullRequest.Builder marshalled = delegateMarshaller.marshall(in).toBuilder(); addHeaders(marshalled, asyncRequestBody.contentLength(), requiresLength, transferEncoding, useHttp2); return marshalled.build(); } private AsyncStreamingRequestMarshaller(Builder builder); static Builder builder(); @Override SdkHttpFullRequest marshall(T in); } | @Test public void contentLengthIsPresent_shouldNotOverride() { long contentLengthOnRequest = 1L; long contengLengthOnRequestBody = 5L; when(requestBody.contentLength()).thenReturn(Optional.of(contengLengthOnRequestBody)); AsyncStreamingRequestMarshaller marshaller = createMarshaller(true, true, true); SdkHttpFullRequest requestWithContentLengthHeader = generateBasicRequest().toBuilder() .appendHeader(Header.CONTENT_LENGTH, String.valueOf(contentLengthOnRequest)) .build(); when(delegate.marshall(any())).thenReturn(requestWithContentLengthHeader); SdkHttpFullRequest httpFullRequest = marshaller.marshall(object); assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH)).isPresent(); assertContentLengthValue(httpFullRequest, contentLengthOnRequest); }
@Test public void contentLengthOnRequestBody_shouldAddContentLengthHeader() { long value = 5L; when(requestBody.contentLength()).thenReturn(Optional.of(value)); AsyncStreamingRequestMarshaller marshaller = createMarshaller(true, true, true); SdkHttpFullRequest httpFullRequest = marshaller.marshall(object); assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH)).isPresent(); assertContentLengthValue(httpFullRequest, value); assertThat(httpFullRequest.firstMatchingHeader(Header.TRANSFER_ENCODING)).isEmpty(); }
@Test public void throwsException_contentLengthHeaderIsMissing_AndRequiresLengthIsPresent() { when(requestBody.contentLength()).thenReturn(Optional.empty()); AsyncStreamingRequestMarshaller marshaller = createMarshaller(true, false, false); assertThatThrownBy(() -> marshaller.marshall(object)).isInstanceOf(SdkClientException.class); }
@Test public void transferEncodingIsUsed_OverHttp1() { when(requestBody.contentLength()).thenReturn(Optional.empty()); AsyncStreamingRequestMarshaller marshaller = createMarshaller(false, true, false); SdkHttpFullRequest httpFullRequest = marshaller.marshall(object); assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH)).isEmpty(); assertThat(httpFullRequest.firstMatchingHeader(Header.TRANSFER_ENCODING)).isPresent(); }
@Test public void transferEncodingIsNotUsed_OverHttp2() { when(requestBody.contentLength()).thenReturn(Optional.empty()); AsyncStreamingRequestMarshaller marshaller = createMarshaller(false, true, true); SdkHttpFullRequest httpFullRequest = marshaller.marshall(object); assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH)).isEmpty(); assertThat(httpFullRequest.firstMatchingHeader(Header.TRANSFER_ENCODING)).isEmpty(); } |
RetryPolicyContext implements ToCopyableBuilder<RetryPolicyContext.Builder, RetryPolicyContext> { public int totalRequests() { return this.retriesAttempted + 1; } private RetryPolicyContext(Builder builder); static Builder builder(); SdkRequest originalRequest(); SdkHttpFullRequest request(); SdkException exception(); ExecutionAttributes executionAttributes(); int retriesAttempted(); int totalRequests(); Integer httpStatusCode(); @Override Builder toBuilder(); } | @Test public void totalRequests_IsOneMoreThanRetriesAttempted() { assertEquals(4, RetryPolicyContexts.withRetriesAttempted(3).totalRequests()); } |
RetryPolicyContext implements ToCopyableBuilder<RetryPolicyContext.Builder, RetryPolicyContext> { public Integer httpStatusCode() { return this.httpStatusCode; } private RetryPolicyContext(Builder builder); static Builder builder(); SdkRequest originalRequest(); SdkHttpFullRequest request(); SdkException exception(); ExecutionAttributes executionAttributes(); int retriesAttempted(); int totalRequests(); Integer httpStatusCode(); @Override Builder toBuilder(); } | @Test public void nullHttpStatusCodeAllowed() { assertNull(RetryPolicyContexts.withStatusCode(null).httpStatusCode()); } |
RetryPolicyContext implements ToCopyableBuilder<RetryPolicyContext.Builder, RetryPolicyContext> { public SdkException exception() { return this.exception; } private RetryPolicyContext(Builder builder); static Builder builder(); SdkRequest originalRequest(); SdkHttpFullRequest request(); SdkException exception(); ExecutionAttributes executionAttributes(); int retriesAttempted(); int totalRequests(); Integer httpStatusCode(); @Override Builder toBuilder(); } | @Test public void nullExceptionAllowed() { assertNull(RetryPolicyContexts.withException(null).exception()); } |
DefaultWaiterResponse implements WaiterResponse<T> { public static <T> Builder<T> builder() { return new Builder<>(); } private DefaultWaiterResponse(Builder<T> builder); static Builder<T> builder(); @Override ResponseOrException<T> matched(); @Override int attemptsExecuted(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void missingAttemptsExecuted_shouldThrowException() { assertThatThrownBy(() -> DefaultWaiterResponse.<String>builder().response("foobar") .build()).hasMessageContaining("attemptsExecuted"); } |
S3ArnUtils { public static S3AccessPointResource parseS3AccessPointArn(Arn arn) { return S3AccessPointResource.builder() .partition(arn.partition()) .region(arn.region().orElse(null)) .accountId(arn.accountId().orElse(null)) .accessPointName(arn.resource().resource()) .build(); } private S3ArnUtils(); static S3AccessPointResource parseS3AccessPointArn(Arn arn); static IntermediateOutpostResource parseOutpostArn(Arn arn); } | @Test public void parseS3AccessPointArn_shouldParseCorrectly() { S3AccessPointResource s3AccessPointResource = S3ArnUtils.parseS3AccessPointArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("accesspoint:accesspoint-name") .build()); assertThat(s3AccessPointResource.accessPointName(), is("accesspoint-name")); assertThat(s3AccessPointResource.accountId(), is(Optional.of("123456789012"))); assertThat(s3AccessPointResource.partition(), is(Optional.of("aws"))); assertThat(s3AccessPointResource.region(), is(Optional.of("us-east-1"))); assertThat(s3AccessPointResource.type(), is(S3ResourceType.ACCESS_POINT.toString())); } |
MakeHttpRequestStage implements RequestPipeline<SdkHttpFullRequest, Pair<SdkHttpFullRequest, SdkHttpFullResponse>> { public Pair<SdkHttpFullRequest, SdkHttpFullResponse> execute(SdkHttpFullRequest request, RequestExecutionContext context) throws Exception { InterruptMonitor.checkInterrupted(); HttpExecuteResponse executeResponse = executeHttpRequest(request, context); SdkHttpFullResponse httpResponse = (SdkHttpFullResponse) executeResponse.httpResponse(); return Pair.of(request, httpResponse.toBuilder().content(executeResponse.responseBody().orElse(null)).build()); } MakeHttpRequestStage(HttpClientDependencies dependencies); Pair<SdkHttpFullRequest, SdkHttpFullResponse> execute(SdkHttpFullRequest request,
RequestExecutionContext context); } | @Test public void testExecute_contextContainsMetricCollector_addsChildToExecuteRequest() { SdkHttpFullRequest sdkRequest = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .host("mybucket.s3.us-west-2.amazonaws.com") .protocol("https") .build(); MetricCollector mockCollector = mock(MetricCollector.class); MetricCollector childCollector = mock(MetricCollector.class); when(mockCollector.createChild(any(String.class))).thenReturn(childCollector); ExecutionContext executionContext = ExecutionContext.builder() .executionAttributes(new ExecutionAttributes()) .build(); RequestExecutionContext context = RequestExecutionContext.builder() .originalRequest(ValidSdkObjects.sdkRequest()) .executionContext(executionContext) .build(); context.attemptMetricCollector(mockCollector); context.apiCallAttemptTimeoutTracker(mock(TimeoutTracker.class)); context.apiCallTimeoutTracker(mock(TimeoutTracker.class)); try { stage.execute(sdkRequest, context); } catch (Exception e) { } finally { ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); verify(mockCollector).createChild(eq("HttpClient")); verify(mockClient).prepareRequest(httpRequestCaptor.capture()); assertThat(httpRequestCaptor.getValue().metricCollector()).contains(childCollector); } } |
MakeAsyncHttpRequestStage implements RequestPipeline<CompletableFuture<SdkHttpFullRequest>, CompletableFuture<Response<OutputT>>> { @Override public CompletableFuture<Response<OutputT>> execute(CompletableFuture<SdkHttpFullRequest> requestFuture, RequestExecutionContext context) { CompletableFuture<Response<OutputT>> toReturn = new CompletableFuture<>(); CompletableFutureUtils.forwardExceptionTo(requestFuture, toReturn); CompletableFutureUtils.forwardExceptionTo(toReturn, requestFuture); requestFuture.thenAccept(request -> { try { CompletableFuture<Response<OutputT>> executeFuture = executeHttpRequest(request, context); executeFuture.whenComplete((r, t) -> { if (t != null) { toReturn.completeExceptionally(t); } else { toReturn.complete(r); } }); CompletableFutureUtils.forwardExceptionTo(toReturn, executeFuture); } catch (Throwable t) { toReturn.completeExceptionally(t); } }); return toReturn; } MakeAsyncHttpRequestStage(TransformingAsyncResponseHandler<Response<OutputT>> responseHandler,
HttpClientDependencies dependencies); @Override CompletableFuture<Response<OutputT>> execute(CompletableFuture<SdkHttpFullRequest> requestFuture,
RequestExecutionContext context); } | @Test public void apiCallAttemptTimeoutEnabled_shouldInvokeExecutor() throws Exception { stage = new MakeAsyncHttpRequestStage<>( combinedAsyncResponseHandler(AsyncResponseHandlerTestUtils.noOpResponseHandler(), AsyncResponseHandlerTestUtils.noOpResponseHandler()), clientDependencies(Duration.ofMillis(1000))); CompletableFuture<SdkHttpFullRequest> requestFuture = CompletableFuture.completedFuture( ValidSdkObjects.sdkHttpFullRequest().build()); stage.execute(requestFuture, requestContext()); verify(timeoutExecutor, times(1)).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); }
@Test public void apiCallAttemptTimeoutNotEnabled_shouldNotInvokeExecutor() throws Exception { stage = new MakeAsyncHttpRequestStage<>( combinedAsyncResponseHandler(AsyncResponseHandlerTestUtils.noOpResponseHandler(), AsyncResponseHandlerTestUtils.noOpResponseHandler()), clientDependencies(null)); CompletableFuture<SdkHttpFullRequest> requestFuture = CompletableFuture.completedFuture( ValidSdkObjects.sdkHttpFullRequest().build()); stage.execute(requestFuture, requestContext()); verify(timeoutExecutor, never()).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); }
@Test public void testExecute_contextContainsMetricCollector_addsChildToExecuteRequest() { stage = new MakeAsyncHttpRequestStage<>( combinedAsyncResponseHandler(AsyncResponseHandlerTestUtils.noOpResponseHandler(), AsyncResponseHandlerTestUtils.noOpResponseHandler()), clientDependencies(null)); SdkHttpFullRequest sdkHttpRequest = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .host("mybucket.s3.us-west-2.amazonaws.com") .protocol("https") .build(); MetricCollector mockCollector = mock(MetricCollector.class); MetricCollector childCollector = mock(MetricCollector.class); when(mockCollector.createChild(any(String.class))).thenReturn(childCollector); ExecutionContext executionContext = ExecutionContext.builder() .executionAttributes(new ExecutionAttributes()) .build(); RequestExecutionContext context = RequestExecutionContext.builder() .originalRequest(ValidSdkObjects.sdkRequest()) .executionContext(executionContext) .build(); context.attemptMetricCollector(mockCollector); CompletableFuture<SdkHttpFullRequest> requestFuture = CompletableFuture.completedFuture(sdkHttpRequest); try { stage.execute(requestFuture, context); } catch (Exception e) { e.printStackTrace(); } finally { ArgumentCaptor<AsyncExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); verify(mockCollector).createChild(eq("HttpClient")); verify(sdkAsyncHttpClient).execute(httpRequestCaptor.capture()); assertThat(httpRequestCaptor.getValue().metricCollector()).contains(childCollector); } } |
TimeoutExceptionHandlingStage implements RequestToResponsePipeline<OutputT> { @Override public Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context) throws Exception { try { return requestPipeline.execute(request, context); } catch (Exception e) { throw translatePipelineException(context, e); } } TimeoutExceptionHandlingStage(HttpClientDependencies dependencies, RequestPipeline<SdkHttpFullRequest,
Response<OutputT>> requestPipeline); @Override Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context); } | @Test public void IOException_causedByApiCallTimeout_shouldThrowInterruptedException() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new SocketException()); verifyExceptionThrown(InterruptedException.class); }
@Test public void IOException_causedByApiCallAttemptTimeout_shouldThrowApiCallAttemptTimeoutException() throws Exception { when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new IOException()); verifyExceptionThrown(ApiCallAttemptTimeoutException.class); }
@Test public void IOException_bothTimeouts_shouldThrowInterruptedException() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new IOException()); verifyExceptionThrown(InterruptedException.class); }
@Test public void IOException_notCausedByTimeouts_shouldPropagate() throws Exception { when(requestPipeline.execute(any(), any())).thenThrow(new SocketException()); verifyExceptionThrown(SocketException.class); }
@Test public void AbortedException_notCausedByTimeouts_shouldPropagate() throws Exception { when(requestPipeline.execute(any(), any())).thenThrow(AbortedException.create("")); verifyExceptionThrown(AbortedException.class); }
@Test public void AbortedException_causedByAttemptTimeout_shouldThrowApiCallAttemptTimeoutException() throws Exception { when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(AbortedException.create("")); verifyExceptionThrown(ApiCallAttemptTimeoutException.class); }
@Test public void AbortedException_causedByCallTimeout_shouldThrowInterruptedException() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(AbortedException.create("")); verifyExceptionThrown(InterruptedException.class); }
@Test public void nonTimeoutCausedException_shouldPropagate() throws Exception { when(requestPipeline.execute(any(), any())).thenThrow(new RuntimeException()); verifyExceptionThrown(RuntimeException.class); }
@Test public void interruptedException_notCausedByTimeouts_shouldPreserveInterruptFlag() throws Exception { when(requestPipeline.execute(any(), any())).thenThrow(new InterruptedException()); verifyExceptionThrown(AbortedException.class); verifyInterruptStatusPreserved(); }
@Test public void interruptedException_causedByApiCallTimeout_shouldPropagate() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new InterruptedException()); verifyExceptionThrown(InterruptedException.class); }
@Test public void interruptedException_causedByAttemptTimeout_shouldThrowApiAttempt() throws Exception { when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new InterruptedException()); verifyExceptionThrown(ApiCallAttemptTimeoutException.class); verifyInterruptStatusClear(); }
@Test public void interruptFlagWasSet_causedByAttemptTimeout_shouldThrowApiAttempt() throws Exception { Thread.currentThread().interrupt(); when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new RuntimeException()); verifyExceptionThrown(ApiCallAttemptTimeoutException.class); verifyInterruptStatusClear(); }
@Test public void interruptFlagWasSet_causedByApiCallTimeout_shouldThrowInterruptException() throws Exception { Thread.currentThread().interrupt(); when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new RuntimeException()); verifyExceptionThrown(InterruptedException.class); verifyInterruptStatusPreserved(); } |
S3ArnUtils { public static IntermediateOutpostResource parseOutpostArn(Arn arn) { String resource = arn.resourceAsString(); Integer outpostIdEndIndex = null; for (int i = OUTPOST_ID_START_INDEX; i < resource.length(); ++i) { char ch = resource.charAt(i); if (ch == ':' || ch == '/') { outpostIdEndIndex = i; break; } } if (outpostIdEndIndex == null) { throw new IllegalArgumentException("Invalid format for S3 outpost ARN, missing outpostId"); } String outpostId = resource.substring(OUTPOST_ID_START_INDEX, outpostIdEndIndex); if (StringUtils.isEmpty(outpostId)) { throw new IllegalArgumentException("Invalid format for S3 outpost ARN, missing outpostId"); } String subresource = resource.substring(outpostIdEndIndex + 1); if (StringUtils.isEmpty(subresource)) { throw new IllegalArgumentException("Invalid format for S3 outpost ARN"); } return IntermediateOutpostResource.builder() .outpostId(outpostId) .outpostSubresource(ArnResource.fromString(subresource)) .build(); } private S3ArnUtils(); static S3AccessPointResource parseS3AccessPointArn(Arn arn); static IntermediateOutpostResource parseOutpostArn(Arn arn); } | @Test public void parseOutpostArn_arnWithColon_shouldParseCorrectly() { IntermediateOutpostResource intermediateOutpostResource = S3ArnUtils.parseOutpostArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost:22222:accesspoint:foobar") .build()); assertThat(intermediateOutpostResource.outpostId(), is("22222")); assertThat(intermediateOutpostResource.outpostSubresource(), equalTo(ArnResource.fromString("accesspoint:foobar"))); }
@Test public void parseOutpostArn_arnWithSlash_shouldParseCorrectly() { IntermediateOutpostResource intermediateOutpostResource = S3ArnUtils.parseOutpostArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost/22222/accesspoint/foobar") .build()); assertThat(intermediateOutpostResource.outpostId(), is("22222")); assertThat(intermediateOutpostResource.outpostSubresource(), equalTo(ArnResource.fromString("accesspoint/foobar"))); }
@Test public void parseOutpostArn_shouldParseCorrectly() { IntermediateOutpostResource intermediateOutpostResource = S3ArnUtils.parseOutpostArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost:22222:futuresegment:foobar") .build()); assertThat(intermediateOutpostResource.outpostId(), is("22222")); assertThat(intermediateOutpostResource.outpostSubresource(), equalTo(ArnResource.fromString("futuresegment/foobar"))); }
@Test public void parseOutpostArn_malformedArnNullSubresourceType_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Invalid format"); S3ArnUtils.parseOutpostArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost/22222/") .build()); }
@Test public void parseOutpostArn_malformedArnNullSubresource_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Invalid format for S3 Outpost ARN"); S3ArnUtils.parseOutpostArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost:op-01234567890123456:accesspoint") .build()); }
@Test public void parseOutpostArn_malformedArnEmptyOutpostId_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("resource must not be blank or empty"); S3ArnUtils.parseOutpostArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost::accesspoint:name") .build()); } |
ApiCallAttemptTimeoutTrackingStage implements RequestToResponsePipeline<OutputT> { @Override public Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context) throws Exception { try { long timeoutInMillis = resolveTimeoutInMillis(context.requestConfig()::apiCallAttemptTimeout, apiCallAttemptTimeout); TimeoutTracker timeoutTracker = timeSyncTaskIfNeeded(timeoutExecutor, timeoutInMillis, Thread.currentThread()); Response<OutputT> response; try { context.apiCallAttemptTimeoutTracker(timeoutTracker); response = wrapped.execute(request, context); } finally { timeoutTracker.cancel(); } if (timeoutTracker.hasExecuted()) { Thread.interrupted(); } return response; } catch (Exception e) { throw translatePipelineException(context, e); } } ApiCallAttemptTimeoutTrackingStage(HttpClientDependencies dependencies,
RequestPipeline<SdkHttpFullRequest,
Response<OutputT>> wrapped); @Override Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context); } | @Test public void timeoutEnabled_shouldHaveTracker() throws Exception { when(wrapped.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))) .thenAnswer(invocationOnMock -> null); when(timeoutExecutor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(scheduledFuture); RequestExecutionContext context = requestContext(500); stage.execute(mock(SdkHttpFullRequest.class), context); assertThat(scheduledFuture.isDone()).isFalse(); assertThat(context.apiCallAttemptTimeoutTracker()).isInstanceOf(ApiCallTimeoutTracker.class); }
@Test public void timeoutDisabled_shouldNotExecuteTimer() throws Exception { when(wrapped.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))) .thenAnswer(invocationOnMock -> null); RequestExecutionContext context = requestContext(0); stage.execute(mock(SdkHttpFullRequest.class), context); assertThat(context.apiCallAttemptTimeoutTracker()).isInstanceOf(NoOpTimeoutTracker.class); assertThat(context.apiCallAttemptTimeoutTracker().isEnabled()).isFalse(); assertThat(context.apiCallAttemptTimeoutTracker().hasExecuted()).isFalse(); } |
AsyncApiCallTimeoutTrackingStage implements RequestPipeline<SdkHttpFullRequest, CompletableFuture<OutputT>> { @Override public CompletableFuture<OutputT> execute(SdkHttpFullRequest input, RequestExecutionContext context) throws Exception { CompletableFuture<OutputT> future = new CompletableFuture<>(); long apiCallTimeoutInMillis = resolveTimeoutInMillis(() -> context.requestConfig().apiCallTimeout(), clientConfig.option(SdkClientOption.API_CALL_TIMEOUT)); Supplier<SdkClientException> exceptionSupplier = () -> ApiCallTimeoutException.create(apiCallTimeoutInMillis); TimeoutTracker timeoutTracker = timeAsyncTaskIfNeeded(future, scheduledExecutor, exceptionSupplier, apiCallTimeoutInMillis); context.apiCallTimeoutTracker(timeoutTracker); CompletableFuture<OutputT> executeFuture = requestPipeline.execute(input, context); executeFuture.whenComplete((r, t) -> { if (t != null) { future.completeExceptionally(t); } else { future.complete(r); } }); return CompletableFutureUtils.forwardExceptionTo(future, executeFuture); } AsyncApiCallTimeoutTrackingStage(HttpClientDependencies dependencies,
RequestPipeline<SdkHttpFullRequest, CompletableFuture<OutputT>> requestPipeline); @Override CompletableFuture<OutputT> execute(SdkHttpFullRequest input, RequestExecutionContext context); } | @Test @SuppressWarnings("unchecked") public void testSchedulesTheTimeoutUsingSuppliedExecutorService() throws Exception { AsyncApiCallTimeoutTrackingStage apiCallTimeoutTrackingStage = new AsyncApiCallTimeoutTrackingStage(dependencies, requestPipeline); apiCallTimeoutTrackingStage.execute(httpRequest, requestExecutionContext); verify(executorService) .schedule(any(Runnable.class), eq(TIMEOUT_MILLIS), eq(TimeUnit.MILLISECONDS)); } |
MergeCustomHeadersStage implements MutableRequestToRequestPipeline { @Override public SdkHttpFullRequest.Builder execute(SdkHttpFullRequest.Builder request, RequestExecutionContext context) throws Exception { return request.headers(mergeHeaders(request.headers(), config.option(SdkClientOption.ADDITIONAL_HTTP_HEADERS), adaptHeaders(context.requestConfig().headers()))); } MergeCustomHeadersStage(HttpClientDependencies dependencies); @Override SdkHttpFullRequest.Builder execute(SdkHttpFullRequest.Builder request, RequestExecutionContext context); } | @Test public void singleHeader_inMarshalledRequest_overriddenOnClient() throws Exception { SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder(); RequestExecutionContext ctx = requestContext(NoopTestRequest.builder().build()); requestBuilder.putHeader(singleHeaderName, "marshaller"); Map<String, List<String>> clientHeaders = new HashMap<>(); clientHeaders.put(singleHeaderName, Collections.singletonList("client")); HttpClientDependencies clientDeps = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, clientHeaders) .build()) .build(); MergeCustomHeadersStage stage = new MergeCustomHeadersStage(clientDeps); stage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(singleHeaderName)).containsExactly("client"); }
@Test public void singleHeader_inMarshalledRequest_overriddenOnRequest() throws Exception { SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder(); requestBuilder.putHeader(singleHeaderName, "marshaller"); RequestExecutionContext ctx = requestContext(NoopTestRequest.builder() .overrideConfiguration(SdkRequestOverrideConfiguration.builder() .putHeader(singleHeaderName, "request").build()) .build()); HttpClientDependencies clientDeps = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, Collections.emptyMap()) .build()) .build(); MergeCustomHeadersStage stage = new MergeCustomHeadersStage(clientDeps); stage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(singleHeaderName)).containsExactly("request"); }
@Test public void singleHeader_inClient_overriddenOnRequest() throws Exception { SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder(); RequestExecutionContext ctx = requestContext(NoopTestRequest.builder() .overrideConfiguration(SdkRequestOverrideConfiguration.builder() .putHeader(singleHeaderName, "request").build()) .build()); Map<String, List<String>> clientHeaders = new HashMap<>(); clientHeaders.put(singleHeaderName, Collections.singletonList("client")); HttpClientDependencies clientDeps = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, clientHeaders) .build()) .build(); MergeCustomHeadersStage stage = new MergeCustomHeadersStage(clientDeps); stage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(singleHeaderName)).containsExactly("request"); }
@Test public void singleHeader_inMarshalledRequest_inClient_inRequest() throws Exception { SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder(); requestBuilder.putHeader(singleHeaderName, "marshaller"); RequestExecutionContext ctx = requestContext(NoopTestRequest.builder() .overrideConfiguration(SdkRequestOverrideConfiguration.builder() .putHeader(singleHeaderName, "request").build()) .build()); Map<String, List<String>> clientHeaders = new HashMap<>(); clientHeaders.put(singleHeaderName, Collections.singletonList("client")); HttpClientDependencies clientDeps = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, clientHeaders) .build()) .build(); MergeCustomHeadersStage stage = new MergeCustomHeadersStage(clientDeps); stage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(singleHeaderName)).containsExactly("request"); }
@Test public void singleHeader_inRequestAsList_keepsMultipleValues() throws Exception { SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder(); requestBuilder.putHeader(singleHeaderName, "marshaller"); RequestExecutionContext ctx = requestContext(NoopTestRequest.builder() .overrideConfiguration(SdkRequestOverrideConfiguration.builder() .putHeader(singleHeaderName, Arrays.asList("request", "request2", "request3")) .build()) .build()); Map<String, List<String>> clientHeaders = new HashMap<>(); HttpClientDependencies clientDeps = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, clientHeaders) .build()) .build(); MergeCustomHeadersStage stage = new MergeCustomHeadersStage(clientDeps); stage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(singleHeaderName)).containsExactly("request", "request2", "request3"); } |
ApiCallTimeoutTrackingStage implements RequestToResponsePipeline<OutputT> { @Override public Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context) throws Exception { try { return executeWithTimer(request, context); } catch (Exception e) { throw translatePipelineException(context, e); } } ApiCallTimeoutTrackingStage(HttpClientDependencies dependencies,
RequestPipeline<SdkHttpFullRequest, Response<OutputT>> wrapped); @Override Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context); } | @Test public void timedOut_shouldThrowApiCallTimeoutException() throws Exception { when(wrapped.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))) .thenAnswer(invocationOnMock -> { Thread.sleep(600); return null; }); RequestExecutionContext context = requestContext(500); assertThatThrownBy(() -> stage.execute(mock(SdkHttpFullRequest.class), context)).isInstanceOf(ApiCallTimeoutException .class); assertThat(context.apiCallTimeoutTracker().hasExecuted()).isTrue(); }
@Test public void timeoutDisabled_shouldNotExecuteTimer() throws Exception { when(wrapped.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))) .thenAnswer(invocationOnMock -> null); RequestExecutionContext context = requestContext(0); stage.execute(mock(SdkHttpFullRequest.class), context); assertThat(context.apiCallTimeoutTracker().hasExecuted()).isFalse(); } |
SystemPropertyHttpServiceProvider implements SdkHttpServiceProvider<T> { @Override public Optional<T> loadService() { return implSetting .getStringValue() .map(this::createServiceFromProperty); } private SystemPropertyHttpServiceProvider(SystemSetting implSetting, Class<T> serviceClass); @Override Optional<T> loadService(); } | @Test public void systemPropertyNotSet_ReturnsEmptyOptional() { assertThat(provider.loadService()).isEmpty(); }
@Test(expected = SdkClientException.class) public void systemPropertySetToInvalidClassName_ThrowsException() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), "com.invalid.ClassName"); provider.loadService(); }
@Test(expected = SdkClientException.class) public void systemPropertySetToNonServiceClass_ThrowsException() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), getClass().getName()); provider.loadService(); }
@Test(expected = SdkClientException.class) public void systemPropertySetToServiceClassWithNoDefaultCtor_ThrowsException() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), HttpServiceWithNoDefaultCtor.class.getName()); provider.loadService(); }
@Test public void systemPropertySetToValidClass_ReturnsFulfulledOptional() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), MockHttpService.class.getName()); assertThat(provider.loadService()).isPresent(); } |
SdkHttpServiceProviderChain implements SdkHttpServiceProvider<T> { @Override public Optional<T> loadService() { return httpProviders.stream() .map(SdkHttpServiceProvider::loadService) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); } @SafeVarargs SdkHttpServiceProviderChain(SdkHttpServiceProvider<T>... httpProviders); @Override Optional<T> loadService(); } | @Test public void allProvidersReturnEmpty_ReturnsEmptyOptional() { SdkHttpServiceProvider<SdkHttpService> delegateOne = mock(SdkHttpServiceProvider.class); SdkHttpServiceProvider<SdkHttpService> delegateTwo = mock(SdkHttpServiceProvider.class); when(delegateOne.loadService()).thenReturn(Optional.empty()); when(delegateTwo.loadService()).thenReturn(Optional.empty()); final Optional<SdkHttpService> actual = new SdkHttpServiceProviderChain<>(delegateOne, delegateTwo).loadService(); assertThat(actual).isEmpty(); }
@Test public void firstProviderReturnsNonEmpty_DoesNotCallSecondProvider() { SdkHttpServiceProvider<SdkHttpService> delegateOne = mock(SdkHttpServiceProvider.class); SdkHttpServiceProvider<SdkHttpService> delegateTwo = mock(SdkHttpServiceProvider.class); when(delegateOne.loadService()).thenReturn(Optional.of(mock(SdkHttpService.class))); final Optional<SdkHttpService> actual = new SdkHttpServiceProviderChain<>(delegateOne, delegateTwo).loadService(); assertThat(actual).isPresent(); verify(delegateTwo, never()).loadService(); } |
CachingSdkHttpServiceProvider implements SdkHttpServiceProvider<T> { @Override public Optional<T> loadService() { if (factory == null) { synchronized (this) { if (factory == null) { this.factory = delegate.loadService(); } } } return factory; } CachingSdkHttpServiceProvider(SdkHttpServiceProvider<T> delegate); @Override Optional<T> loadService(); } | @Test public void delegateReturnsEmptyOptional_DelegateCalledOnce() { when(delegate.loadService()).thenReturn(Optional.empty()); provider.loadService(); provider.loadService(); verify(delegate, times(1)).loadService(); }
@Test public void delegateReturnsNonEmptyOptional_DelegateCalledOne() { when(delegate.loadService()).thenReturn(Optional.of(mock(SdkHttpService.class))); provider.loadService(); provider.loadService(); verify(delegate, times(1)).loadService(); } |
ClasspathSdkHttpServiceProvider implements SdkHttpServiceProvider<T> { @Override public Optional<T> loadService() { Iterator<T> httpServices = serviceLoader.loadServices(serviceClass); if (!httpServices.hasNext()) { return Optional.empty(); } T httpService = httpServices.next(); if (httpServices.hasNext()) { throw SdkClientException.builder().message( String.format( "Multiple HTTP implementations were found on the classpath. To avoid non-deterministic loading " + "implementations, please explicitly provide an HTTP client via the client builders, set the %s " + "system property with the FQCN of the HTTP service to use as the default, or remove all but one " + "HTTP implementation from the classpath", implSystemProperty.property())) .build(); } return Optional.of(httpService); } @SdkTestInternalApi ClasspathSdkHttpServiceProvider(SdkServiceLoader serviceLoader, SystemSetting implSystemProperty, Class<T> serviceClass); @Override Optional<T> loadService(); } | @Test public void noImplementationsFound_ReturnsEmptyOptional() { when(serviceLoader.loadServices(SdkHttpService.class)) .thenReturn(iteratorOf()); assertThat(provider.loadService()).isEmpty(); }
@Test public void oneImplementationsFound_ReturnsFulfilledOptional() { when(serviceLoader.loadServices(SdkHttpService.class)) .thenReturn(iteratorOf(mock(SdkHttpService.class))); assertThat(provider.loadService()).isPresent(); }
@Test(expected = SdkClientException.class) public void multipleImplementationsFound_ThrowsException() { when(serviceLoader.loadServices(SdkHttpService.class)) .thenReturn(iteratorOf(mock(SdkHttpService.class), mock(SdkHttpService.class))); provider.loadService(); } |
MetricUtils { public static <T> Pair<T, Duration> measureDuration(Supplier<T> c) { long start = System.nanoTime(); T result = c.get(); Duration d = Duration.ofNanos(System.nanoTime() - start); return Pair.of(result, d); } private MetricUtils(); static Pair<T, Duration> measureDuration(Supplier<T> c); static Pair<T, Duration> measureDurationUnsafe(Callable<T> c); static void collectHttpMetrics(MetricCollector metricCollector, SdkHttpFullResponse httpResponse); static MetricCollector createAttemptMetricsCollector(RequestExecutionContext context); static MetricCollector createHttpMetricsCollector(RequestExecutionContext context); } | @Test public void testMeasureDuration_returnsAccurateDurationInformation() { long testDurationNanos = Duration.ofMillis(1).toNanos(); Pair<Object, Duration> measuredExecute = MetricUtils.measureDuration(() -> { long start = System.nanoTime(); while (System.nanoTime() - start < testDurationNanos) { } return "foo"; }); assertThat(measuredExecute.right()).isGreaterThanOrEqualTo(Duration.ofNanos(testDurationNanos)); }
@Test public void testMeasureDuration_returnsCallableReturnValue() { String result = "foo"; Pair<String, Duration> measuredExecute = MetricUtils.measureDuration(() -> result); assertThat(measuredExecute.left()).isEqualTo(result); }
@Test public void testMeasureDuration_doesNotWrapException() { RuntimeException e = new RuntimeException("boom"); thrown.expect(RuntimeException.class); try { MetricUtils.measureDuration(() -> { throw e; }); } catch (RuntimeException caught) { assertThat(caught).isSameAs(e); throw caught; } } |
MetricUtils { public static <T> Pair<T, Duration> measureDurationUnsafe(Callable<T> c) throws Exception { long start = System.nanoTime(); T result = c.call(); Duration d = Duration.ofNanos(System.nanoTime() - start); return Pair.of(result, d); } private MetricUtils(); static Pair<T, Duration> measureDuration(Supplier<T> c); static Pair<T, Duration> measureDurationUnsafe(Callable<T> c); static void collectHttpMetrics(MetricCollector metricCollector, SdkHttpFullResponse httpResponse); static MetricCollector createAttemptMetricsCollector(RequestExecutionContext context); static MetricCollector createHttpMetricsCollector(RequestExecutionContext context); } | @Test public void testMeasureDurationUnsafe_doesNotWrapException() throws Exception { IOException ioe = new IOException("boom"); thrown.expect(IOException.class); try { MetricUtils.measureDurationUnsafe(() -> { throw ioe; }); } catch (IOException caught) { assertThat(caught).isSameAs(ioe); throw caught; } } |
MetricUtils { public static void collectHttpMetrics(MetricCollector metricCollector, SdkHttpFullResponse httpResponse) { if (metricCollector != null && httpResponse != null) { metricCollector.reportMetric(HttpMetric.HTTP_STATUS_CODE, httpResponse.statusCode()); SdkHttpUtils.allMatchingHeadersFromCollection(httpResponse.headers(), X_AMZN_REQUEST_ID_HEADERS) .forEach(v -> metricCollector.reportMetric(CoreMetric.AWS_REQUEST_ID, v)); httpResponse.firstMatchingHeader(X_AMZ_ID_2_HEADER) .ifPresent(v -> metricCollector.reportMetric(CoreMetric.AWS_EXTENDED_REQUEST_ID, v)); } } private MetricUtils(); static Pair<T, Duration> measureDuration(Supplier<T> c); static Pair<T, Duration> measureDurationUnsafe(Callable<T> c); static void collectHttpMetrics(MetricCollector metricCollector, SdkHttpFullResponse httpResponse); static MetricCollector createAttemptMetricsCollector(RequestExecutionContext context); static MetricCollector createHttpMetricsCollector(RequestExecutionContext context); } | @Test public void testCollectHttpMetrics_collectsAllExpectedMetrics() { MetricCollector mockCollector = mock(MetricCollector.class); int statusCode = 200; String requestId = "request-id"; String amznRequestId = "amzn-request-id"; String requestId2 = "request-id-2"; SdkHttpFullResponse response = SdkHttpFullResponse.builder() .statusCode(statusCode) .putHeader("x-amz-request-id", requestId) .putHeader(HttpResponseHandler.X_AMZN_REQUEST_ID_HEADER, amznRequestId) .putHeader(HttpResponseHandler.X_AMZ_ID_2_HEADER, requestId2) .build(); MetricUtils.collectHttpMetrics(mockCollector, response); verify(mockCollector).reportMetric(HttpMetric.HTTP_STATUS_CODE, statusCode); verify(mockCollector).reportMetric(CoreMetric.AWS_REQUEST_ID, requestId); verify(mockCollector).reportMetric(CoreMetric.AWS_REQUEST_ID, amznRequestId); verify(mockCollector).reportMetric(CoreMetric.AWS_EXTENDED_REQUEST_ID, requestId2); } |
Mimetype { public String getMimetype(Path path) { Validate.notNull(path, "path"); Path file = path.getFileName(); if (file != null) { return getMimetype(file.toString()); } return MIMETYPE_OCTET_STREAM; } private Mimetype(); static Mimetype getInstance(); String getMimetype(Path path); String getMimetype(File file); static final String MIMETYPE_XML; static final String MIMETYPE_HTML; static final String MIMETYPE_OCTET_STREAM; static final String MIMETYPE_GZIP; static final String MIMETYPE_TEXT_PLAIN; static final String MIMETYPE_EVENT_STREAM; } | @Test public void extensionsWithCaps() throws Exception { assertThat(mimetype.getMimetype("image.JPeG")).isEqualTo("image/jpeg"); }
@Test public void extensionsWithUvi() throws Exception { assertThat(mimetype.getMimetype("test.uvvi")).isEqualTo("image/vnd.dece.graphic"); }
@Test public void unknownExtensions_defaulttoBeStream() throws Exception { assertThat(mimetype.getMimetype("test.unknown")).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); }
@Test public void noExtensions_defaulttoBeStream() throws Exception { assertThat(mimetype.getMimetype("test")).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); }
@Test public void pathWithoutFileName_defaulttoBeStream() throws Exception { Path mockPath = mock(Path.class); when(mockPath.getFileName()).thenReturn(null); assertThat(mimetype.getMimetype(mockPath)).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } |
UserAgentUtils { static String userAgent() { String ua = UA_STRING; ua = ua .replace("{platform}", "java") .replace("{version}", VersionInfo.SDK_VERSION) .replace("{os.name}", sanitizeInput(JavaSystemSetting.OS_NAME.getStringValue().orElse(null))) .replace("{os.version}", sanitizeInput(JavaSystemSetting.OS_VERSION.getStringValue().orElse(null))) .replace("{java.vm.name}", sanitizeInput(JavaSystemSetting.JAVA_VM_NAME.getStringValue().orElse(null))) .replace("{java.vm.version}", sanitizeInput(JavaSystemSetting.JAVA_VM_VERSION.getStringValue().orElse(null))) .replace("{java.version}", sanitizeInput(JavaSystemSetting.JAVA_VERSION.getStringValue().orElse(null))) .replace("{java.vendor}", sanitizeInput(JavaSystemSetting.JAVA_VENDOR.getStringValue().orElse(null))) .replace("{additional.languages}", getAdditionalJvmLanguages()); Optional<String> language = JavaSystemSetting.USER_LANGUAGE.getStringValue(); Optional<String> region = JavaSystemSetting.USER_REGION.getStringValue(); String languageAndRegion = ""; if (language.isPresent() && region.isPresent()) { languageAndRegion = " (" + sanitizeInput(language.get()) + "_" + sanitizeInput(region.get()) + ")"; } ua = ua.replace("{language.and.region}", languageAndRegion); return ua; } private UserAgentUtils(); static String getUserAgent(); } | @Test public void userAgent() { String userAgent = UserAgentUtils.userAgent(); assertNotNull(userAgent); Arrays.stream(userAgent.split(" ")).forEach(str -> assertThat(isValidInput(str)).isTrue()); }
@Test public void userAgent_HasVendor() { System.setProperty(JavaSystemSetting.JAVA_VENDOR.property(), "finks"); String userAgent = UserAgentUtils.userAgent(); System.clearProperty(JavaSystemSetting.JAVA_VENDOR.property()); assertThat(userAgent).contains("vendor/finks"); }
@Test public void userAgent_HasUnknownVendor() { System.clearProperty(JavaSystemSetting.JAVA_VENDOR.property()); String userAgent = UserAgentUtils.userAgent(); assertThat(userAgent).contains("vendor/unknown"); } |
ByteArrayAsyncRequestBody implements AsyncRequestBody { @Override public void subscribe(Subscriber<? super ByteBuffer> s) { if (s == null) { throw new NullPointerException("Subscription MUST NOT be null."); } try { s.onSubscribe( new Subscription() { private boolean done = false; @Override public void request(long n) { if (done) { return; } if (n > 0) { done = true; s.onNext(ByteBuffer.wrap(bytes)); s.onComplete(); } else { s.onError(new IllegalArgumentException("§3.9: non-positive requests are not allowed!")); } } @Override public void cancel() { synchronized (this) { if (!done) { done = true; } } } } ); } catch (Throwable ex) { new IllegalStateException(s + " violated the Reactive Streams rule 2.13 " + "by throwing an exception from onSubscribe.", ex) .printStackTrace(); } } ByteArrayAsyncRequestBody(byte[] bytes); @Override Optional<Long> contentLength(); @Override void subscribe(Subscriber<? super ByteBuffer> s); } | @Test public void concurrentRequests_shouldCompleteNormally() { ByteArrayAsyncRequestBody byteArrayReq = new ByteArrayAsyncRequestBody("Hello World!".getBytes()); byteArrayReq.subscribe(subscriber); assertTrue(subscriber.onCompleteCalled.get()); } |
ClockSkewAdjuster { public Integer getAdjustmentInSeconds(SdkHttpResponse response) { Instant now = Instant.now(); Instant serverTime = ClockSkew.getServerTime(response).orElse(null); Duration skew = ClockSkew.getClockSkew(now, serverTime); try { return Math.toIntExact(skew.getSeconds()); } catch (ArithmeticException e) { log.warn(() -> "The clock skew between the client and server was too large to be compensated for (" + now + " versus " + serverTime + ")."); return 0; } } boolean shouldAdjust(SdkException exception); Integer getAdjustmentInSeconds(SdkHttpResponse response); } | @Test public void adjustmentTranslatesCorrectly() { assertThat(adjuster.getAdjustmentInSeconds(responseWithDateOffset(1, HOURS))).isCloseTo(-1 * 60 * 60, within(5)); assertThat(adjuster.getAdjustmentInSeconds(responseWithDateOffset(-14, MINUTES))).isCloseTo(14 * 60, within(5)); }
@Test public void farFutureDateTranslatesToZero() { assertThat(adjuster.getAdjustmentInSeconds(responseWithDate("Fri, 31 Dec 9999 23:59:59 GMT"))).isEqualTo(0); }
@Test public void badDateTranslatesToZero() { assertThat(adjuster.getAdjustmentInSeconds(responseWithDate("X"))).isEqualTo(0); } |
FileContentStreamProvider implements ContentStreamProvider { @Override public InputStream newStream() { closeCurrentStream(); currentStream = invokeSafely(() -> Files.newInputStream(filePath)); return currentStream; } FileContentStreamProvider(Path filePath); @Override InputStream newStream(); } | @Test public void newStreamClosesPreviousStream() { FileContentStreamProvider provider = new FileContentStreamProvider(testFile); InputStream oldStream = provider.newStream(); provider.newStream(); assertThatThrownBy(oldStream::read).hasMessage("stream is closed"); } |
AwsHostNameUtils { public static Optional<Region> parseSigningRegion(final String host, final String serviceHint) { if (host == null) { throw new IllegalArgumentException("hostname cannot be null"); } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN.matcher(host); if (matcher.matches()) { return Optional.of(Region.of(matcher.group(1))); } } Pattern pattern = Pattern.compile("^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\."); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return Optional.of(Region.of(matcher.group(1))); } } return Optional.empty(); } private AwsHostNameUtils(); static Optional<Region> parseSigningRegion(final String host, final String serviceHint); } | @Test public void testStandardNoHint() { assertThat(parseSigningRegion("iam.amazonaws.com", null)).hasValue(Region.US_EAST_1); assertThat(parseSigningRegion("iam.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("ec2.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("cloudsearch.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("domain.us-west-2.cloudsearch.amazonaws.com", null)).hasValue(Region.US_WEST_2); }
@Test public void testStandard() { assertThat(parseSigningRegion("iam.amazonaws.com", "iam")).hasValue(Region.US_EAST_1); assertThat(parseSigningRegion("iam.us-west-2.amazonaws.com", "iam")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("ec2.us-west-2.amazonaws.com", "ec2")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("cloudsearch.us-west-2.amazonaws.com", "cloudsearch")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("domain.us-west-2.cloudsearch.amazonaws.com", "cloudsearch")).hasValue(Region.US_WEST_2); }
@Test public void testBjs() { assertThat(parseSigningRegion("iam.cn-north-1.amazonaws.com.cn", "iam")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("ec2.cn-north-1.amazonaws.com.cn", "ec2")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("s3.cn-north-1.amazonaws.com.cn", "s3")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("bucket.name.with.periods.s3.cn-north-1.amazonaws.com.cn", "s3")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("cloudsearch.cn-north-1.amazonaws.com.cn", "cloudsearch")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("domain.cn-north-1.cloudsearch.amazonaws.com.cn", "cloudsearch")).hasValue(Region.CN_NORTH_1); }
@Test public void testParseRegionWithIpv4() { assertThat(parseSigningRegion("54.231.16.200", null)).isNotPresent(); } |
HelpfulUnknownHostExceptionInterceptor implements ExecutionInterceptor { @Override public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) { if (!hasCause(context.exception(), UnknownHostException.class)) { return context.exception(); } StringBuilder error = new StringBuilder(); error.append("Received an UnknownHostException when attempting to interact with a service. See cause for the " + "exact endpoint that is failing to resolve. "); Optional<String> globalRegionErrorDetails = getGlobalRegionErrorDetails(executionAttributes); if (globalRegionErrorDetails.isPresent()) { error.append(globalRegionErrorDetails.get()); } else { error.append("If this is happening on an endpoint that previously worked, there may be a network connectivity " + "issue or your DNS cache could be storing endpoints for too long."); } return SdkClientException.builder().message(error.toString()).cause(context.exception()).build(); } @Override Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes); } | @Test public void modifyException_skipsNonUnknownHostExceptions() { IOException exception = new IOException(); assertThat(modifyException(exception)).isEqualTo(exception); }
@Test public void modifyException_supportsNestedUnknownHostExceptions() { Exception exception = new UnknownHostException(); exception.initCause(new IOException()); exception = new IllegalArgumentException(exception); exception = new UnsupportedOperationException(exception); assertThat(modifyException(exception, Region.AWS_GLOBAL)).isInstanceOf(SdkClientException.class); }
@Test public void modifyException_returnsGenericHelp_forGlobalRegions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.AWS_GLOBAL)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("network"); }
@Test public void modifyException_returnsGenericHelp_forUnknownServices() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.US_EAST_1, "millems-hotdog-stand")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "global")) .hasMessageContaining("network"); }
@Test public void modifyException_returnsGenericHelp_forUnknownServicesInUnknownRegions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.of("cn-north-99"), "millems-hotdog-stand")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "global")) .hasMessageContaining("network"); }
@Test public void modifyException_returnsGenericHelp_forServicesRegionalizedInAllPartitions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.US_EAST_1, "dynamodb")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "global")) .hasMessageContaining("network"); }
@Test public void modifyException_returnsGenericGlobalRegionHelp_forServicesGlobalInSomePartitionOtherThanTheClientPartition() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.of("cn-north-99"), "iam")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "network")) .hasMessageContaining("aws-global") .hasMessageContaining("aws-cn-global"); }
@Test public void modifyException_returnsSpecificGlobalRegionHelp_forServicesGlobalInTheClientRegionPartition() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.of("cn-north-1"), "iam")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "aws-global")) .hasMessageContaining("aws-cn-global"); } |
S3AccessPointResource implements S3Resource, ToCopyableBuilder<S3AccessPointResource.Builder, S3AccessPointResource> { @Override public Builder toBuilder() { return builder() .partition(partition) .region(region) .accountId(accountId) .accessPointName(accessPointName); } private S3AccessPointResource(Builder b); static Builder builder(); @Override String type(); @Override Optional<S3Resource> parentS3Resource(); @Override Optional<String> partition(); @Override Optional<String> region(); @Override Optional<String> accountId(); String accessPointName(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | @Test public void toBuilder() { S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder() .accessPointName("access_point-name") .accountId("account-id") .partition("partition") .region("region") .build() .toBuilder() .build(); assertEquals("access_point-name", s3AccessPointResource.accessPointName()); assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId()); assertEquals(Optional.of("partition"), s3AccessPointResource.partition()); assertEquals(Optional.of("region"), s3AccessPointResource.region()); assertEquals("accesspoint", s3AccessPointResource.type()); } |
QueryParametersToBodyInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest httpRequest = context.httpRequest(); if (!(httpRequest instanceof SdkHttpFullRequest)) { return httpRequest; } SdkHttpFullRequest httpFullRequest = (SdkHttpFullRequest) httpRequest; if (shouldPutParamsInBody(httpFullRequest)) { return changeQueryParametersToFormData(httpFullRequest); } return httpFullRequest; } @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); } | @Test public void postRequestsWithNoBodyHaveTheirParametersMovedToTheBody() throws Exception { SdkHttpFullRequest request = requestBuilder.build(); SdkHttpFullRequest output = (SdkHttpFullRequest) interceptor.modifyHttpRequest( new HttpRequestOnlyContext(request, null), executionAttributes); assertThat(output.rawQueryParameters()).hasSize(0); assertThat(output.headers()) .containsKey("Content-Length") .containsEntry("Content-Type", singletonList("application/x-www-form-urlencoded; charset=utf-8")); assertThat(output.contentStreamProvider()).isNotEmpty(); }
@Test public void postWithContentIsUnaltered() throws Exception { byte[] contentBytes = "hello".getBytes(StandardCharsets.UTF_8); ContentStreamProvider contentProvider = () -> new ByteArrayInputStream(contentBytes); SdkHttpFullRequest request = requestBuilder.contentStreamProvider(contentProvider).build(); SdkHttpFullRequest output = (SdkHttpFullRequest) interceptor.modifyHttpRequest( new HttpRequestOnlyContext(request, null), executionAttributes); assertThat(output.rawQueryParameters()).hasSize(1); assertThat(output.headers()).hasSize(0); assertThat(IoUtils.toByteArray(output.contentStreamProvider().get().newStream())).isEqualTo(contentBytes); }
@Test public void onlyAlterRequestsIfParamsArePresent() throws Exception { SdkHttpFullRequest request = requestBuilder.clearQueryParameters().build(); SdkHttpFullRequest output = (SdkHttpFullRequest) interceptor.modifyHttpRequest( new HttpRequestOnlyContext(request, null), executionAttributes); assertThat(output.rawQueryParameters()).hasSize(0); assertThat(output.headers()).hasSize(0); assertThat(output.contentStreamProvider()).isEmpty(); } |
ProtocolUtils { public static SdkHttpFullRequest.Builder createSdkHttpRequest(OperationInfo operationInfo, URI endpoint) { SdkHttpFullRequest.Builder request = SdkHttpFullRequest .builder() .method(operationInfo.httpMethod()) .uri(endpoint); return request.encodedPath(SdkHttpUtils.appendUri(request.encodedPath(), addStaticQueryParametersToRequest(request, operationInfo.requestUri()))); } private ProtocolUtils(); static SdkHttpFullRequest.Builder createSdkHttpRequest(OperationInfo operationInfo, URI endpoint); } | @Test public void createSdkHttpRequest_SetsHttpMethodAndEndpointCorrectly() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .build(), URI.create("http: assertThat(sdkHttpRequest.protocol()).isEqualTo("http"); assertThat(sdkHttpRequest.host()).isEqualTo("localhost"); assertThat(sdkHttpRequest.port()).isEqualTo(8080); assertThat(sdkHttpRequest.method()).isEqualTo(SdkHttpMethod.DELETE); }
@Test public void createSdkHttpRequest_EndpointWithPathSetCorrectly() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar"); }
@Test public void createSdkHttpRequest_RequestUriAppendedToEndpointPath() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .requestUri("/baz") .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz"); }
@Test public void createSdkHttpRequest_NoTrailingSlashInEndpointPath_RequestUriAppendedToEndpointPath() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .requestUri("/baz") .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz"); }
@Test public void createSdkHttpRequest_NoLeadingSlashInRequestUri_RequestUriAppendedToEndpointPath() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .requestUri("baz") .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz"); }
@Test public void createSdkHttpRequest_NoTrailingOrLeadingSlash_RequestUriAppendedToEndpointPath() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .requestUri("baz") .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz"); } |
S3ArnConverter implements ArnConverter<S3Resource> { @Override public S3Resource convertArn(Arn arn) { if (isV1Arn(arn)) { return convertV1Arn(arn); } S3ResourceType s3ResourceType; String resourceType = arn.resource().resourceType().orElseThrow(() -> new IllegalArgumentException("Unknown ARN type")); try { s3ResourceType = S3ResourceType.fromValue(resourceType); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unknown ARN type '" + arn.resource().resourceType().get() + "'"); } switch (s3ResourceType) { case ACCESS_POINT: return parseS3AccessPointArn(arn); case BUCKET: return parseS3BucketArn(arn); case OUTPOST: return parseS3OutpostAccessPointArn(arn); default: throw new IllegalArgumentException("Unknown ARN type '" + s3ResourceType + "'"); } } private S3ArnConverter(); static S3ArnConverter create(); @Override S3Resource convertArn(Arn arn); } | @Test public void parseArn_objectThroughAp_v2Arn() { S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("accesspoint:test-ap/object/test-key") .build()); assertThat(resource, instanceOf(S3ObjectResource.class)); S3ObjectResource s3ObjectResource = (S3ObjectResource) resource; assertThat(s3ObjectResource.parentS3Resource().get(), instanceOf(S3AccessPointResource.class)); S3AccessPointResource s3AccessPointResource = (S3AccessPointResource)s3ObjectResource.parentS3Resource().get(); assertThat(s3AccessPointResource.accessPointName(), is("test-ap")); assertThat(s3ObjectResource.key(), is("test-key")); assertThat(s3ObjectResource.accountId(), is(Optional.of("123456789012"))); assertThat(s3ObjectResource.partition(), is(Optional.of("aws"))); assertThat(s3ObjectResource.region(), is(Optional.of("us-east-1"))); assertThat(s3ObjectResource.type(), is(S3ResourceType.OBJECT.toString())); }
@Test public void parseArn_object_v1Arn() { S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .resource("bucket/key") .build()); assertThat(resource, instanceOf(S3ObjectResource.class)); S3ObjectResource s3ObjectResource = (S3ObjectResource) resource; assertThat(s3ObjectResource.parentS3Resource().get(), instanceOf(S3BucketResource.class)); S3BucketResource s3BucketResource = (S3BucketResource) s3ObjectResource.parentS3Resource().get(); assertThat(s3BucketResource.bucketName(), is("bucket")); assertThat(s3ObjectResource.key(), is("key")); assertThat(s3ObjectResource.accountId(), is(Optional.empty())); assertThat(s3ObjectResource.partition(), is(Optional.of("aws"))); assertThat(s3ObjectResource.region(), is(Optional.empty())); assertThat(s3ObjectResource.type(), is(S3ResourceType.OBJECT.toString())); }
@Test public void parseArn_accessPoint() { S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("accesspoint:accesspoint-name") .build()); assertThat(resource, instanceOf(S3AccessPointResource.class)); S3AccessPointResource s3EndpointResource = (S3AccessPointResource) resource; assertThat(s3EndpointResource.accessPointName(), is("accesspoint-name")); assertThat(s3EndpointResource.accountId(), is(Optional.of("123456789012"))); assertThat(s3EndpointResource.partition(), is(Optional.of("aws"))); assertThat(s3EndpointResource.region(), is(Optional.of("us-east-1"))); assertThat(s3EndpointResource.type(), is(S3ResourceType.ACCESS_POINT.toString())); }
@Test public void parseArn_accessPoint_withQualifier() { S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("accesspoint:accesspoint-name:1214234234") .build()); assertThat(resource, instanceOf(S3AccessPointResource.class)); S3AccessPointResource s3EndpointResource = (S3AccessPointResource) resource; assertThat(s3EndpointResource.accessPointName(), is("accesspoint-name")); assertThat(s3EndpointResource.accountId(), is(Optional.of("123456789012"))); assertThat(s3EndpointResource.partition(), is(Optional.of("aws"))); assertThat(s3EndpointResource.region(), is(Optional.of("us-east-1"))); assertThat(s3EndpointResource.type(), is(S3ResourceType.ACCESS_POINT.toString())); }
@Test public void parseArn_v1Bucket() { S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .resource("bucket-name") .build()); assertThat(resource, instanceOf(S3BucketResource.class)); S3BucketResource s3BucketResource = (S3BucketResource) resource; assertThat(s3BucketResource.bucketName(), is("bucket-name")); assertThat(s3BucketResource.accountId(), is(Optional.empty())); assertThat(s3BucketResource.partition(), is(Optional.of("aws"))); assertThat(s3BucketResource.region(), is(Optional.empty())); assertThat(s3BucketResource.type(), is(S3ResourceType.BUCKET.toString())); }
@Test public void parseArn_v2Bucket() { S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("bucket_name:bucket-name") .build()); assertThat(resource, instanceOf(S3BucketResource.class)); S3BucketResource s3BucketResource = (S3BucketResource) resource; assertThat(s3BucketResource.bucketName(), is("bucket-name")); assertThat(s3BucketResource.accountId(), is(Optional.of("123456789012"))); assertThat(s3BucketResource.partition(), is(Optional.of("aws"))); assertThat(s3BucketResource.region(), is(Optional.of("us-east-1"))); assertThat(s3BucketResource.type(), is(S3ResourceType.BUCKET.toString())); }
@Test public void parseArn_unknownResource() { exception.expect(IllegalArgumentException.class); exception.expectMessage("ARN type"); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("unknown:foobar") .build()); }
@Test public void parseArn_bucket_noName() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("bucket_name:") .build()); }
@Test public void parseArn_accesspoint_noName() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("access_point:") .build()); }
@Test public void parseArn_object_v2Arn_noKey() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("object:bucket") .build()); }
@Test public void parseArn_object_v2Arn_emptyBucket() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("object:/key") .build()); }
@Test public void parseArn_object_v2Arn_emptyKey() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("object:bucket/") .build()); }
@Test public void parseArn_object_v1Arn_emptyKey() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .resource("bucket/") .build()); }
@Test public void parseArn_object_v1Arn_emptyBucket() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .resource("/key") .build()); }
@Test public void parseArn_unknownType_throwsCorrectException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("invalidType"); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("invalidType:something") .build()); }
@Test public void parseArn_outpostAccessPoint_slash() { S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId(ACCOUNT_ID) .resource("outpost/22222/accesspoint/foobar") .build()); assertThat(resource, instanceOf(S3AccessPointResource.class)); S3AccessPointResource s3AccessPointResource = (S3AccessPointResource) resource; assertThat(s3AccessPointResource.accessPointName(), is("foobar")); assertThat(s3AccessPointResource.parentS3Resource().get(), instanceOf(S3OutpostResource.class)); S3OutpostResource outpostResource = (S3OutpostResource)s3AccessPointResource.parentS3Resource().get(); assertThat(outpostResource.accountId(), is(Optional.of(ACCOUNT_ID))); assertThat(outpostResource.partition(), is(Optional.of("aws"))); assertThat(outpostResource.region(), is(Optional.of("us-east-1"))); assertThat(outpostResource.outpostId(), is("22222")); assertThat(outpostResource.type(), is(S3ResourceType.OUTPOST.toString())); }
@Test public void parseArn_outpostAccessPoint_colon() { S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId(ACCOUNT_ID) .resource("outpost:22222:accesspoint:foobar") .build()); assertThat(resource, instanceOf(S3AccessPointResource.class)); S3AccessPointResource s3AccessPointResource = (S3AccessPointResource) resource; assertThat(s3AccessPointResource.accessPointName(), is("foobar")); assertThat(s3AccessPointResource.parentS3Resource().get(), instanceOf(S3OutpostResource.class)); S3OutpostResource outpostResource = (S3OutpostResource)s3AccessPointResource.parentS3Resource().get(); assertThat(outpostResource.accountId(), is(Optional.of(ACCOUNT_ID))); assertThat(outpostResource.partition(), is(Optional.of("aws"))); assertThat(outpostResource.region(), is(Optional.of("us-east-1"))); assertThat(outpostResource.outpostId(), is("22222")); assertThat(outpostResource.type(), is(S3ResourceType.OUTPOST.toString())); }
@Test public void parseArn_invalidOutpostAccessPointMissingAccessPointName_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Invalid format"); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId(ACCOUNT_ID) .resource("outpost:op-01234567890123456:accesspoint") .build()); }
@Test public void parseArn_invalidOutpostAccessPointMissingOutpostId_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Invalid format"); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId(ACCOUNT_ID) .resource("outpost/myaccesspoint") .build()); }
@Test public void parseArn_malformedOutpostArn_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Unknown outpost ARN type"); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId(ACCOUNT_ID) .resource("outpost:1:accesspoin1:1") .build()); } |
ProtocolUtils { @SdkTestInternalApi static String addStaticQueryParametersToRequest(SdkHttpFullRequest.Builder request, String uriResourcePath) { if (request == null || uriResourcePath == null) { return null; } String resourcePath = uriResourcePath; int index = resourcePath.indexOf("?"); if (index != -1) { String queryString = resourcePath.substring(index + 1); resourcePath = resourcePath.substring(0, index); for (String s : queryString.split("[;&]")) { index = s.indexOf("="); if (index != -1) { request.putRawQueryParameter(s.substring(0, index), s.substring(index + 1)); } else { request.putRawQueryParameter(s, (String) null); } } } return resourcePath; } private ProtocolUtils(); static SdkHttpFullRequest.Builder createSdkHttpRequest(OperationInfo operationInfo, URI endpoint); } | @Test public void request_null_returns_null() { Assert.assertNull(ProtocolUtils.addStaticQueryParametersToRequest(null, "foo")); }
@Test public void uri_resource_path_null_returns_null() { Assert.assertNull(ProtocolUtils .addStaticQueryParametersToRequest(emptyRequest(), null)); }
@Test public void uri_resource_path_doesnot_have_static_query_params_returns_uri_resource_path() { final String uriResourcePath = "/foo/bar"; Assert.assertEquals(uriResourcePath, ProtocolUtils .addStaticQueryParametersToRequest(emptyRequest(), uriResourcePath)); }
@Test public void uri_resource_path_ends_with_question_mark_returns_path_removed_with_question_mark() { final String expectedResourcePath = "/foo/bar"; final String pathWithEmptyStaticQueryParams = expectedResourcePath + "?"; Assert.assertEquals(expectedResourcePath, ProtocolUtils .addStaticQueryParametersToRequest(emptyRequest(), pathWithEmptyStaticQueryParams)); }
@Test public void queryparam_value_empty_adds_parameter_with_empty_string_to_request() { final String uriResourcePath = "/foo/bar"; final String uriResourcePathWithParams = uriResourcePath + "?param1="; SdkHttpFullRequest.Builder request = emptyRequest(); Assert.assertEquals(uriResourcePath, ProtocolUtils .addStaticQueryParametersToRequest(request, uriResourcePathWithParams)); Assert.assertTrue(request.rawQueryParameters().containsKey("param1")); Assert.assertEquals(singletonList(""), request.rawQueryParameters().get("param1")); }
@Test public void static_queryparams_in_path_added_to_request() { final String uriResourcePath = "/foo/bar"; final String uriResourcePathWithParams = uriResourcePath + "?param1=value1¶m2=value2"; SdkHttpFullRequest.Builder request = emptyRequest(); Assert.assertEquals(uriResourcePath, ProtocolUtils .addStaticQueryParametersToRequest(request, uriResourcePathWithParams)); Assert.assertTrue(request.rawQueryParameters().containsKey("param1")); Assert.assertTrue(request.rawQueryParameters().containsKey("param2")); Assert.assertEquals(singletonList("value1"), request.rawQueryParameters().get("param1")); Assert.assertEquals(singletonList("value2"), request.rawQueryParameters().get("param2")); }
@Test public void queryparam_without_value_returns_list_containing_null_value() { final String uriResourcePath = "/foo/bar"; final String uriResourcePathWithParams = uriResourcePath + "?param"; SdkHttpFullRequest.Builder request = emptyRequest(); Assert.assertEquals(uriResourcePath, ProtocolUtils.addStaticQueryParametersToRequest(request, uriResourcePathWithParams)); Assert.assertTrue(request.rawQueryParameters().containsKey("param")); Assert.assertEquals(singletonList((String) null), request.rawQueryParameters().get("param")); } |
AwsCborProtocolFactory extends BaseAwsJsonProtocolFactory { @Override protected Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() { if (!isCborEnabled()) { return super.getDefaultTimestampFormats(); } Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class); formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822); formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.UNIX_TIMESTAMP_MILLIS); return Collections.unmodifiableMap(formats); } private AwsCborProtocolFactory(Builder builder); static Builder builder(); } | @Test public void defaultTimestampFormats_cborEnabled() { Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats = factory.getDefaultTimestampFormats(); assertThat(defaultTimestampFormats.get(MarshallLocation.HEADER)).isEqualTo(RFC_822); assertThat(defaultTimestampFormats.get(MarshallLocation.PAYLOAD)).isEqualTo(UNIX_TIMESTAMP_MILLIS); }
@Test public void defaultTimestampFormats_cborDisabled() { System.setProperty(CBOR_ENABLED.property(), "false"); try { Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats = factory.getDefaultTimestampFormats(); assertThat(defaultTimestampFormats.get(MarshallLocation.HEADER)).isEqualTo(RFC_822); assertThat(defaultTimestampFormats.get(MarshallLocation.PAYLOAD)).isEqualTo(UNIX_TIMESTAMP); } finally { System.clearProperty(CBOR_ENABLED.property()); } } |
AwsXmlUnmarshallingContext { public Builder toBuilder() { return builder().sdkHttpFullResponse(this.sdkHttpFullResponse) .parsedXml(this.parsedXml) .executionAttributes(this.executionAttributes) .isResponseSuccess(this.isResponseSuccess) .parsedErrorXml(this.parsedErrorXml); } private AwsXmlUnmarshallingContext(Builder builder); static Builder builder(); SdkHttpFullResponse sdkHttpFullResponse(); XmlElement parsedRootXml(); ExecutionAttributes executionAttributes(); Boolean isResponseSuccess(); XmlElement parsedErrorXml(); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void toBuilder_maximal() { assertThat(maximal().toBuilder().build()).isEqualTo(maximal()); }
@Test public void toBuilder_minimal() { assertThat(minimal().toBuilder().build()).isEqualTo(minimal()); } |
AwsXmlUnmarshallingContext { @Override public int hashCode() { int result = sdkHttpFullResponse != null ? sdkHttpFullResponse.hashCode() : 0; result = 31 * result + (parsedXml != null ? parsedXml.hashCode() : 0); result = 31 * result + (executionAttributes != null ? executionAttributes.hashCode() : 0); result = 31 * result + (isResponseSuccess != null ? isResponseSuccess.hashCode() : 0); result = 31 * result + (parsedErrorXml != null ? parsedErrorXml.hashCode() : 0); return result; } private AwsXmlUnmarshallingContext(Builder builder); static Builder builder(); SdkHttpFullResponse sdkHttpFullResponse(); XmlElement parsedRootXml(); ExecutionAttributes executionAttributes(); Boolean isResponseSuccess(); XmlElement parsedErrorXml(); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void hashcode_maximal_positive() { assertThat(maximal().hashCode()).isEqualTo(maximal().hashCode()); }
@Test public void hashcode_minimal_positive() { assertThat(minimal().hashCode()).isEqualTo(minimal().hashCode()); } |
JsonDomParser { public SdkJsonNode parse(InputStream content) throws IOException { try (JsonParser parser = jsonFactory.createParser(content) .configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false)) { return parseToken(parser, parser.nextToken()); } } private JsonDomParser(JsonFactory jsonFactory); SdkJsonNode parse(InputStream content); static JsonDomParser create(JsonFactory jsonFactory); } | @Test public void simpleString_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("\"foo\""); assertThat(node) .isInstanceOf(SdkScalarNode.class) .matches(s -> ((SdkScalarNode) s).value().equals("foo")); }
@Test public void simpleNumber_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("42"); assertThat(node) .isInstanceOf(SdkScalarNode.class) .matches(s -> ((SdkScalarNode) s).value().equals("42")); }
@Test public void decimalNumber_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("1234.56"); assertThat(node) .isInstanceOf(SdkScalarNode.class) .matches(s -> ((SdkScalarNode) s).value().equals("1234.56")); }
@Test public void falseBoolean_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("false"); assertThat(node) .isInstanceOf(SdkScalarNode.class) .matches(s -> ((SdkScalarNode) s).value().equals("false")); }
@Test public void trueBoolean_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("true"); assertThat(node) .isInstanceOf(SdkScalarNode.class) .matches(s -> ((SdkScalarNode) s).value().equals("true")); }
@Test public void jsonNull_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("null"); assertThat(node).isInstanceOf(SdkNullNode.class); }
@Test public void emptyObject_ParsedCorrecty() throws IOException { SdkJsonNode node = parse("{}"); SdkObjectNode expected = SdkObjectNode.builder().build(); assertThat(node).isInstanceOf(SdkObjectNode.class) .isEqualTo(expected); }
@Test public void simpleObjectOfScalars_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("{" + " \"stringMember\": \"foo\"," + " \"integerMember\": 42," + " \"floatMember\": 1234.56," + " \"booleanMember\": true," + " \"nullMember\": null" + "}"); SdkObjectNode expected = SdkObjectNode.builder() .putField("stringMember", scalar("foo")) .putField("integerMember", scalar("42")) .putField("floatMember", scalar("1234.56")) .putField("booleanMember", scalar("true")) .putField("nullMember", nullNode()) .build(); assertThat(node).isInstanceOf(SdkObjectNode.class) .isEqualTo(expected); }
@Test public void nestedObject_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("{" + " \"structMember\": {" + " \"floatMember\": 1234.56," + " \"booleanMember\": true," + " \"nullMember\": null" + " }," + " \"integerMember\": 42" + "}"); SdkObjectNode expected = SdkObjectNode.builder() .putField("structMember", SdkObjectNode.builder() .putField("floatMember", scalar("1234.56")) .putField("booleanMember", scalar("true")) .putField("nullMember", nullNode()) .build()) .putField("integerMember", scalar("42")) .build(); assertThat(node).isInstanceOf(SdkObjectNode.class) .isEqualTo(expected); }
@Test public void emptyArray_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("[]"); SdkArrayNode expected = SdkArrayNode.builder().build(); assertThat(node).isInstanceOf(SdkArrayNode.class) .isEqualTo(expected); }
@Test public void arrayOfScalars_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("[\"foo\", 42, null, false, 1234.56]"); SdkArrayNode expected = SdkArrayNode.builder() .addItem(scalar("foo")) .addItem(scalar("42")) .addItem(nullNode()) .addItem(scalar("false")) .addItem(scalar("1234.56")) .build(); assertThat(node).isInstanceOf(SdkArrayNode.class) .isEqualTo(expected); }
@Test public void nestedArray_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("[[\"valOne\", \"valTwo\"], [\"valThree\", \"valFour\"]]"); SdkArrayNode expected = SdkArrayNode.builder() .addItem(array(scalar("valOne"), scalar("valTwo"))) .addItem(array(scalar("valThree"), scalar("valFour"))) .build(); assertThat(node).isInstanceOf(SdkArrayNode.class) .isEqualTo(expected); }
@Test public void complexObject_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("{" + " \"stringMember\":\"foo\"," + " \"deeplyNestedArray\":[" + " [\"valOne\", 42, null]," + " \"valTwo\"," + " [" + " []," + " [\"valThree\"]" + " ]" + " ]," + " \"deeplyNestedObject\":{\n" + " \"deeplyNestedArray\":[" + " [\"valOne\", 42, null]," + " \"valTwo\"," + " [" + " []," + " [\"valThree\"]" + " ]" + " ]," + " \"nestedObject\":{" + " \"stringMember\":\"foo\"," + " \"integerMember\":42," + " \"floatMember\":1234.56," + " \"booleanMember\":true," + " \"furtherNestedObject\":{" + " \"stringMember\":\"foo\"," + " \"arrayMember\":[" + " \"valOne\"," + " \"valTwo\"" + " ],\n" + " \"nullMember\":null" + " }" + " }" + " }" + "}"); SdkArrayNode deeplyNestedArray = array( array(scalar("valOne"), scalar("42"), nullNode()), scalar("valTwo"), array(array(), array(scalar("valThree"))) ); SdkObjectNode furtherNestedObject = SdkObjectNode.builder() .putField("stringMember", scalar("foo")) .putField("arrayMember", array(scalar("valOne"), scalar("valTwo"))) .putField("nullMember", nullNode()) .build(); SdkObjectNode deeplyNestedObject = SdkObjectNode.builder() .putField("deeplyNestedArray", deeplyNestedArray) .putField("nestedObject", SdkObjectNode.builder() .putField("stringMember", scalar("foo")) .putField("integerMember", scalar("42")) .putField("floatMember", scalar("1234.56")) .putField("booleanMember", scalar("true")) .putField("furtherNestedObject", furtherNestedObject) .build()) .build(); SdkObjectNode expected = SdkObjectNode.builder() .putField("stringMember", scalar("foo")) .putField("deeplyNestedArray", deeplyNestedArray) .putField("deeplyNestedObject", deeplyNestedObject) .build(); assertThat(node).isInstanceOf(SdkObjectNode.class) .isEqualTo(expected); } |
ProfileFileLocation { @SdkInternalApi static String userHomeDirectory() { boolean isWindows = JavaSystemSetting.OS_NAME.getStringValue() .map(s -> StringUtils.lowerCase(s).startsWith("windows")) .orElse(false); String home = System.getenv("HOME"); if (home != null) { return home; } if (isWindows) { String userProfile = System.getenv("USERPROFILE"); if (userProfile != null) { return userProfile; } String homeDrive = System.getenv("HOMEDRIVE"); String homePath = System.getenv("HOMEPATH"); if (homeDrive != null && homePath != null) { return homeDrive + homePath; } } return JavaSystemSetting.USER_HOME.getStringValueOrThrow(); } private ProfileFileLocation(); static Path configurationFilePath(); static Path credentialsFilePath(); static Optional<Path> configurationFileLocation(); static Optional<Path> credentialsFileLocation(); } | @Test public void homeDirectoryResolutionPriorityIsCorrectOnWindows() throws Exception { String osName = System.getProperty("os.name"); try { System.setProperty("os.name", "Windows 7"); ENVIRONMENT_VARIABLE_HELPER.set("HOME", "home"); ENVIRONMENT_VARIABLE_HELPER.set("USERPROFILE", "userprofile"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEDRIVE", "homedrive"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEPATH", "homepath"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo("home"); ENVIRONMENT_VARIABLE_HELPER.remove("HOME"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo("userprofile"); ENVIRONMENT_VARIABLE_HELPER.remove("USERPROFILE"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo("homedrivehomepath"); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEDRIVE"); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEPATH"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo(System.getProperty("user.home")); } finally { System.setProperty("os.name", osName); } }
@Test public void homeDirectoryResolutionPriorityIsCorrectOnNonWindows() throws Exception { String osName = System.getProperty("os.name"); try { System.setProperty("os.name", "Linux"); ENVIRONMENT_VARIABLE_HELPER.set("HOME", "home"); ENVIRONMENT_VARIABLE_HELPER.set("USERPROFILE", "userprofile"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEDRIVE", "homedrive"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEPATH", "homepath"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo("home"); ENVIRONMENT_VARIABLE_HELPER.remove("HOME"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo(System.getProperty("user.home")); ENVIRONMENT_VARIABLE_HELPER.remove("USERPROFILE"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo(System.getProperty("user.home")); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEDRIVE"); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEPATH"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo(System.getProperty("user.home")); } finally { System.setProperty("os.name", osName); } } |
ProfileFile { public Map<String, Profile> profiles() { return profiles; } private ProfileFile(Map<String, Map<String, String>> rawProfiles); static Builder builder(); static Aggregator aggregator(); static ProfileFile defaultProfileFile(); Optional<Profile> profile(String profileName); Map<String, Profile> profiles(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void invalidProfilesNamesAreIgnored() { assertThat(aggregateFileProfiles("[profile in valid]\n" + "name = value\n", "[in valid 2]\n" + "name2 = value2")) .isEqualTo(profiles()); }
@Test public void configProfilesWithoutPrefixAreIgnored() { assertThat(configFileProfiles("[foo]\n" + "name = value")) .isEqualTo(profiles()); }
@Test public void credentialsProfilesWithPrefixAreIgnored() { assertThat(credentialFileProfiles("[profile foo]\n" + "name = value")) .isEqualTo(profiles()); } |
ProfileFile { public static ProfileFile defaultProfileFile() { return ProfileFile.aggregator() .applyMutation(ProfileFile::addCredentialsFile) .applyMutation(ProfileFile::addConfigFile) .build(); } private ProfileFile(Map<String, Map<String, String>> rawProfiles); static Builder builder(); static Aggregator aggregator(); static ProfileFile defaultProfileFile(); Optional<Profile> profile(String profileName); Map<String, Profile> profiles(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void loadingDefaultProfileFileWorks() { ProfileFile.defaultProfileFile(); } |
EnhancedS3ServiceMetadata implements ServiceMetadata { @Override public URI endpointFor(Region region) { if (Region.US_EAST_1.equals(region) && !useUsEast1RegionalEndpoint.getValue()) { return URI.create("s3.amazonaws.com"); } return s3ServiceMetadata.endpointFor(region); } EnhancedS3ServiceMetadata(); private EnhancedS3ServiceMetadata(ServiceMetadataConfiguration config); @Override URI endpointFor(Region region); @Override Region signingRegion(Region region); @Override List<Region> regions(); @Override List<ServicePartitionMetadata> servicePartitions(); @Override ServiceMetadata reconfigure(ServiceMetadataConfiguration configuration); } | @Test public void optionNotSet_returnsGlobalEndpoint() { assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_GLOBAL_ENDPOINT); }
@Test public void regionalSet_profile_returnsRegionalEndpoint() throws URISyntaxException { String testFile = "/profileconfig/s3_regional_config_profile.tst"; System.setProperty(ProfileFileSystemSetting.AWS_PROFILE.property(), "regional_s3_endpoint"); System.setProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property(), Paths.get(getClass().getResource(testFile).toURI()).toString()); assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_IAD_REGIONAL_ENDPOINT); }
@Test public void regionalSet_env_returnsRegionalEndpoint() { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.environmentVariable(), "regional"); assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_IAD_REGIONAL_ENDPOINT); }
@Test public void regionalSet_mixedCase_env_returnsRegionalEndpoint() { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.environmentVariable(), "rEgIoNaL"); assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_IAD_REGIONAL_ENDPOINT); }
@Test public void global_env_returnsGlobalEndpoint() { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.environmentVariable(), "non_regional"); assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_GLOBAL_ENDPOINT); }
@Test public void valueNotEqualToRegional_env_returnsGlobalEndpoint() { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.environmentVariable(), "some-nonsense-value"); assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_GLOBAL_ENDPOINT); } |
AwsRegionProviderChain implements AwsRegionProvider { @Override public Region getRegion() throws SdkClientException { List<String> exceptionMessages = null; for (AwsRegionProvider provider : providers) { try { Region region = provider.getRegion(); if (region != null) { return region; } } catch (Exception e) { log.debug("Unable to load region from {}:{}", provider.toString(), e.getMessage()); String message = provider.toString() + ": " + e.getMessage(); if (exceptionMessages == null) { exceptionMessages = new ArrayList<>(); } exceptionMessages.add(message); } } throw SdkClientException.builder() .message("Unable to load region from any of the providers in the chain " + this + ": " + exceptionMessages) .build(); } AwsRegionProviderChain(AwsRegionProvider... providers); @Override Region getRegion(); } | @Test public void firstProviderInChainGivesRegionInformation_DoesNotConsultOtherProviders() { AwsRegionProvider providerOne = mock(AwsRegionProvider.class); AwsRegionProvider providerTwo = mock(AwsRegionProvider.class); AwsRegionProvider providerThree = mock(AwsRegionProvider.class); AwsRegionProviderChain chain = new AwsRegionProviderChain(providerOne, providerTwo, providerThree); final Region expectedRegion = Region.of("some-region-string"); when(providerOne.getRegion()).thenReturn(expectedRegion); assertEquals(expectedRegion, chain.getRegion()); verify(providerTwo, never()).getRegion(); verify(providerThree, never()).getRegion(); }
@Test public void lastProviderInChainGivesRegionInformation() { final Region expectedRegion = Region.of("some-region-string"); AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new NeverAwsRegionProvider(), new StaticAwsRegionProvider( expectedRegion)); assertEquals(expectedRegion, chain.getRegion()); }
@Test public void providerThrowsException_ContinuesToNextInChain() { final Region expectedRegion = Region.of("some-region-string"); AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new FaultyAwsRegionProvider(), new StaticAwsRegionProvider( expectedRegion)); assertEquals(expectedRegion, chain.getRegion()); }
@Test(expected = Error.class) public void providerThrowsError_DoesNotContinueChain() { final Region expectedRegion = Region.of("some-region-string"); AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new FatalAwsRegionProvider(), new StaticAwsRegionProvider( expectedRegion)); assertEquals(expectedRegion, chain.getRegion()); }
@Test (expected = SdkClientException.class) public void noProviderGivesRegion_ThrowsException() { AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new NeverAwsRegionProvider(), new NeverAwsRegionProvider()); chain.getRegion(); } |
LazyAwsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() { return delegate.getValue().getRegion(); } LazyAwsRegionProvider(Supplier<AwsRegionProvider> delegateConstructor); @Override Region getRegion(); @Override String toString(); } | @Test public void getRegionInvokesSupplierExactlyOnce() { LazyAwsRegionProvider lazyRegionProvider = new LazyAwsRegionProvider(regionProviderConstructor); lazyRegionProvider.getRegion(); lazyRegionProvider.getRegion(); Mockito.verify(regionProviderConstructor, Mockito.times(1)).get(); Mockito.verify(regionProvider, Mockito.times(2)).getRegion(); } |
AwsProfileRegionProvider implements AwsRegionProvider { @Override public Region getRegion() { return profileFile.get() .profile(profileName) .map(p -> p.properties().get(ProfileProperty.REGION)) .map(Region::of) .orElseThrow(() -> SdkClientException.builder() .message("No region provided in profile: " + profileName) .build()); } AwsProfileRegionProvider(); AwsProfileRegionProvider(Supplier<ProfileFile> profileFile, String profileName); @Override Region getRegion(); } | @Test public void nonExistentDefaultConfigFile_ThrowsException() { settingsHelper.set(ProfileFileSystemSetting.AWS_CONFIG_FILE, "/var/tmp/this/is/invalid.txt"); settingsHelper.set(ProfileFileSystemSetting.AWS_SHARED_CREDENTIALS_FILE, "/var/tmp/this/is/also.invalid.txt"); assertThatThrownBy(() -> new AwsProfileRegionProvider().getRegion()) .isInstanceOf(SdkClientException.class) .hasMessageContaining("No region provided in profile: default"); }
@Test public void profilePresentAndRegionIsSet_ProvidesCorrectRegion() throws URISyntaxException { String testFile = "/profileconfig/test-profiles.tst"; settingsHelper.set(ProfileFileSystemSetting.AWS_PROFILE, "test"); settingsHelper.set(ProfileFileSystemSetting.AWS_CONFIG_FILE, Paths.get(getClass().getResource(testFile).toURI()).toString()); assertThat(new AwsProfileRegionProvider().getRegion()).isEqualTo(Region.of("saa")); } |
EC2MetadataUtils { public static String getToken() { try { return HttpResourcesUtils.instance().readResource(TOKEN_ENDPOINT_PROVIDER, "PUT"); } catch (Exception e) { boolean is400ServiceException = e instanceof SdkServiceException && ((SdkServiceException) e).statusCode() == 400; if (is400ServiceException) { throw SdkClientException.builder() .message("Unable to fetch metadata token") .cause(e) .build(); } return null; } } private EC2MetadataUtils(); static String getAmiId(); static String getAmiLaunchIndex(); static String getAmiManifestPath(); static List<String> getAncestorAmiIds(); static String getInstanceAction(); static String getInstanceId(); static String getInstanceType(); static String getLocalHostName(); static String getMacAddress(); static String getPrivateIpAddress(); static String getAvailabilityZone(); static List<String> getProductCodes(); static String getPublicKey(); static String getRamdiskId(); static String getReservationId(); static List<String> getSecurityGroups(); static IamInfo getIamInstanceProfileInfo(); static InstanceInfo getInstanceInfo(); static String getInstanceSignature(); static String getEC2InstanceRegion(); static Map<String, IamSecurityCredential> getIamSecurityCredentials(); static Map<String, String> getBlockDeviceMapping(); static List<NetworkInterface> getNetworkInterfaces(); static String getUserData(); static String getData(String path); static String getData(String path, int tries); static List<String> getItems(String path); static List<String> getItems(String path, int tries); static String getToken(); } | @Test public void getToken_queriesCorrectPath() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); String token = EC2MetadataUtils.getToken(); assertThat(token).isEqualTo("some-token"); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); } |
EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } private EC2MetadataUtils(); static String getAmiId(); static String getAmiLaunchIndex(); static String getAmiManifestPath(); static List<String> getAncestorAmiIds(); static String getInstanceAction(); static String getInstanceId(); static String getInstanceType(); static String getLocalHostName(); static String getMacAddress(); static String getPrivateIpAddress(); static String getAvailabilityZone(); static List<String> getProductCodes(); static String getPublicKey(); static String getRamdiskId(); static String getReservationId(); static List<String> getSecurityGroups(); static IamInfo getIamInstanceProfileInfo(); static InstanceInfo getInstanceInfo(); static String getInstanceSignature(); static String getEC2InstanceRegion(); static Map<String, IamSecurityCredential> getIamSecurityCredentials(); static Map<String, String> getBlockDeviceMapping(); static List<NetworkInterface> getNetworkInterfaces(); static String getUserData(); static String getData(String path); static String getData(String path, int tries); static List<String> getItems(String path); static List<String> getItems(String path, int tries); static String getToken(); } | @Test public void getAmiId_queriesAndIncludesToken() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withHeader(TOKEN_HEADER, equalTo("some-token"))); }
@Test public void getAmiId_tokenQueryTimeout_fallsBackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withFixedDelay(Integer.MAX_VALUE))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER)); }
@Test public void getAmiId_queriesTokenResource_403Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(403).withBody("oops"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER)); }
@Test public void getAmiId_queriesTokenResource_404Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(404).withBody("oops"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER)); }
@Test public void getAmiId_queriesTokenResource_405Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(405).withBody("oops"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER)); }
@Test public void getAmiId_queriesTokenResource_400Error_throws() { thrown.expect(SdkClientException.class); thrown.expectMessage("token"); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(400).withBody("oops"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); } |
DefaultMetricCollection implements MetricCollection { @SuppressWarnings("unchecked") @Override public <T> List<T> metricValues(SdkMetric<T> metric) { if (metrics.containsKey(metric)) { List<MetricRecord<?>> metricRecords = metrics.get(metric); List<?> values = metricRecords.stream() .map(MetricRecord::value) .collect(toList()); return (List<T>) Collections.unmodifiableList(values); } return Collections.emptyList(); } DefaultMetricCollection(String name, Map<SdkMetric<?>,
List<MetricRecord<?>>> metrics, List<MetricCollection> children); @Override String name(); @SuppressWarnings("unchecked") @Override List<T> metricValues(SdkMetric<T> metric); @Override List<MetricCollection> children(); @Override Instant creationTime(); @Override Iterator<MetricRecord<?>> iterator(); @Override String toString(); } | @Test public void testMetricValues_noValues_returnsEmptyList() { DefaultMetricCollection foo = new DefaultMetricCollection("foo", Collections.emptyMap(), Collections.emptyList()); assertThat(foo.metricValues(M1)).isEmpty(); } |
DefaultMetricCollection implements MetricCollection { @Override public List<MetricCollection> children() { return children; } DefaultMetricCollection(String name, Map<SdkMetric<?>,
List<MetricRecord<?>>> metrics, List<MetricCollection> children); @Override String name(); @SuppressWarnings("unchecked") @Override List<T> metricValues(SdkMetric<T> metric); @Override List<MetricCollection> children(); @Override Instant creationTime(); @Override Iterator<MetricRecord<?>> iterator(); @Override String toString(); } | @Test public void testChildren_noChildren_returnsEmptyList() { DefaultMetricCollection foo = new DefaultMetricCollection("foo", Collections.emptyMap(), Collections.emptyList()); assertThat(foo.children()).isEmpty(); } |
DefaultSdkMetric extends AttributeMap.Key<T> implements SdkMetric<T> { public static <T> SdkMetric<T> create(String name, Class<T> clzz, MetricLevel level, MetricCategory c1, MetricCategory... cn) { Stream<MetricCategory> categoryStream = Stream.of(c1); if (cn != null) { categoryStream = Stream.concat(categoryStream, Stream.of(cn)); } Set<MetricCategory> categories = categoryStream.collect(Collectors.toSet()); return create(name, clzz, level, categories); } private DefaultSdkMetric(String name, Class<T> clzz, MetricLevel level, Set<MetricCategory> categories); @Override String name(); @Override Set<MetricCategory> categories(); @Override MetricLevel level(); @Override Class<T> valueClass(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SdkMetric<T> create(String name, Class<T> clzz, MetricLevel level,
MetricCategory c1, MetricCategory... cn); static SdkMetric<T> create(String name, Class<T> clzz, MetricLevel level, Set<MetricCategory> categories); } | @Test public void testOf_variadicOverload_c1Null_throws() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("must not contain null elements"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, (MetricCategory) null); }
@Test public void testOf_variadicOverload_c1NotNull_cnNull_doesNotThrow() { SdkMetric.create("event", Integer.class, MetricLevel.INFO, MetricCategory.CORE, null); }
@Test public void testOf_variadicOverload_cnContainsNull_throws() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("must not contain null elements"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, MetricCategory.CORE, new MetricCategory[]{null }); }
@Test public void testOf_setOverload_null_throws() { thrown.expect(NullPointerException.class); thrown.expectMessage("object is null"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, (Set<MetricCategory>) null); }
@Test public void testOf_setOverload_nullElement_throws() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("categories must not contain null elements"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, Stream.of((MetricCategory) null).collect(Collectors.toSet())); }
@Test public void testOf_namePreviouslyUsed_throws() { String fooName = "metricEvent"; thrown.expect(IllegalArgumentException.class); thrown.expectMessage(fooName + " has already been created"); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); }
@Test public void testOf_namePreviouslyUsed_differentArgs_throws() { String fooName = "metricEvent"; thrown.expect(IllegalArgumentException.class); thrown.expectMessage(fooName + " has already been created"); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); SdkMetric.create(fooName, Long.class, MetricLevel.INFO, MetricCategory.HTTP_CLIENT); } |
StaticCredentialsProvider implements AwsCredentialsProvider { public static StaticCredentialsProvider create(AwsCredentials credentials) { return new StaticCredentialsProvider(credentials); } private StaticCredentialsProvider(AwsCredentials credentials); static StaticCredentialsProvider create(AwsCredentials credentials); @Override AwsCredentials resolveCredentials(); @Override String toString(); } | @Test(expected = RuntimeException.class) public void nullCredentials_ThrowsIllegalArgumentException() { StaticCredentialsProvider.create(null); } |
InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | @Test public void resolveCredentials_metadataLookupDisabled_throws() { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property(), "true"); thrown.expect(SdkClientException.class); thrown.expectMessage("Loading credentials from local endpoint is disabled"); try { InstanceProfileCredentialsProvider.builder().build().resolveCredentials(); } finally { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property()); } }
@Test public void resolveCredentials_requestsIncludeUserAgent() { String stubToken = "some-token"; stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); String userAgentHeader = "User-Agent"; String userAgent = UserAgentUtils.getUserAgent(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(userAgentHeader, equalTo(userAgent))); }
@Test public void resolveCredentials_queriesTokenResource() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); }
@Test public void resolveCredentials_queriesTokenResource_includedInCredentialsRequests() { String stubToken = "some-token"; stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(TOKEN_HEADER, equalTo(stubToken))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(TOKEN_HEADER, equalTo(stubToken))); }
@Test public void resolveCredentials_queriesTokenResource_403Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(403).withBody("oops"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); }
@Test public void resolveCredentials_queriesTokenResource_404Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(404).withBody("oops"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); }
@Test public void resolveCredentials_queriesTokenResource_405Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(405).withBody("oops"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); }
@Test public void resolveCredentials_queriesTokenResource_400Error_throws() { thrown.expect(SdkClientException.class); thrown.expectMessage("token"); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(400).withBody("oops"))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); }
@Test public void resolveCredentials_queriesTokenResource_socketTimeout_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token").withFixedDelay(Integer.MAX_VALUE))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); }
@Test public void resolveCredentials_endpointSettingEmpty_throws() { thrown.expect(SdkClientException.class); System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), ""); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); }
@Test public void resolveCredentials_endpointSettingHostNotExists_throws() { thrown.expect(SdkClientException.class); System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "some-host-that-does-not-exist"); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); } |
ContainerCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private ContainerCredentialsProvider(BuilderImpl builder); static Builder builder(); @Override String toString(); } | @Test(expected = SdkClientException.class) public void testEnvVariableNotSet() { helper.remove(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); ContainerCredentialsProvider.builder() .build() .resolveCredentials(); } |
HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } protected HttpCredentialsProvider(BuilderImpl<?, ?> builder); HttpCredentialsProvider(boolean asyncCredentialUpdateEnabled, String asyncThreadName); @Override AwsCredentials resolveCredentials(); @Override void close(); } | @Test public void testLoadCredentialsParsesJsonResponseProperly() { stubForSuccessResponseWithCustomBody(successResponse); HttpCredentialsProvider credentialsProvider = testCredentialsProvider(); AwsSessionCredentials credentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials(); assertThat(credentials.accessKeyId()).isEqualTo("ACCESS_KEY_ID"); assertThat(credentials.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY"); assertThat(credentials.sessionToken()).isEqualTo("TOKEN_TOKEN_TOKEN"); }
@Test public void testNoMetadataService() throws Exception { stubForErrorResponse(); HttpCredentialsProvider credentialsProvider = testCredentialsProvider(); assertThatExceptionOfType(SdkClientException.class).isThrownBy(credentialsProvider::resolveCredentials); stubForSuccessResonseWithCustomExpirationDate(new Date(System.currentTimeMillis() + ONE_MINUTE * 4)); credentialsProvider.resolveCredentials(); stubForErrorResponse(); assertThatExceptionOfType(SdkClientException.class).isThrownBy(credentialsProvider::resolveCredentials); }
@Test public void basicCachingFunctionalityWorks() { HttpCredentialsProvider credentialsProvider = testCredentialsProvider(); stubForSuccessResonseWithCustomExpirationDate(Date.from(Instant.now().plus(Duration.ofDays(10)))); assertThat(credentialsProvider.resolveCredentials()).isNotNull(); stubForErrorResponse(); assertThat(credentialsProvider.resolveCredentials()).isNotNull(); } |
LazyAwsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor) { return new LazyAwsCredentialsProvider(delegateConstructor); } private LazyAwsCredentialsProvider(Supplier<AwsCredentialsProvider> delegateConstructor); static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor); @Override AwsCredentials resolveCredentials(); @Override void close(); @Override String toString(); } | @Test public void creationDoesntInvokeSupplier() { LazyAwsCredentialsProvider.create(credentialsConstructor); Mockito.verifyZeroInteractions(credentialsConstructor); } |
ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } | @Test public void profileFileWithStaticCredentialsLoadsCorrectly() { ProfileFile profileFile = allTypesProfile(); assertThat(profileFile.profile("default")).hasValueSatisfying(profile -> { assertThat(profile.name()).isEqualTo("default"); assertThat(profile.property(ProfileProperty.AWS_ACCESS_KEY_ID)).hasValue("defaultAccessKey"); assertThat(profile.toString()).contains("default"); assertThat(profile.property(ProfileProperty.REGION)).isNotPresent(); assertThat(new ProfileCredentialsUtils(profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> { assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); }); }); }); }
@Test public void profileFileWithSessionCredentialsLoadsCorrectly() { ProfileFile profileFile = allTypesProfile(); assertThat(profileFile.profile("profile-with-session-token")).hasValueSatisfying(profile -> { assertThat(profile.property(ProfileProperty.REGION)).isNotPresent(); assertThat(new ProfileCredentialsUtils(profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> { assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials).isInstanceOf(AwsSessionCredentials.class); assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); Assertions.assertThat(((AwsSessionCredentials) credentials).sessionToken()).isEqualTo("awsSessionToken"); }); }); }); }
@Test public void profileFileWithProcessCredentialsLoadsCorrectly() { ProfileFile profileFile = allTypesProfile(); assertThat(profileFile.profile("profile-credential-process")).hasValueSatisfying(profile -> { assertThat(profile.property(ProfileProperty.REGION)).isNotPresent(); assertThat(new ProfileCredentialsUtils(profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> { assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials).isInstanceOf(AwsBasicCredentials.class); assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); }); }); }); }
@Test public void profileFileWithCircularDependencyThrowsExceptionWhenResolvingCredentials() { ProfileFile configFile = configFile("[profile source]\n" + "aws_access_key_id=defaultAccessKey\n" + "aws_secret_access_key=defaultSecretAccessKey\n" + "\n" + "[profile test]\n" + "source_profile=test3\n" + "role_arn=arn:aws:iam::123456789012:role/testRole\n" + "\n" + "[profile test2]\n" + "source_profile=test\n" + "role_arn=arn:aws:iam::123456789012:role/testRole2\n" + "\n" + "[profile test3]\n" + "source_profile=test2\n" + "role_arn=arn:aws:iam::123456789012:role/testRole3"); Assertions.assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile.profile("test").get(), configFile::profile) .credentialsProvider()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Invalid profile file: Circular relationship detected with profiles"); }
@Test public void profileWithBothCredentialSourceAndSourceProfileThrowsException() { ProfileFile configFile = configFile("[profile test]\n" + "source_profile=source\n" + "credential_source=Environment\n" + "role_arn=arn:aws:iam::123456789012:role/testRole3\n" + "\n" + "[profile source]\n" + "aws_access_key_id=defaultAccessKey\n" + "aws_secret_access_key=defaultSecretAccessKey"); Assertions.assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile.profile("test").get(), configFile::profile) .credentialsProvider()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Invalid profile file: profile has both source_profile and credential_source."); }
@Test public void profileWithInvalidCredentialSourceThrowsException() { ProfileFile configFile = configFile("[profile test]\n" + "credential_source=foobar\n" + "role_arn=arn:aws:iam::123456789012:role/testRole3"); Assertions.assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile.profile("test").get(), configFile::profile) .credentialsProvider()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("foobar is not a valid credential_source"); } |
ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); static ProfileCredentialsProvider create(); static ProfileCredentialsProvider create(String profileName); static Builder builder(); @Override AwsCredentials resolveCredentials(); @Override String toString(); @Override void close(); } | @Test public void missingProfileFileThrowsExceptionInGetCredentials() { ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); }
@Test public void missingProfileThrowsExceptionInGetCredentials() { ProfileFile file = profileFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder().profileFile(file).profileName("foo").build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); }
@Test public void profileWithoutCredentialsThrowsExceptionInGetCredentials() { ProfileFile file = profileFile("[default]"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder().profileFile(file).profileName("default").build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } |
Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } | @Test public void testSigning() throws Exception { final String expectedAuthorizationHeaderWithoutSha256Header = "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=77fe7c02927966018667f21d1dc3dfad9057e58401cbb9ed64f1b7868288e35a"; final String expectedAuthorizationHeaderWithSha256Header = "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date;x-amz-sha256, " + "Signature=e73e20539446307a5dc71252dbd5b97e861f1d1267456abda3ebd8d57e519951"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); SdkHttpFullRequest.Builder request = generateBasicRequest(); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")) .hasValue(expectedAuthorizationHeaderWithoutSha256Header); request = generateBasicRequest(); request.putHeader("x-amz-sha256", "required"); signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorizationHeaderWithSha256Header); }
@Test public void queryParamsWithNullValuesAreStillSignedWithTrailingEquals() throws Exception { final String expectedAuthorizationHeaderWithoutSha256Header = "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=c45a3ff1f028e83017f3812c06b4440f0b3240264258f6e18cd683b816990ba4"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); SdkHttpFullRequest.Builder request = generateBasicRequest().putRawQueryParameter("Foo", (String) null); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")) .hasValue(expectedAuthorizationHeaderWithoutSha256Header); }
@Test public void testPresigning() throws Exception { final String expectedAmzSignature = "bf7ae1c2f266d347e290a2aee7b126d38b8a695149d003b9fab2ed1eb6d6ebda"; final String expectedAmzCredentials = "access/19810216/us-east-1/demo/aws4_request"; final String expectedAmzHeader = "19810216T063000Z"; final String expectedAmzExpires = "604800"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); SdkHttpFullRequest request = generateBasicRequest().build(); SdkHttpFullRequest signed = SignerTestUtils.presignRequest(signer, request, credentials, null, "demo", signingOverrideClock, "us-east-1"); assertEquals(expectedAmzSignature, signed.rawQueryParameters().get("X-Amz-Signature").get(0)); assertEquals(expectedAmzCredentials, signed.rawQueryParameters().get("X-Amz-Credential").get(0)); assertEquals(expectedAmzHeader, signed.rawQueryParameters().get("X-Amz-Date").get(0)); assertEquals(expectedAmzExpires, signed.rawQueryParameters().get("X-Amz-Expires").get(0)); }
@Test public void testAnonymous() throws Exception { AwsCredentials credentials = AnonymousCredentialsProvider.create().resolveCredentials(); SdkHttpFullRequest request = generateBasicRequest().build(); SignerTestUtils.signRequest(signer, request, credentials, "demo", signingOverrideClock, "us-east-1"); assertNull(request.headers().get("Authorization")); }
@Test public void xAmznTraceId_NotSigned() throws Exception { AwsBasicCredentials credentials = AwsBasicCredentials.create("akid", "skid"); SdkHttpFullRequest.Builder request = generateBasicRequest(); request.putHeader("X-Amzn-Trace-Id", " Root=1-584b150a-708479cb060007ffbf3ee1da;Parent=36d3dbcfd150aac9;Sampled=1"); SdkHttpFullRequest actual = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(actual.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=581d0042389009a28d461124138f1fe8eeb8daed87611d2a2b47fd3d68d81d73"); } |
EventStreamAws4Signer extends BaseEventStreamAsyncAws4Signer { public static EventStreamAws4Signer create() { return new EventStreamAws4Signer(); } private EventStreamAws4Signer(); static EventStreamAws4Signer create(); } | @Test public void openStreamEventSignaturesCanRollOverBetweenDays() { EventStreamAws4Signer signer = EventStreamAws4Signer.create(); Region region = Region.US_WEST_2; AwsCredentials credentials = AwsBasicCredentials.create("a", "s"); String signingName = "name"; AdjustableClock clock = new AdjustableClock(); clock.time = Instant.parse("2020-01-01T23:59:59Z"); SdkHttpFullRequest initialRequest = SdkHttpFullRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.GET) .build(); SdkHttpFullRequest signedRequest = SignerTestUtils.signRequest(signer, initialRequest, credentials, signingName, clock, region.id()); ByteBuffer event = new Message(Collections.emptyMap(), "foo".getBytes(UTF_8)).toByteBuffer(); Callable<ByteBuffer> lastEvent = () -> { clock.time = Instant.parse("2020-01-02T00:00:00Z"); return event; }; AsyncRequestBody requestBody = AsyncRequestBody.fromPublisher(Flowable.concatArray(Flowable.just(event), Flowable.fromCallable(lastEvent))); AsyncRequestBody signedBody = SignerTestUtils.signAsyncRequest(signer, signedRequest, requestBody, credentials, signingName, clock, region.id()); List<Message> signedMessages = readMessages(signedBody); assertThat(signedMessages.size()).isEqualTo(3); Map<String, HeaderValue> firstMessageHeaders = signedMessages.get(0).getHeaders(); assertThat(firstMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-01T23:59:59Z"); assertThat(Base64.getEncoder().encodeToString(firstMessageHeaders.get(":chunk-signature").getByteArray())) .isEqualTo("EFt7ZU043r/TJE8U+1GxJXscmNxoqmIdGtUIl8wE9u0="); Map<String, HeaderValue> lastMessageHeaders = signedMessages.get(2).getHeaders(); assertThat(lastMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-02T00:00:00Z"); assertThat(Base64.getEncoder().encodeToString(lastMessageHeaders.get(":chunk-signature").getByteArray())) .isEqualTo("UTRGo0D7BQytiVkH1VofR/8f3uFsM4V5QR1A8grr1+M="); } |
BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); static final String EVENT_STREAM_SIGNATURE; static final String EVENT_STREAM_DATE; } | @Test public void toDebugString_emptyPayload_generatesCorrectString() { Message m = new Message(headers, new byte[0]); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=}"); }
@Test public void toDebugString_noHeaders_emptyPayload_generatesCorrectString() { Message m = new Message(new LinkedHashMap<>(), new byte[0]); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={}, payload=}"); }
@Test public void toDebugString_largePayload_truncate_generatesCorrectString() { byte[] payload = new byte[128]; new Random().nextBytes(payload); Message m = new Message(headers, payload); byte[] first32 = Arrays.copyOf(payload, 32); String expectedPayloadString = BinaryUtils.toHex(first32); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, true)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "...}"); }
@Test public void toDebugString_largePayload_noTruncate_generatesCorrectString() { byte[] payload = new byte[128]; new Random().nextBytes(payload); Message m = new Message(headers, payload); String expectedPayloadString = BinaryUtils.toHex(payload); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "}"); }
@Test public void toDebugString_smallPayload_truncate_doesNotAddEllipsis() { byte[] payload = new byte[8]; new Random().nextBytes(payload); Message m = new Message(headers, payload); String expectedPayloadString = BinaryUtils.toHex(payload); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, true)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "}"); } |
SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); boolean isValidForDate(Instant other); byte[] getSigningKey(); } | @Test public void isValidForDate_dayBefore_false() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant dayBefore = Instant.parse("2020-03-02T23:59:59Z"); assertThat(key.isValidForDate(dayBefore)).isFalse(); }
@Test public void isValidForDate_sameDay_true() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant sameDay = Instant.parse("2020-03-03T01:02:03Z"); assertThat(key.isValidForDate(sameDay)).isTrue(); }
@Test public void isValidForDate_dayAfter_false() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant dayAfter = Instant.parse("2020-03-04T00:00:00Z"); assertThat(key.isValidForDate(dayAfter)).isFalse(); } |
ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { @Override public Builder toBuilder() { return builder() .resource(resource) .resourceType(resourceType) .qualifier(qualifier); } private ArnResource(DefaultBuilder builder); Optional<String> resourceType(); String resource(); Optional<String> qualifier(); static Builder builder(); static ArnResource fromString(String resource); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | @Test public void toBuilder() { ArnResource oneResource = ArnResource.fromString("bucket:foobar:1"); ArnResource anotherResource = oneResource.toBuilder().build(); assertThat(oneResource).isEqualTo(anotherResource); assertThat(oneResource.hashCode()).isEqualTo(anotherResource.hashCode()); } |
ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { public static Builder builder() { return new DefaultBuilder(); } private ArnResource(DefaultBuilder builder); Optional<String> resourceType(); String resource(); Optional<String> qualifier(); static Builder builder(); static ArnResource fromString(String resource); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | @Test public void arnResource_nullResource_shouldThrowException() { assertThatThrownBy(() -> ArnResource.builder() .build()).hasMessageContaining("resource must not be null."); } |
Arn implements ToCopyableBuilder<Arn.Builder, Arn> { @Override public Builder toBuilder() { return builder().accountId(accountId) .partition(partition) .region(region) .resource(resource) .service(service) ; } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | @Test public void toBuilder() { Arn oneArn = Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("bucket:foobar:1") .build(); Arn anotherArn = oneArn.toBuilder().build(); assertThat(oneArn).isEqualTo(anotherArn); assertThat(oneArn.hashCode()).isEqualTo(anotherArn.hashCode()); } |
Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | @Test public void arnWithoutPartition_ThrowsIllegalArgumentException() { String arnString = "arn::s3:us-east-1:12345678910:myresource"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("artition must not be blank or empty."); }
@Test public void arnWithoutService_ThrowsIllegalArgumentException() { String arnString = "arn:aws::us-east-1:12345678910:myresource"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("service must not be blank or empty"); }
@Test public void arnWithoutResource_ThrowsIllegalArgumentException() { String arnString = "arn:aws:s3:us-east-1:12345678910:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); }
@Test public void invalidArn_ThrowsIllegalArgumentException() { String arnString = "arn:aws:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); }
@Test public void arnDoesntStartWithArn_ThrowsIllegalArgumentException() { String arnString = "fakearn:aws:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); }
@Test public void invalidArnWithoutPartition_ThrowsIllegalArgumentException() { String arnString = "arn:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); }
@Test public void invalidArnWithoutService_ThrowsIllegalArgumentException() { String arnString = "arn:aws:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); }
@Test public void invalidArnWithoutRegion_ThrowsIllegalArgumentException() { String arnString = "arn:aws:s3:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); }
@Test public void invalidArnWithoutAccountId_ThrowsIllegalArgumentException() { String arnString = "arn:aws:s3:us-east-1:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); } |
Http2Configuration implements ToCopyableBuilder<Http2Configuration.Builder, Http2Configuration> { public static Builder builder() { return new DefaultBuilder(); } private Http2Configuration(DefaultBuilder builder); Long maxStreams(); Integer initialWindowSize(); Duration healthCheckPingPeriod(); @Override Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); static Builder builder(); } | @Test public void builder_returnsInstance() { assertThat(Http2Configuration.builder()).isNotNull(); } |
ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } private ProxyConfiguration(BuilderImpl builder); String scheme(); String host(); int port(); Set<String> nonProxyHosts(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); static Builder builder(); } | @Test public void toBuilder_roundTrip_producesExactCopy() { ProxyConfiguration original = allPropertiesSetConfig(); ProxyConfiguration copy = original.toBuilder().build(); assertThat(copy).isEqualTo(original); }
@Test public void toBuilderModified_doesNotModifySource() { ProxyConfiguration original = allPropertiesSetConfig(); ProxyConfiguration modified = setAllPropertiesToRandomValues(original.toBuilder()).build(); assertThat(original).isNotEqualTo(modified); } |
FutureCancelHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } private FutureCancelHandler(); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable e); static FutureCancelHandler getInstance(); } | @Test public void surfacesCancelExceptionAsIOException() { FutureCancelledException cancelledException = new FutureCancelledException(1L, new CancellationException()); ArgumentCaptor<Throwable> exceptionCaptor = ArgumentCaptor.forClass(Throwable.class); handler.exceptionCaught(ctx, cancelledException); verify(ctx).fireExceptionCaught(exceptionCaptor.capture()); assertThat(exceptionCaptor.getValue()).isInstanceOf(IOException.class); }
@Test public void forwardsExceptionIfNotCancelledException() { ArgumentCaptor<Throwable> exceptionCaptor = ArgumentCaptor.forClass(Throwable.class); Throwable err = new RuntimeException("some other exception"); handler.exceptionCaught(ctx, err); verify(ctx).fireExceptionCaught(exceptionCaptor.capture()); assertThat(exceptionCaptor.getValue()).isEqualTo(err); } |
Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | @Test public void tunnelAlreadyEstablished_doesNotAddInitHandler() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); when(mockAttr.get()).thenReturn(true); tunnelPool.acquire().awaitUninterruptibly(); verify(mockPipeline, never()).addLast(anyObject()); }
@Test(timeout = 1000) public void tunnelNotEstablished_addsInitHandler() throws InterruptedException { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); when(mockAttr.get()).thenReturn(false); CountDownLatch latch = new CountDownLatch(1); when(mockPipeline.addLast(any(ChannelHandler.class))).thenAnswer(i -> { latch.countDown(); return mockPipeline; }); tunnelPool.acquire(); latch.await(); verify(mockPipeline, times(1)).addLast(any(ProxyTunnelInitHandler.class)); }
@Test public void tunnelInitFails_acquireFutureFails() { Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, remoteAddr, initFuture) -> { initFuture.setFailure(new IOException("boom")); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, supplier); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().cause()).hasMessage("boom"); }
@Test public void tunnelInitSucceeds_acquireFutureSucceeds() { Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, supplier); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().getNow()).isEqualTo(mockChannel); }
@Test public void acquireFromDelegatePoolFails_failsFuture() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); when(delegatePool.acquire(any(Promise.class))).thenReturn(GROUP.next().newFailedFuture(new IOException("boom"))); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().cause()).hasMessage("boom"); }
@Test public void sslContextProvided_andProxyUsingHttps_addsSslHandler() { SslHandler mockSslHandler = mock(SslHandler.class); TestSslContext mockSslCtx = new TestSslContext(mockSslHandler); Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx, HTTPS_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, supplier); tunnelPool.acquire().awaitUninterruptibly(); ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class); verify(mockPipeline, times(2)).addLast(handlersCaptor.capture()); assertThat(handlersCaptor.getAllValues().get(0)).isEqualTo(mockSslHandler); }
@Test public void sslContextProvided_andProxyNotUsingHttps_doesNotAddSslHandler() { SslHandler mockSslHandler = mock(SslHandler.class); TestSslContext mockSslCtx = new TestSslContext(mockSslHandler); Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, supplier); tunnelPool.acquire().awaitUninterruptibly(); ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class); verify(mockPipeline).addLast(handlersCaptor.capture()); assertThat(handlersCaptor.getAllValues().get(0)).isNotInstanceOf(SslHandler.class); } |
Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | @Test public void release_releasedToDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); tunnelPool.release(mockChannel); verify(delegatePool).release(eq(mockChannel), any(Promise.class)); }
@Test public void release_withGivenPromise_releasedToDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); Promise mockPromise = mock(Promise.class); tunnelPool.release(mockChannel, mockPromise); verify(delegatePool).release(eq(mockChannel), eq(mockPromise)); } |
Http1TunnelConnectionPool implements ChannelPool { @Override public void close() { delegate.close(); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | @Test public void close_closesDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); tunnelPool.close(); verify(delegatePool).close(); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.