target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void userAgent() { String userAgent = UserAgentUtils.userAgent(); assertNotNull(userAgent); Arrays.stream(userAgent.split(" ")).forEach(str -> assertThat(isValidInput(str)).isTrue()); } | 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; } | 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; } } | 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(); } | 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(); } | 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 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()); } | 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(); } | 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(); } } | 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(); } | 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); } | 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 build_missingProperty_httpRequest() { assertThatThrownBy(() -> generateMinimal().toBuilder().httpRequest(null).build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("httpRequest"); } | @Override public Builder toBuilder() { return new DefaultBuilder(this); } | PresignedGetObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedGetObjectRequest.Builder, PresignedGetObjectRequest> { @Override public Builder toBuilder() { return new DefaultBuilder(this); } } | PresignedGetObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedGetObjectRequest.Builder, PresignedGetObjectRequest> { @Override public Builder toBuilder() { return new DefaultBuilder(this); } private PresignedGetObjectRequest(DefaultBuilder builder); } | PresignedGetObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedGetObjectRequest.Builder, PresignedGetObjectRequest> { @Override public Builder toBuilder() { return new DefaultBuilder(this); } private PresignedGetObjectRequest(DefaultBuilder builder); static Builder builder(); @Override Builder toBuilder(); } | PresignedGetObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedGetObjectRequest.Builder, PresignedGetObjectRequest> { @Override public Builder toBuilder() { return new DefaultBuilder(this); } private PresignedGetObjectRequest(DefaultBuilder builder); static Builder builder(); @Override Builder toBuilder(); } |
@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"); } | 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; } | 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; } } | 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(); } | 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(); } | 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_HasUnknownVendor() { System.clearProperty(JavaSystemSetting.JAVA_VENDOR.property()); String userAgent = UserAgentUtils.userAgent(); assertThat(userAgent).contains("vendor/unknown"); } | 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; } | 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; } } | 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(); } | 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(); } | 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 concurrentRequests_shouldCompleteNormally() { ByteArrayAsyncRequestBody byteArrayReq = new ByteArrayAsyncRequestBody("Hello World!".getBytes()); byteArrayReq.subscribe(subscriber); assertTrue(subscriber.onCompleteCalled.get()); } | @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 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 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); } | 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); } | 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 adjustmentTranslatesCorrectly() { assertThat(adjuster.getAdjustmentInSeconds(responseWithDateOffset(1, HOURS))).isCloseTo(-1 * 60 * 60, within(5)); assertThat(adjuster.getAdjustmentInSeconds(responseWithDateOffset(-14, MINUTES))).isCloseTo(14 * 60, within(5)); } | 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; } } | 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; } } } | 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; } } } | 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); } | 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 farFutureDateTranslatesToZero() { assertThat(adjuster.getAdjustmentInSeconds(responseWithDate("Fri, 31 Dec 9999 23:59:59 GMT"))).isEqualTo(0); } | 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; } } | 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; } } } | 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; } } } | 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); } | 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 badDateTranslatesToZero() { assertThat(adjuster.getAdjustmentInSeconds(responseWithDate("X"))).isEqualTo(0); } | 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; } } | 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; } } } | 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; } } } | 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); } | 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 newStreamClosesPreviousStream() { FileContentStreamProvider provider = new FileContentStreamProvider(testFile); InputStream oldStream = provider.newStream(); provider.newStream(); assertThatThrownBy(oldStream::read).hasMessage("stream is closed"); } | @Override public InputStream newStream() { closeCurrentStream(); currentStream = invokeSafely(() -> Files.newInputStream(filePath)); return currentStream; } | FileContentStreamProvider implements ContentStreamProvider { @Override public InputStream newStream() { closeCurrentStream(); currentStream = invokeSafely(() -> Files.newInputStream(filePath)); return currentStream; } } | FileContentStreamProvider implements ContentStreamProvider { @Override public InputStream newStream() { closeCurrentStream(); currentStream = invokeSafely(() -> Files.newInputStream(filePath)); return currentStream; } FileContentStreamProvider(Path filePath); } | FileContentStreamProvider implements ContentStreamProvider { @Override public InputStream newStream() { closeCurrentStream(); currentStream = invokeSafely(() -> Files.newInputStream(filePath)); return currentStream; } FileContentStreamProvider(Path filePath); @Override InputStream newStream(); } | FileContentStreamProvider implements ContentStreamProvider { @Override public InputStream newStream() { closeCurrentStream(); currentStream = invokeSafely(() -> Files.newInputStream(filePath)); return currentStream; } FileContentStreamProvider(Path filePath); @Override InputStream newStream(); } |
@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); } | 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(); } | 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(); } } | 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(); } | 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); } | 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 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()); } | 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(); } | 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(); } } | 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(); } | 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); } | 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 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); } | 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(); } | 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(); } } | 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(); } | 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); } | 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 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); } | 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(); } | 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(); } } | 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(); } | 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); } | 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 testParseRegionWithIpv4() { assertThat(parseSigningRegion("54.231.16.200", null)).isNotPresent(); } | 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(); } | 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(); } } | 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(); } | 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); } | 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 modifyException_skipsNonUnknownHostExceptions() { IOException exception = new IOException(); assertThat(modifyException(exception)).isEqualTo(exception); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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_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); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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_returnsGenericHelp_forGlobalRegions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.AWS_GLOBAL)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("network"); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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_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"); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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_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"); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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_returnsGenericHelp_forServicesRegionalizedInAllPartitions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.US_EAST_1, "dynamodb")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "global")) .hasMessageContaining("network"); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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_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"); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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 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()); } | @Override public Builder toBuilder() { return builder() .partition(partition) .region(region) .accountId(accountId) .accessPointName(accessPointName); } | S3AccessPointResource implements S3Resource, ToCopyableBuilder<S3AccessPointResource.Builder, S3AccessPointResource> { @Override public Builder toBuilder() { return builder() .partition(partition) .region(region) .accountId(accountId) .accessPointName(accessPointName); } } | 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); } | 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(); } | 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 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"); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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 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(); } | @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; } | 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; } } | 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; } } | 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); } | 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 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); } | @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; } | 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; } } | 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; } } | 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); } | 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 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(); } | @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; } | 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; } } | 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; } } | 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); } | 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 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); } | 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()))); } | 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()))); } } | 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(); } | 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); } | 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_EndpointWithPathSetCorrectly() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar"); } | 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()))); } | 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()))); } } | 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(); } | 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); } | 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_RequestUriAppendedToEndpointPath() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .requestUri("/baz") .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz"); } | 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()))); } | 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()))); } } | 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(); } | 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); } | 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_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"); } | 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()))); } | 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()))); } } | 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(); } | 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); } | 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_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"); } | 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()))); } | 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()))); } } | 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(); } | 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); } | 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_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"); } | 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()))); } | 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()))); } } | 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(); } | 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); } | 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 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())); } | @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 + "'"); } } | 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 + "'"); } } } | 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(); } | 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); } | 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 request_null_returns_null() { Assert.assertNull(ProtocolUtils.addStaticQueryParametersToRequest(null, "foo")); } | @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; } | 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; } } | 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(); } | 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); } | 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 uri_resource_path_null_returns_null() { Assert.assertNull(ProtocolUtils .addStaticQueryParametersToRequest(emptyRequest(), null)); } | @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; } | 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; } } | 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(); } | 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); } | 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 uri_resource_path_doesnot_have_static_query_params_returns_uri_resource_path() { final String uriResourcePath = "/foo/bar"; Assert.assertEquals(uriResourcePath, ProtocolUtils .addStaticQueryParametersToRequest(emptyRequest(), uriResourcePath)); } | @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; } | 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; } } | 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(); } | 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); } | 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 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)); } | @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; } | 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; } } | 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(); } | 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); } | 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 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")); } | @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; } | 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; } } | 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(); } | 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); } | 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 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")); } | @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; } | 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; } } | 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(); } | 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); } | 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 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")); } | @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; } | 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; } } | 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(); } | 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); } | 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 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); } | @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); } | 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); } } | 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); } | 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(); } | 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_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()); } } | @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); } | 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); } } | 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); } | 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(); } | 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 toBuilder_maximal() { assertThat(maximal().toBuilder().build()).isEqualTo(maximal()); } | public Builder toBuilder() { return builder().sdkHttpFullResponse(this.sdkHttpFullResponse) .parsedXml(this.parsedXml) .executionAttributes(this.executionAttributes) .isResponseSuccess(this.isResponseSuccess) .parsedErrorXml(this.parsedErrorXml); } | AwsXmlUnmarshallingContext { public Builder toBuilder() { return builder().sdkHttpFullResponse(this.sdkHttpFullResponse) .parsedXml(this.parsedXml) .executionAttributes(this.executionAttributes) .isResponseSuccess(this.isResponseSuccess) .parsedErrorXml(this.parsedErrorXml); } } | 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); } | 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(); } | 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 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())); } | @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 + "'"); } } | 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 + "'"); } } } | 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(); } | 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); } | 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 toBuilder_minimal() { assertThat(minimal().toBuilder().build()).isEqualTo(minimal()); } | public Builder toBuilder() { return builder().sdkHttpFullResponse(this.sdkHttpFullResponse) .parsedXml(this.parsedXml) .executionAttributes(this.executionAttributes) .isResponseSuccess(this.isResponseSuccess) .parsedErrorXml(this.parsedErrorXml); } | AwsXmlUnmarshallingContext { public Builder toBuilder() { return builder().sdkHttpFullResponse(this.sdkHttpFullResponse) .parsedXml(this.parsedXml) .executionAttributes(this.executionAttributes) .isResponseSuccess(this.isResponseSuccess) .parsedErrorXml(this.parsedErrorXml); } } | 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); } | 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(); } | 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 hashcode_maximal_positive() { assertThat(maximal().hashCode()).isEqualTo(maximal().hashCode()); } | @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; } | 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; } } | 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); } | 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(); } | 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_minimal_positive() { assertThat(minimal().hashCode()).isEqualTo(minimal().hashCode()); } | @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; } | 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; } } | 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); } | 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(); } | 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 simpleString_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("\"foo\""); assertThat(node) .isInstanceOf(SdkScalarNode.class) .matches(s -> ((SdkScalarNode) s).value().equals("foo")); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 simpleNumber_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("42"); assertThat(node) .isInstanceOf(SdkScalarNode.class) .matches(s -> ((SdkScalarNode) s).value().equals("42")); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 decimalNumber_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("1234.56"); assertThat(node) .isInstanceOf(SdkScalarNode.class) .matches(s -> ((SdkScalarNode) s).value().equals("1234.56")); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 falseBoolean_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("false"); assertThat(node) .isInstanceOf(SdkScalarNode.class) .matches(s -> ((SdkScalarNode) s).value().equals("false")); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 trueBoolean_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("true"); assertThat(node) .isInstanceOf(SdkScalarNode.class) .matches(s -> ((SdkScalarNode) s).value().equals("true")); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 jsonNull_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("null"); assertThat(node).isInstanceOf(SdkNullNode.class); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 emptyObject_ParsedCorrecty() throws IOException { SdkJsonNode node = parse("{}"); SdkObjectNode expected = SdkObjectNode.builder().build(); assertThat(node).isInstanceOf(SdkObjectNode.class) .isEqualTo(expected); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 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())); } | @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 + "'"); } } | 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 + "'"); } } } | 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(); } | 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); } | 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 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); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 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); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 emptyArray_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("[]"); SdkArrayNode expected = SdkArrayNode.builder().build(); assertThat(node).isInstanceOf(SdkArrayNode.class) .isEqualTo(expected); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 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); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 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); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 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); } | 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()); } } | 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()); } } } | 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); } | 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); } | 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 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); } } | @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(); } | 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(); } } | 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(); } | 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(); } | 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 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); } } | @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(); } | 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(); } } | 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(); } | 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(); } | 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 invalidProfilesNamesAreIgnored() { assertThat(aggregateFileProfiles("[profile in valid]\n" + "name = value\n", "[in valid 2]\n" + "name2 = value2")) .isEqualTo(profiles()); } | public Map<String, Profile> profiles() { return profiles; } | ProfileFile { public Map<String, Profile> profiles() { return profiles; } } | ProfileFile { public Map<String, Profile> profiles() { return profiles; } private ProfileFile(Map<String, Map<String, String>> rawProfiles); } | 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(); } | 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 configProfilesWithoutPrefixAreIgnored() { assertThat(configFileProfiles("[foo]\n" + "name = value")) .isEqualTo(profiles()); } | public Map<String, Profile> profiles() { return profiles; } | ProfileFile { public Map<String, Profile> profiles() { return profiles; } } | ProfileFile { public Map<String, Profile> profiles() { return profiles; } private ProfileFile(Map<String, Map<String, String>> rawProfiles); } | 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(); } | 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 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())); } | @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 + "'"); } } | 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 + "'"); } } } | 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(); } | 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); } | 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 credentialsProfilesWithPrefixAreIgnored() { assertThat(credentialFileProfiles("[profile foo]\n" + "name = value")) .isEqualTo(profiles()); } | public Map<String, Profile> profiles() { return profiles; } | ProfileFile { public Map<String, Profile> profiles() { return profiles; } } | ProfileFile { public Map<String, Profile> profiles() { return profiles; } private ProfileFile(Map<String, Map<String, String>> rawProfiles); } | 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(); } | 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 loadingDefaultProfileFileWorks() { ProfileFile.defaultProfileFile(); } | public static ProfileFile defaultProfileFile() { return ProfileFile.aggregator() .applyMutation(ProfileFile::addCredentialsFile) .applyMutation(ProfileFile::addConfigFile) .build(); } | ProfileFile { public static ProfileFile defaultProfileFile() { return ProfileFile.aggregator() .applyMutation(ProfileFile::addCredentialsFile) .applyMutation(ProfileFile::addConfigFile) .build(); } } | ProfileFile { public static ProfileFile defaultProfileFile() { return ProfileFile.aggregator() .applyMutation(ProfileFile::addCredentialsFile) .applyMutation(ProfileFile::addConfigFile) .build(); } private ProfileFile(Map<String, Map<String, String>> rawProfiles); } | 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(); } | 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 optionNotSet_returnsGlobalEndpoint() { assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_GLOBAL_ENDPOINT); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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(); } | @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 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 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); } | 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(); } | 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 lastProviderInChainGivesRegionInformation() { final Region expectedRegion = Region.of("some-region-string"); AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new NeverAwsRegionProvider(), new StaticAwsRegionProvider( expectedRegion)); assertEquals(expectedRegion, chain.getRegion()); } | @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 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 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); } | 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(); } | 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 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())); } | @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 + "'"); } } | 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 + "'"); } } } | 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(); } | 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); } | 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 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()); } | @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 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 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); } | 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(); } | 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(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()); } | @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 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 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); } | 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(); } | 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 (expected = SdkClientException.class) public void noProviderGivesRegion_ThrowsException() { AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new NeverAwsRegionProvider(), new NeverAwsRegionProvider()); chain.getRegion(); } | @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 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 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); } | 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(); } | 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 getRegionInvokesSupplierExactlyOnce() { LazyAwsRegionProvider lazyRegionProvider = new LazyAwsRegionProvider(regionProviderConstructor); lazyRegionProvider.getRegion(); lazyRegionProvider.getRegion(); Mockito.verify(regionProviderConstructor, Mockito.times(1)).get(); Mockito.verify(regionProvider, Mockito.times(2)).getRegion(); } | @Override public Region getRegion() { return delegate.getValue().getRegion(); } | LazyAwsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() { return delegate.getValue().getRegion(); } } | LazyAwsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() { return delegate.getValue().getRegion(); } LazyAwsRegionProvider(Supplier<AwsRegionProvider> delegateConstructor); } | LazyAwsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() { return delegate.getValue().getRegion(); } LazyAwsRegionProvider(Supplier<AwsRegionProvider> delegateConstructor); @Override Region getRegion(); @Override String toString(); } | LazyAwsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() { return delegate.getValue().getRegion(); } LazyAwsRegionProvider(Supplier<AwsRegionProvider> delegateConstructor); @Override Region getRegion(); @Override String toString(); } |
@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"); } | @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 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 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); } | 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(); } | 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 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")); } | @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 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 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); } | 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(); } | 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 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"))); } | 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; } } | 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; } } } | 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(); } | 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(); } | 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 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"))); } | public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } private EC2MetadataUtils(); } | 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(); } | 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_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)); } | public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } private EC2MetadataUtils(); } | 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(); } | 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_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)); } | public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } private EC2MetadataUtils(); } | 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(); } | 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 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())); } | @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 + "'"); } } | 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 + "'"); } } } | 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(); } | 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); } | 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 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)); } | public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } private EC2MetadataUtils(); } | 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(); } | 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_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)); } | public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } private EC2MetadataUtils(); } | 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(); } | 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_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(); } | public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } } | EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } private EC2MetadataUtils(); } | 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(); } | 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 testMetricValues_noValues_returnsEmptyList() { DefaultMetricCollection foo = new DefaultMetricCollection("foo", Collections.emptyMap(), Collections.emptyList()); assertThat(foo.metricValues(M1)).isEmpty(); } | @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 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 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); } | 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(); } | 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 testChildren_noChildren_returnsEmptyList() { DefaultMetricCollection foo = new DefaultMetricCollection("foo", Collections.emptyMap(), Collections.emptyList()); assertThat(foo.children()).isEmpty(); } | @Override public List<MetricCollection> children() { return children; } | DefaultMetricCollection implements MetricCollection { @Override public List<MetricCollection> children() { return children; } } | DefaultMetricCollection implements MetricCollection { @Override public List<MetricCollection> children() { return children; } DefaultMetricCollection(String name, Map<SdkMetric<?>,
List<MetricRecord<?>>> metrics, List<MetricCollection> children); } | 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(); } | 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 testOf_variadicOverload_c1Null_throws() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("must not contain null elements"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, (MetricCategory) null); } | 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); } | 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); } } | 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); } | 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); } | 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_c1NotNull_cnNull_doesNotThrow() { SdkMetric.create("event", Integer.class, MetricLevel.INFO, MetricCategory.CORE, null); } | 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); } | 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); } } | 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); } | 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); } | 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_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 }); } | 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); } | 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); } } | 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); } | 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); } | 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_setOverload_null_throws() { thrown.expect(NullPointerException.class); thrown.expectMessage("object is null"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, (Set<MetricCategory>) null); } | 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); } | 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); } } | 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); } | 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); } | 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_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())); } | 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); } | 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); } } | 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); } | 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); } | 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 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()); } | @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 + "'"); } } | 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 + "'"); } } } | 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(); } | 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); } | 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); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.