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 testOf_namePreviouslyUsed_throws() { String fooName = "metricEvent"; thrown.expect(IllegalArgumentException.class); thrown.expectMessage(fooName + " has already been created"); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); } | 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_namePreviouslyUsed_differentArgs_throws() { String fooName = "metricEvent"; thrown.expect(IllegalArgumentException.class); thrown.expectMessage(fooName + " has already been created"); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); SdkMetric.create(fooName, Long.class, MetricLevel.INFO, MetricCategory.HTTP_CLIENT); } | 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(expected = RuntimeException.class) public void nullCredentials_ThrowsIllegalArgumentException() { StaticCredentialsProvider.create(null); } | public static StaticCredentialsProvider create(AwsCredentials credentials) { return new StaticCredentialsProvider(credentials); } | StaticCredentialsProvider implements AwsCredentialsProvider { public static StaticCredentialsProvider create(AwsCredentials credentials) { return new StaticCredentialsProvider(credentials); } } | StaticCredentialsProvider implements AwsCredentialsProvider { public static StaticCredentialsProvider create(AwsCredentials credentials) { return new StaticCredentialsProvider(credentials); } private StaticCredentialsProvider(AwsCredentials credentials); } | StaticCredentialsProvider implements AwsCredentialsProvider { public static StaticCredentialsProvider create(AwsCredentials credentials) { return new StaticCredentialsProvider(credentials); } private StaticCredentialsProvider(AwsCredentials credentials); static StaticCredentialsProvider create(AwsCredentials credentials); @Override AwsCredentials resolveCredentials(); @Override String toString(); } | StaticCredentialsProvider implements AwsCredentialsProvider { public static StaticCredentialsProvider create(AwsCredentials credentials) { return new StaticCredentialsProvider(credentials); } private StaticCredentialsProvider(AwsCredentials credentials); static StaticCredentialsProvider create(AwsCredentials credentials); @Override AwsCredentials resolveCredentials(); @Override String toString(); } |
@Test public void resolveCredentials_metadataLookupDisabled_throws() { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property(), "true"); thrown.expect(SdkClientException.class); thrown.expectMessage("Loading credentials from local endpoint is disabled"); try { InstanceProfileCredentialsProvider.builder().build().resolveCredentials(); } finally { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property()); } } | public static Builder builder() { return new BuilderImpl(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } |
@Test public void resolveCredentials_requestsIncludeUserAgent() { String stubToken = "some-token"; stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); String userAgentHeader = "User-Agent"; String userAgent = UserAgentUtils.getUserAgent(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(userAgentHeader, equalTo(userAgent))); } | public static Builder builder() { return new BuilderImpl(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } |
@Test public void resolveCredentials_queriesTokenResource() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); } | public static Builder builder() { return new BuilderImpl(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } |
@Test public void resolveCredentials_queriesTokenResource_includedInCredentialsRequests() { String stubToken = "some-token"; stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(TOKEN_HEADER, equalTo(stubToken))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(TOKEN_HEADER, equalTo(stubToken))); } | public static Builder builder() { return new BuilderImpl(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } |
@Test public void resolveCredentials_queriesTokenResource_403Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(403).withBody("oops"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); } | public static Builder builder() { return new BuilderImpl(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } |
@Test public void resolveCredentials_queriesTokenResource_404Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(404).withBody("oops"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); } | public static Builder builder() { return new BuilderImpl(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } |
@Test public void resolveCredentials_queriesTokenResource_405Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(405).withBody("oops"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); } | public static Builder builder() { return new BuilderImpl(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } |
@Test public void parseArn_bucket_noName() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("bucket_name:") .build()); } | @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 equalsAndHashCode_differentProperty_httpRequest() throws URISyntaxException { SdkHttpRequest otherHttpRequest = mock(SdkHttpRequest.class); when(otherHttpRequest.getUri()).thenReturn(FAKE_URL.toURI()); PresignedGetObjectRequest request = generateMaximal(); PresignedGetObjectRequest otherRequest = request.toBuilder().httpRequest(otherHttpRequest).build(); assertThat(request).isNotEqualTo(otherRequest); assertThat(request.hashCode()).isNotEqualTo(otherRequest.hashCode()); } | @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 resolveCredentials_queriesTokenResource_400Error_throws() { thrown.expect(SdkClientException.class); thrown.expectMessage("token"); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(400).withBody("oops"))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); } | public static Builder builder() { return new BuilderImpl(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } |
@Test public void resolveCredentials_queriesTokenResource_socketTimeout_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token").withFixedDelay(Integer.MAX_VALUE))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); } | public static Builder builder() { return new BuilderImpl(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } |
@Test public void resolveCredentials_endpointSettingEmpty_throws() { thrown.expect(SdkClientException.class); System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), ""); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); } | public static Builder builder() { return new BuilderImpl(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } |
@Test public void resolveCredentials_endpointSettingHostNotExists_throws() { thrown.expect(SdkClientException.class); System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "some-host-that-does-not-exist"); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); } | public static Builder builder() { return new BuilderImpl(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } |
@Test(expected = SdkClientException.class) public void testEnvVariableNotSet() { helper.remove(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); ContainerCredentialsProvider.builder() .build() .resolveCredentials(); } | public static Builder builder() { return new BuilderImpl(); } | ContainerCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } } | ContainerCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private ContainerCredentialsProvider(BuilderImpl builder); } | ContainerCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private ContainerCredentialsProvider(BuilderImpl builder); static Builder builder(); @Override String toString(); } | ContainerCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private ContainerCredentialsProvider(BuilderImpl builder); static Builder builder(); @Override String toString(); } |
@Test public void testLoadCredentialsParsesJsonResponseProperly() { stubForSuccessResponseWithCustomBody(successResponse); HttpCredentialsProvider credentialsProvider = testCredentialsProvider(); AwsSessionCredentials credentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials(); assertThat(credentials.accessKeyId()).isEqualTo("ACCESS_KEY_ID"); assertThat(credentials.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY"); assertThat(credentials.sessionToken()).isEqualTo("TOKEN_TOKEN_TOKEN"); } | @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } protected HttpCredentialsProvider(BuilderImpl<?, ?> builder); HttpCredentialsProvider(boolean asyncCredentialUpdateEnabled, String asyncThreadName); } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } protected HttpCredentialsProvider(BuilderImpl<?, ?> builder); HttpCredentialsProvider(boolean asyncCredentialUpdateEnabled, String asyncThreadName); @Override AwsCredentials resolveCredentials(); @Override void close(); } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } protected HttpCredentialsProvider(BuilderImpl<?, ?> builder); HttpCredentialsProvider(boolean asyncCredentialUpdateEnabled, String asyncThreadName); @Override AwsCredentials resolveCredentials(); @Override void close(); } |
@Test public void testNoMetadataService() throws Exception { stubForErrorResponse(); HttpCredentialsProvider credentialsProvider = testCredentialsProvider(); assertThatExceptionOfType(SdkClientException.class).isThrownBy(credentialsProvider::resolveCredentials); stubForSuccessResonseWithCustomExpirationDate(new Date(System.currentTimeMillis() + ONE_MINUTE * 4)); credentialsProvider.resolveCredentials(); stubForErrorResponse(); assertThatExceptionOfType(SdkClientException.class).isThrownBy(credentialsProvider::resolveCredentials); } | @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } protected HttpCredentialsProvider(BuilderImpl<?, ?> builder); HttpCredentialsProvider(boolean asyncCredentialUpdateEnabled, String asyncThreadName); } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } protected HttpCredentialsProvider(BuilderImpl<?, ?> builder); HttpCredentialsProvider(boolean asyncCredentialUpdateEnabled, String asyncThreadName); @Override AwsCredentials resolveCredentials(); @Override void close(); } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } protected HttpCredentialsProvider(BuilderImpl<?, ?> builder); HttpCredentialsProvider(boolean asyncCredentialUpdateEnabled, String asyncThreadName); @Override AwsCredentials resolveCredentials(); @Override void close(); } |
@Test public void basicCachingFunctionalityWorks() { HttpCredentialsProvider credentialsProvider = testCredentialsProvider(); stubForSuccessResonseWithCustomExpirationDate(Date.from(Instant.now().plus(Duration.ofDays(10)))); assertThat(credentialsProvider.resolveCredentials()).isNotNull(); stubForErrorResponse(); assertThat(credentialsProvider.resolveCredentials()).isNotNull(); } | @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } protected HttpCredentialsProvider(BuilderImpl<?, ?> builder); HttpCredentialsProvider(boolean asyncCredentialUpdateEnabled, String asyncThreadName); } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } protected HttpCredentialsProvider(BuilderImpl<?, ?> builder); HttpCredentialsProvider(boolean asyncCredentialUpdateEnabled, String asyncThreadName); @Override AwsCredentials resolveCredentials(); @Override void close(); } | HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } protected HttpCredentialsProvider(BuilderImpl<?, ?> builder); HttpCredentialsProvider(boolean asyncCredentialUpdateEnabled, String asyncThreadName); @Override AwsCredentials resolveCredentials(); @Override void close(); } |
@Test public void creationDoesntInvokeSupplier() { LazyAwsCredentialsProvider.create(credentialsConstructor); Mockito.verifyZeroInteractions(credentialsConstructor); } | public static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor) { return new LazyAwsCredentialsProvider(delegateConstructor); } | LazyAwsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor) { return new LazyAwsCredentialsProvider(delegateConstructor); } } | LazyAwsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor) { return new LazyAwsCredentialsProvider(delegateConstructor); } private LazyAwsCredentialsProvider(Supplier<AwsCredentialsProvider> delegateConstructor); } | LazyAwsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor) { return new LazyAwsCredentialsProvider(delegateConstructor); } private LazyAwsCredentialsProvider(Supplier<AwsCredentialsProvider> delegateConstructor); static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor); @Override AwsCredentials resolveCredentials(); @Override void close(); @Override String toString(); } | LazyAwsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor) { return new LazyAwsCredentialsProvider(delegateConstructor); } private LazyAwsCredentialsProvider(Supplier<AwsCredentialsProvider> delegateConstructor); static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor); @Override AwsCredentials resolveCredentials(); @Override void close(); @Override String toString(); } |
@Test public void profileFileWithStaticCredentialsLoadsCorrectly() { ProfileFile profileFile = allTypesProfile(); assertThat(profileFile.profile("default")).hasValueSatisfying(profile -> { assertThat(profile.name()).isEqualTo("default"); assertThat(profile.property(ProfileProperty.AWS_ACCESS_KEY_ID)).hasValue("defaultAccessKey"); assertThat(profile.toString()).contains("default"); assertThat(profile.property(ProfileProperty.REGION)).isNotPresent(); assertThat(new ProfileCredentialsUtils(profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> { assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); }); }); }); } | public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } |
@Test public void parseArn_accesspoint_noName() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("access_point:") .build()); } | @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 profileFileWithSessionCredentialsLoadsCorrectly() { ProfileFile profileFile = allTypesProfile(); assertThat(profileFile.profile("profile-with-session-token")).hasValueSatisfying(profile -> { assertThat(profile.property(ProfileProperty.REGION)).isNotPresent(); assertThat(new ProfileCredentialsUtils(profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> { assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials).isInstanceOf(AwsSessionCredentials.class); assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); Assertions.assertThat(((AwsSessionCredentials) credentials).sessionToken()).isEqualTo("awsSessionToken"); }); }); }); } | public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } |
@Test public void profileFileWithProcessCredentialsLoadsCorrectly() { ProfileFile profileFile = allTypesProfile(); assertThat(profileFile.profile("profile-credential-process")).hasValueSatisfying(profile -> { assertThat(profile.property(ProfileProperty.REGION)).isNotPresent(); assertThat(new ProfileCredentialsUtils(profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> { assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials).isInstanceOf(AwsBasicCredentials.class); assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); }); }); }); } | public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } |
@Test public void profileFileWithCircularDependencyThrowsExceptionWhenResolvingCredentials() { ProfileFile configFile = configFile("[profile source]\n" + "aws_access_key_id=defaultAccessKey\n" + "aws_secret_access_key=defaultSecretAccessKey\n" + "\n" + "[profile test]\n" + "source_profile=test3\n" + "role_arn=arn:aws:iam::123456789012:role/testRole\n" + "\n" + "[profile test2]\n" + "source_profile=test\n" + "role_arn=arn:aws:iam::123456789012:role/testRole2\n" + "\n" + "[profile test3]\n" + "source_profile=test2\n" + "role_arn=arn:aws:iam::123456789012:role/testRole3"); Assertions.assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile.profile("test").get(), configFile::profile) .credentialsProvider()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Invalid profile file: Circular relationship detected with profiles"); } | public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } |
@Test public void profileWithBothCredentialSourceAndSourceProfileThrowsException() { ProfileFile configFile = configFile("[profile test]\n" + "source_profile=source\n" + "credential_source=Environment\n" + "role_arn=arn:aws:iam::123456789012:role/testRole3\n" + "\n" + "[profile source]\n" + "aws_access_key_id=defaultAccessKey\n" + "aws_secret_access_key=defaultSecretAccessKey"); Assertions.assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile.profile("test").get(), configFile::profile) .credentialsProvider()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Invalid profile file: profile has both source_profile and credential_source."); } | public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } |
@Test public void profileWithInvalidCredentialSourceThrowsException() { ProfileFile configFile = configFile("[profile test]\n" + "credential_source=foobar\n" + "role_arn=arn:aws:iam::123456789012:role/testRole3"); Assertions.assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile.profile("test").get(), configFile::profile) .credentialsProvider()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("foobar is not a valid credential_source"); } | public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } | ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } |
@Test public void missingProfileFileThrowsExceptionInGetCredentials() { ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } | public static Builder builder() { return new BuilderImpl(); } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); static ProfileCredentialsProvider create(); static ProfileCredentialsProvider create(String profileName); static Builder builder(); @Override AwsCredentials resolveCredentials(); @Override String toString(); @Override void close(); } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); static ProfileCredentialsProvider create(); static ProfileCredentialsProvider create(String profileName); static Builder builder(); @Override AwsCredentials resolveCredentials(); @Override String toString(); @Override void close(); } |
@Test public void missingProfileThrowsExceptionInGetCredentials() { ProfileFile file = profileFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder().profileFile(file).profileName("foo").build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } | public static Builder builder() { return new BuilderImpl(); } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); static ProfileCredentialsProvider create(); static ProfileCredentialsProvider create(String profileName); static Builder builder(); @Override AwsCredentials resolveCredentials(); @Override String toString(); @Override void close(); } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); static ProfileCredentialsProvider create(); static ProfileCredentialsProvider create(String profileName); static Builder builder(); @Override AwsCredentials resolveCredentials(); @Override String toString(); @Override void close(); } |
@Test public void profileWithoutCredentialsThrowsExceptionInGetCredentials() { ProfileFile file = profileFile("[default]"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder().profileFile(file).profileName("default").build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } | public static Builder builder() { return new BuilderImpl(); } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); static ProfileCredentialsProvider create(); static ProfileCredentialsProvider create(String profileName); static Builder builder(); @Override AwsCredentials resolveCredentials(); @Override String toString(); @Override void close(); } | ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); static ProfileCredentialsProvider create(); static ProfileCredentialsProvider create(String profileName); static Builder builder(); @Override AwsCredentials resolveCredentials(); @Override String toString(); @Override void close(); } |
@Test public void testSigning() throws Exception { final String expectedAuthorizationHeaderWithoutSha256Header = "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=77fe7c02927966018667f21d1dc3dfad9057e58401cbb9ed64f1b7868288e35a"; final String expectedAuthorizationHeaderWithSha256Header = "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date;x-amz-sha256, " + "Signature=e73e20539446307a5dc71252dbd5b97e861f1d1267456abda3ebd8d57e519951"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); SdkHttpFullRequest.Builder request = generateBasicRequest(); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")) .hasValue(expectedAuthorizationHeaderWithoutSha256Header); request = generateBasicRequest(); request.putHeader("x-amz-sha256", "required"); signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorizationHeaderWithSha256Header); } | public static Aws4Signer create() { return new Aws4Signer(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } |
@Test public void queryParamsWithNullValuesAreStillSignedWithTrailingEquals() throws Exception { final String expectedAuthorizationHeaderWithoutSha256Header = "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=c45a3ff1f028e83017f3812c06b4440f0b3240264258f6e18cd683b816990ba4"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); SdkHttpFullRequest.Builder request = generateBasicRequest().putRawQueryParameter("Foo", (String) null); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")) .hasValue(expectedAuthorizationHeaderWithoutSha256Header); } | public static Aws4Signer create() { return new Aws4Signer(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } |
@Test public void parseArn_object_v2Arn_noKey() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("object:bucket") .build()); } | @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 testPresigning() throws Exception { final String expectedAmzSignature = "bf7ae1c2f266d347e290a2aee7b126d38b8a695149d003b9fab2ed1eb6d6ebda"; final String expectedAmzCredentials = "access/19810216/us-east-1/demo/aws4_request"; final String expectedAmzHeader = "19810216T063000Z"; final String expectedAmzExpires = "604800"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); SdkHttpFullRequest request = generateBasicRequest().build(); SdkHttpFullRequest signed = SignerTestUtils.presignRequest(signer, request, credentials, null, "demo", signingOverrideClock, "us-east-1"); assertEquals(expectedAmzSignature, signed.rawQueryParameters().get("X-Amz-Signature").get(0)); assertEquals(expectedAmzCredentials, signed.rawQueryParameters().get("X-Amz-Credential").get(0)); assertEquals(expectedAmzHeader, signed.rawQueryParameters().get("X-Amz-Date").get(0)); assertEquals(expectedAmzExpires, signed.rawQueryParameters().get("X-Amz-Expires").get(0)); } | public static Aws4Signer create() { return new Aws4Signer(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } |
@Test public void testAnonymous() throws Exception { AwsCredentials credentials = AnonymousCredentialsProvider.create().resolveCredentials(); SdkHttpFullRequest request = generateBasicRequest().build(); SignerTestUtils.signRequest(signer, request, credentials, "demo", signingOverrideClock, "us-east-1"); assertNull(request.headers().get("Authorization")); } | public static Aws4Signer create() { return new Aws4Signer(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } |
@Test public void xAmznTraceId_NotSigned() throws Exception { AwsBasicCredentials credentials = AwsBasicCredentials.create("akid", "skid"); SdkHttpFullRequest.Builder request = generateBasicRequest(); request.putHeader("X-Amzn-Trace-Id", " Root=1-584b150a-708479cb060007ffbf3ee1da;Parent=36d3dbcfd150aac9;Sampled=1"); SdkHttpFullRequest actual = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(actual.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=581d0042389009a28d461124138f1fe8eeb8daed87611d2a2b47fd3d68d81d73"); } | public static Aws4Signer create() { return new Aws4Signer(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } | Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } |
@Test public void openStreamEventSignaturesCanRollOverBetweenDays() { EventStreamAws4Signer signer = EventStreamAws4Signer.create(); Region region = Region.US_WEST_2; AwsCredentials credentials = AwsBasicCredentials.create("a", "s"); String signingName = "name"; AdjustableClock clock = new AdjustableClock(); clock.time = Instant.parse("2020-01-01T23:59:59Z"); SdkHttpFullRequest initialRequest = SdkHttpFullRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.GET) .build(); SdkHttpFullRequest signedRequest = SignerTestUtils.signRequest(signer, initialRequest, credentials, signingName, clock, region.id()); ByteBuffer event = new Message(Collections.emptyMap(), "foo".getBytes(UTF_8)).toByteBuffer(); Callable<ByteBuffer> lastEvent = () -> { clock.time = Instant.parse("2020-01-02T00:00:00Z"); return event; }; AsyncRequestBody requestBody = AsyncRequestBody.fromPublisher(Flowable.concatArray(Flowable.just(event), Flowable.fromCallable(lastEvent))); AsyncRequestBody signedBody = SignerTestUtils.signAsyncRequest(signer, signedRequest, requestBody, credentials, signingName, clock, region.id()); List<Message> signedMessages = readMessages(signedBody); assertThat(signedMessages.size()).isEqualTo(3); Map<String, HeaderValue> firstMessageHeaders = signedMessages.get(0).getHeaders(); assertThat(firstMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-01T23:59:59Z"); assertThat(Base64.getEncoder().encodeToString(firstMessageHeaders.get(":chunk-signature").getByteArray())) .isEqualTo("EFt7ZU043r/TJE8U+1GxJXscmNxoqmIdGtUIl8wE9u0="); Map<String, HeaderValue> lastMessageHeaders = signedMessages.get(2).getHeaders(); assertThat(lastMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-02T00:00:00Z"); assertThat(Base64.getEncoder().encodeToString(lastMessageHeaders.get(":chunk-signature").getByteArray())) .isEqualTo("UTRGo0D7BQytiVkH1VofR/8f3uFsM4V5QR1A8grr1+M="); } | public static EventStreamAws4Signer create() { return new EventStreamAws4Signer(); } | EventStreamAws4Signer extends BaseEventStreamAsyncAws4Signer { public static EventStreamAws4Signer create() { return new EventStreamAws4Signer(); } } | EventStreamAws4Signer extends BaseEventStreamAsyncAws4Signer { public static EventStreamAws4Signer create() { return new EventStreamAws4Signer(); } private EventStreamAws4Signer(); } | EventStreamAws4Signer extends BaseEventStreamAsyncAws4Signer { public static EventStreamAws4Signer create() { return new EventStreamAws4Signer(); } private EventStreamAws4Signer(); static EventStreamAws4Signer create(); } | EventStreamAws4Signer extends BaseEventStreamAsyncAws4Signer { public static EventStreamAws4Signer create() { return new EventStreamAws4Signer(); } private EventStreamAws4Signer(); static EventStreamAws4Signer create(); } |
@Test public void toDebugString_emptyPayload_generatesCorrectString() { Message m = new Message(headers, new byte[0]); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=}"); } | static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); static final String EVENT_STREAM_SIGNATURE; static final String EVENT_STREAM_DATE; } |
@Test public void toDebugString_noHeaders_emptyPayload_generatesCorrectString() { Message m = new Message(new LinkedHashMap<>(), new byte[0]); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={}, payload=}"); } | static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); static final String EVENT_STREAM_SIGNATURE; static final String EVENT_STREAM_DATE; } |
@Test public void toDebugString_largePayload_truncate_generatesCorrectString() { byte[] payload = new byte[128]; new Random().nextBytes(payload); Message m = new Message(headers, payload); byte[] first32 = Arrays.copyOf(payload, 32); String expectedPayloadString = BinaryUtils.toHex(first32); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, true)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "...}"); } | static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); static final String EVENT_STREAM_SIGNATURE; static final String EVENT_STREAM_DATE; } |
@Test public void toDebugString_largePayload_noTruncate_generatesCorrectString() { byte[] payload = new byte[128]; new Random().nextBytes(payload); Message m = new Message(headers, payload); String expectedPayloadString = BinaryUtils.toHex(payload); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "}"); } | static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); static final String EVENT_STREAM_SIGNATURE; static final String EVENT_STREAM_DATE; } |
@Test public void toDebugString_smallPayload_truncate_doesNotAddEllipsis() { byte[] payload = new byte[8]; new Random().nextBytes(payload); Message m = new Message(headers, payload); String expectedPayloadString = BinaryUtils.toHex(payload); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, true)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "}"); } | static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); } | BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); static final String EVENT_STREAM_SIGNATURE; static final String EVENT_STREAM_DATE; } |
@Test public void isValidForDate_dayBefore_false() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant dayBefore = Instant.parse("2020-03-02T23:59:59Z"); assertThat(key.isValidForDate(dayBefore)).isFalse(); } | public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); boolean isValidForDate(Instant other); byte[] getSigningKey(); } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); boolean isValidForDate(Instant other); byte[] getSigningKey(); } |
@Test public void parseArn_object_v2Arn_emptyBucket() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("object:/key") .build()); } | @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 isValidForDate_sameDay_true() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant sameDay = Instant.parse("2020-03-03T01:02:03Z"); assertThat(key.isValidForDate(sameDay)).isTrue(); } | public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); boolean isValidForDate(Instant other); byte[] getSigningKey(); } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); boolean isValidForDate(Instant other); byte[] getSigningKey(); } |
@Test public void isValidForDate_dayAfter_false() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant dayAfter = Instant.parse("2020-03-04T00:00:00Z"); assertThat(key.isValidForDate(dayAfter)).isFalse(); } | public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); boolean isValidForDate(Instant other); byte[] getSigningKey(); } | SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); boolean isValidForDate(Instant other); byte[] getSigningKey(); } |
@Test public void toBuilder() { ArnResource oneResource = ArnResource.fromString("bucket:foobar:1"); ArnResource anotherResource = oneResource.toBuilder().build(); assertThat(oneResource).isEqualTo(anotherResource); assertThat(oneResource.hashCode()).isEqualTo(anotherResource.hashCode()); } | @Override public Builder toBuilder() { return builder() .resource(resource) .resourceType(resourceType) .qualifier(qualifier); } | ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { @Override public Builder toBuilder() { return builder() .resource(resource) .resourceType(resourceType) .qualifier(qualifier); } } | ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { @Override public Builder toBuilder() { return builder() .resource(resource) .resourceType(resourceType) .qualifier(qualifier); } private ArnResource(DefaultBuilder builder); } | ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { @Override public Builder toBuilder() { return builder() .resource(resource) .resourceType(resourceType) .qualifier(qualifier); } private ArnResource(DefaultBuilder builder); Optional<String> resourceType(); String resource(); Optional<String> qualifier(); static Builder builder(); static ArnResource fromString(String resource); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { @Override public Builder toBuilder() { return builder() .resource(resource) .resourceType(resourceType) .qualifier(qualifier); } private ArnResource(DefaultBuilder builder); Optional<String> resourceType(); String resource(); Optional<String> qualifier(); static Builder builder(); static ArnResource fromString(String resource); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void arnResource_nullResource_shouldThrowException() { assertThatThrownBy(() -> ArnResource.builder() .build()).hasMessageContaining("resource must not be null."); } | public static Builder builder() { return new DefaultBuilder(); } | ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { public static Builder builder() { return new DefaultBuilder(); } } | ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { public static Builder builder() { return new DefaultBuilder(); } private ArnResource(DefaultBuilder builder); } | ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { public static Builder builder() { return new DefaultBuilder(); } private ArnResource(DefaultBuilder builder); Optional<String> resourceType(); String resource(); Optional<String> qualifier(); static Builder builder(); static ArnResource fromString(String resource); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { public static Builder builder() { return new DefaultBuilder(); } private ArnResource(DefaultBuilder builder); Optional<String> resourceType(); String resource(); Optional<String> qualifier(); static Builder builder(); static ArnResource fromString(String resource); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void toBuilder() { Arn oneArn = Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("bucket:foobar:1") .build(); Arn anotherArn = oneArn.toBuilder().build(); assertThat(oneArn).isEqualTo(anotherArn); assertThat(oneArn.hashCode()).isEqualTo(anotherArn.hashCode()); } | @Override public Builder toBuilder() { return builder().accountId(accountId) .partition(partition) .region(region) .resource(resource) .service(service) ; } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { @Override public Builder toBuilder() { return builder().accountId(accountId) .partition(partition) .region(region) .resource(resource) .service(service) ; } } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { @Override public Builder toBuilder() { return builder().accountId(accountId) .partition(partition) .region(region) .resource(resource) .service(service) ; } private Arn(DefaultBuilder builder); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { @Override public Builder toBuilder() { return builder().accountId(accountId) .partition(partition) .region(region) .resource(resource) .service(service) ; } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { @Override public Builder toBuilder() { return builder().accountId(accountId) .partition(partition) .region(region) .resource(resource) .service(service) ; } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void arnWithoutPartition_ThrowsIllegalArgumentException() { String arnString = "arn::s3:us-east-1:12345678910:myresource"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("artition must not be blank or empty."); } | public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void arnWithoutService_ThrowsIllegalArgumentException() { String arnString = "arn:aws::us-east-1:12345678910:myresource"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("service must not be blank or empty"); } | public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void arnWithoutResource_ThrowsIllegalArgumentException() { String arnString = "arn:aws:s3:us-east-1:12345678910:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); } | public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void invalidArn_ThrowsIllegalArgumentException() { String arnString = "arn:aws:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); } | public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void arnDoesntStartWithArn_ThrowsIllegalArgumentException() { String arnString = "fakearn:aws:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); } | public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void parseArn_object_v2Arn_emptyKey() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("object:bucket/") .build()); } | @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 invalidArnWithoutPartition_ThrowsIllegalArgumentException() { String arnString = "arn:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); } | public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void invalidArnWithoutService_ThrowsIllegalArgumentException() { String arnString = "arn:aws:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); } | public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void invalidArnWithoutRegion_ThrowsIllegalArgumentException() { String arnString = "arn:aws:s3:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); } | public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void invalidArnWithoutAccountId_ThrowsIllegalArgumentException() { String arnString = "arn:aws:s3:us-east-1:"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN"); } | public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } | Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1); if (partitionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS partition specified"); } String partition = arn.substring(arnColonIndex + 1, partitionColonIndex); int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1); if (serviceColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no service specified"); } String service = arn.substring(partitionColonIndex + 1, serviceColonIndex); int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1); if (regionColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified"); } String region = arn.substring(serviceColonIndex + 1, regionColonIndex); int accountColonIndex = arn.indexOf(':', regionColonIndex + 1); if (accountColonIndex < 0) { throw new IllegalArgumentException("Malformed ARN - no AWS account specified"); } String accountId = arn.substring(regionColonIndex + 1, accountColonIndex); String resource = arn.substring(accountColonIndex + 1); if (resource.isEmpty()) { throw new IllegalArgumentException("Malformed ARN - no resource specified"); } return Arn.builder() .partition(partition) .service(service) .region(region) .accountId(accountId) .resource(resource) .build(); } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); } |
@Test public void builder_returnsInstance() { assertThat(Http2Configuration.builder()).isNotNull(); } | public static Builder builder() { return new DefaultBuilder(); } | Http2Configuration implements ToCopyableBuilder<Http2Configuration.Builder, Http2Configuration> { public static Builder builder() { return new DefaultBuilder(); } } | Http2Configuration implements ToCopyableBuilder<Http2Configuration.Builder, Http2Configuration> { public static Builder builder() { return new DefaultBuilder(); } private Http2Configuration(DefaultBuilder builder); } | Http2Configuration implements ToCopyableBuilder<Http2Configuration.Builder, Http2Configuration> { public static Builder builder() { return new DefaultBuilder(); } private Http2Configuration(DefaultBuilder builder); Long maxStreams(); Integer initialWindowSize(); Duration healthCheckPingPeriod(); @Override Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); static Builder builder(); } | Http2Configuration implements ToCopyableBuilder<Http2Configuration.Builder, Http2Configuration> { public static Builder builder() { return new DefaultBuilder(); } private Http2Configuration(DefaultBuilder builder); Long maxStreams(); Integer initialWindowSize(); Duration healthCheckPingPeriod(); @Override Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); static Builder builder(); } |
@Test public void toBuilder_roundTrip_producesExactCopy() { ProxyConfiguration original = allPropertiesSetConfig(); ProxyConfiguration copy = original.toBuilder().build(); assertThat(copy).isEqualTo(original); } | @Override public Builder toBuilder() { return new BuilderImpl(this); } | ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } } | ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } private ProxyConfiguration(BuilderImpl builder); } | ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } private ProxyConfiguration(BuilderImpl builder); String scheme(); String host(); int port(); Set<String> nonProxyHosts(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); static Builder builder(); } | ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } private ProxyConfiguration(BuilderImpl builder); String scheme(); String host(); int port(); Set<String> nonProxyHosts(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); static Builder builder(); } |
@Test public void toBuilderModified_doesNotModifySource() { ProxyConfiguration original = allPropertiesSetConfig(); ProxyConfiguration modified = setAllPropertiesToRandomValues(original.toBuilder()).build(); assertThat(original).isNotEqualTo(modified); } | @Override public Builder toBuilder() { return new BuilderImpl(this); } | ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } } | ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } private ProxyConfiguration(BuilderImpl builder); } | ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } private ProxyConfiguration(BuilderImpl builder); String scheme(); String host(); int port(); Set<String> nonProxyHosts(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); static Builder builder(); } | ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } private ProxyConfiguration(BuilderImpl builder); String scheme(); String host(); int port(); Set<String> nonProxyHosts(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); static Builder builder(); } |
@Test public void surfacesCancelExceptionAsIOException() { FutureCancelledException cancelledException = new FutureCancelledException(1L, new CancellationException()); ArgumentCaptor<Throwable> exceptionCaptor = ArgumentCaptor.forClass(Throwable.class); handler.exceptionCaught(ctx, cancelledException); verify(ctx).fireExceptionCaught(exceptionCaptor.capture()); assertThat(exceptionCaptor.getValue()).isInstanceOf(IOException.class); } | @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } | FutureCancelHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } } | FutureCancelHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } private FutureCancelHandler(); } | FutureCancelHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } private FutureCancelHandler(); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable e); static FutureCancelHandler getInstance(); } | FutureCancelHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } private FutureCancelHandler(); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable e); static FutureCancelHandler getInstance(); } |
@Test public void forwardsExceptionIfNotCancelledException() { ArgumentCaptor<Throwable> exceptionCaptor = ArgumentCaptor.forClass(Throwable.class); Throwable err = new RuntimeException("some other exception"); handler.exceptionCaught(ctx, err); verify(ctx).fireExceptionCaught(exceptionCaptor.capture()); assertThat(exceptionCaptor.getValue()).isEqualTo(err); } | @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } | FutureCancelHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } } | FutureCancelHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } private FutureCancelHandler(); } | FutureCancelHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } private FutureCancelHandler(); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable e); static FutureCancelHandler getInstance(); } | FutureCancelHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } private FutureCancelHandler(); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable e); static FutureCancelHandler getInstance(); } |
@Test public void tunnelAlreadyEstablished_doesNotAddInitHandler() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); when(mockAttr.get()).thenReturn(true); tunnelPool.acquire().awaitUninterruptibly(); verify(mockPipeline, never()).addLast(anyObject()); } | @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } |
@Test public void parseArn_object_v1Arn_emptyKey() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .resource("bucket/") .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); } |
@Test(timeout = 1000) public void tunnelNotEstablished_addsInitHandler() throws InterruptedException { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); when(mockAttr.get()).thenReturn(false); CountDownLatch latch = new CountDownLatch(1); when(mockPipeline.addLast(any(ChannelHandler.class))).thenAnswer(i -> { latch.countDown(); return mockPipeline; }); tunnelPool.acquire(); latch.await(); verify(mockPipeline, times(1)).addLast(any(ProxyTunnelInitHandler.class)); } | @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } |
@Test public void tunnelInitFails_acquireFutureFails() { Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, remoteAddr, initFuture) -> { initFuture.setFailure(new IOException("boom")); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, supplier); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().cause()).hasMessage("boom"); } | @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } |
@Test public void tunnelInitSucceeds_acquireFutureSucceeds() { Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, supplier); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().getNow()).isEqualTo(mockChannel); } | @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } |
@Test public void acquireFromDelegatePoolFails_failsFuture() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); when(delegatePool.acquire(any(Promise.class))).thenReturn(GROUP.next().newFailedFuture(new IOException("boom"))); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().cause()).hasMessage("boom"); } | @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } |
@Test public void sslContextProvided_andProxyUsingHttps_addsSslHandler() { SslHandler mockSslHandler = mock(SslHandler.class); TestSslContext mockSslCtx = new TestSslContext(mockSslHandler); Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx, HTTPS_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, supplier); tunnelPool.acquire().awaitUninterruptibly(); ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class); verify(mockPipeline, times(2)).addLast(handlersCaptor.capture()); assertThat(handlersCaptor.getAllValues().get(0)).isEqualTo(mockSslHandler); } | @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } |
@Test public void sslContextProvided_andProxyNotUsingHttps_doesNotAddSslHandler() { SslHandler mockSslHandler = mock(SslHandler.class); TestSslContext mockSslCtx = new TestSslContext(mockSslHandler); Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, supplier); tunnelPool.acquire().awaitUninterruptibly(); ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class); verify(mockPipeline).addLast(handlersCaptor.capture()); assertThat(handlersCaptor.getAllValues().get(0)).isNotInstanceOf(SslHandler.class); } | @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } |
@Test public void release_releasedToDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); tunnelPool.release(mockChannel); verify(delegatePool).release(eq(mockChannel), any(Promise.class)); } | @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } |
@Test public void release_withGivenPromise_releasedToDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); Promise mockPromise = mock(Promise.class); tunnelPool.release(mockChannel, mockPromise); verify(delegatePool).release(eq(mockChannel), eq(mockPromise)); } | @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } |
@Test public void close_closesDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); tunnelPool.close(); verify(delegatePool).close(); } | @Override public void close() { delegate.close(); } | Http1TunnelConnectionPool implements ChannelPool { @Override public void close() { delegate.close(); } } | Http1TunnelConnectionPool implements ChannelPool { @Override public void close() { delegate.close(); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); } | Http1TunnelConnectionPool implements ChannelPool { @Override public void close() { delegate.close(); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } | Http1TunnelConnectionPool implements ChannelPool { @Override public void close() { delegate.close(); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); } |
@Test public void cancelExecuteFuture_channelNotAcquired_failsAcquirePromise() { ArgumentCaptor<Promise> acquireCaptor = ArgumentCaptor.forClass(Promise.class); when(mockChannelPool.acquire(acquireCaptor.capture())).thenAnswer((Answer<Promise>) invocationOnMock -> { return invocationOnMock.getArgumentAt(0, Promise.class); }); CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute(); executeFuture.cancel(true); assertThat(acquireCaptor.getValue().isDone()).isTrue(); assertThat(acquireCaptor.getValue().isSuccess()).isFalse(); } | @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } | NettyRequestExecutor { @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } } | NettyRequestExecutor { @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } NettyRequestExecutor(RequestContext context); } | NettyRequestExecutor { @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } NettyRequestExecutor(RequestContext context); @SuppressWarnings("unchecked") CompletableFuture<Void> execute(); } | NettyRequestExecutor { @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } NettyRequestExecutor(RequestContext context); @SuppressWarnings("unchecked") CompletableFuture<Void> execute(); } |
@Test public void parseArn_object_v1Arn_emptyBucket() { exception.expect(IllegalArgumentException.class); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .resource("/key") .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); } |
@Test public void cancelExecuteFuture_channelAcquired_submitsRunnable() { EventLoop mockEventLoop = mock(EventLoop.class); Channel mockChannel = mock(Channel.class); when(mockChannel.eventLoop()).thenReturn(mockEventLoop); when(mockChannelPool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> { Promise p = invocationOnMock.getArgumentAt(0, Promise.class); p.setSuccess(mockChannel); return p; }); CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute(); executeFuture.cancel(true); verify(mockEventLoop).submit(any(Runnable.class)); } | @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } | NettyRequestExecutor { @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } } | NettyRequestExecutor { @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } NettyRequestExecutor(RequestContext context); } | NettyRequestExecutor { @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } NettyRequestExecutor(RequestContext context); @SuppressWarnings("unchecked") CompletableFuture<Void> execute(); } | NettyRequestExecutor { @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } NettyRequestExecutor(RequestContext context); @SuppressWarnings("unchecked") CompletableFuture<Void> execute(); } |
@Test public void release_openChannel_handlerShouldBeRemovedFromChannelPool() { assertHandlersNotRemoved(); handlerRemovingChannelPool.release(mockChannel); assertHandlersRemoved(); } | @Override public Future<Void> release(Channel channel) { removePerRequestHandlers(channel); return delegate.release(channel); } | HandlerRemovingChannelPool implements SdkChannelPool { @Override public Future<Void> release(Channel channel) { removePerRequestHandlers(channel); return delegate.release(channel); } } | HandlerRemovingChannelPool implements SdkChannelPool { @Override public Future<Void> release(Channel channel) { removePerRequestHandlers(channel); return delegate.release(channel); } HandlerRemovingChannelPool(SdkChannelPool delegate); } | HandlerRemovingChannelPool implements SdkChannelPool { @Override public Future<Void> release(Channel channel) { removePerRequestHandlers(channel); return delegate.release(channel); } HandlerRemovingChannelPool(SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } | HandlerRemovingChannelPool implements SdkChannelPool { @Override public Future<Void> release(Channel channel) { removePerRequestHandlers(channel); return delegate.release(channel); } HandlerRemovingChannelPool(SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } |
@Test public void release_deregisteredOpenChannel_handlerShouldBeRemovedFromChannelPool() { mockChannel.deregister().awaitUninterruptibly(); assertHandlersNotRemoved(); handlerRemovingChannelPool.release(mockChannel); assertHandlersRemoved(); } | @Override public Future<Void> release(Channel channel) { removePerRequestHandlers(channel); return delegate.release(channel); } | HandlerRemovingChannelPool implements SdkChannelPool { @Override public Future<Void> release(Channel channel) { removePerRequestHandlers(channel); return delegate.release(channel); } } | HandlerRemovingChannelPool implements SdkChannelPool { @Override public Future<Void> release(Channel channel) { removePerRequestHandlers(channel); return delegate.release(channel); } HandlerRemovingChannelPool(SdkChannelPool delegate); } | HandlerRemovingChannelPool implements SdkChannelPool { @Override public Future<Void> release(Channel channel) { removePerRequestHandlers(channel); return delegate.release(channel); } HandlerRemovingChannelPool(SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } | HandlerRemovingChannelPool implements SdkChannelPool { @Override public Future<Void> release(Channel channel) { removePerRequestHandlers(channel); return delegate.release(channel); } HandlerRemovingChannelPool(SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } |
@Test @SuppressWarnings("unchecked") public void inUseChannelsAreFlaggedToBeClosed() throws Exception { MockChannel channel = new MockChannel(); channel.attr(ChannelAttributeKey.IN_USE).set(true); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(ctx.channel()).thenReturn(channel); new OldConnectionReaperHandler(1).handlerAdded(ctx); channel.runAllPendingTasks(); Mockito.verify(ctx, new Times(0)).close(); Mockito.verify(ctx, new Times(0)).close(any()); assertThat(channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).get()).isTrue(); } | @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { initialize(ctx); super.handlerAdded(ctx); } | OldConnectionReaperHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { initialize(ctx); super.handlerAdded(ctx); } } | OldConnectionReaperHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { initialize(ctx); super.handlerAdded(ctx); } OldConnectionReaperHandler(int connectionTtlMillis); } | OldConnectionReaperHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { initialize(ctx); super.handlerAdded(ctx); } OldConnectionReaperHandler(int connectionTtlMillis); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelRegistered(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); } | OldConnectionReaperHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { initialize(ctx); super.handlerAdded(ctx); } OldConnectionReaperHandler(int connectionTtlMillis); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelRegistered(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); } |
@Test public void notInUseChannelsAreClosed() throws Exception { MockChannel channel = new MockChannel(); channel.attr(ChannelAttributeKey.IN_USE).set(false); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(ctx.channel()).thenReturn(channel); new OldConnectionReaperHandler(1).handlerAdded(ctx); channel.runAllPendingTasks(); Mockito.verify(ctx, new Times(1)).close(); Mockito.verify(ctx, new Times(0)).close(any()); } | @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { initialize(ctx); super.handlerAdded(ctx); } | OldConnectionReaperHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { initialize(ctx); super.handlerAdded(ctx); } } | OldConnectionReaperHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { initialize(ctx); super.handlerAdded(ctx); } OldConnectionReaperHandler(int connectionTtlMillis); } | OldConnectionReaperHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { initialize(ctx); super.handlerAdded(ctx); } OldConnectionReaperHandler(int connectionTtlMillis); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelRegistered(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); } | OldConnectionReaperHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { initialize(ctx); super.handlerAdded(ctx); } OldConnectionReaperHandler(int connectionTtlMillis); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelRegistered(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); } |
@Test public void acquireCanMakeJustOneCall() throws Exception { stubForIgnoredTimeout(); stubAcquireHealthySequence(true); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(0)); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); } | @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } |
@Test public void acquireCanMakeManyCalls() throws Exception { stubForIgnoredTimeout(); stubAcquireHealthySequence(false, false, false, false, true); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(4)); Mockito.verify(downstreamChannelPool, Mockito.times(5)).acquire(any()); } | @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } |
@Test public void acquireActiveAndKeepAliveTrue_shouldAcquireOnce() throws Exception { stubForIgnoredTimeout(); stubAcquireActiveAndKeepAlive(); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(0)); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); } | @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } |
@Test public void acquire_firstChannelKeepAliveFalse_shouldAcquireAnother() throws Exception { stubForIgnoredTimeout(); stubAcquireTwiceFirstTimeNotKeepAlive(); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(1)); Mockito.verify(downstreamChannelPool, Mockito.times(2)).acquire(any()); } | @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } |
@Test public void badDownstreamAcquiresCausesException() throws Exception { stubForIgnoredTimeout(); stubBadDownstreamAcquire(); Future<Channel> acquire = channelPool.acquire(); try { acquire.get(5, TimeUnit.SECONDS); } catch (ExecutionException e) { } assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isFalse(); assertThat(acquire.cause()).isInstanceOf(IOException.class); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); } | @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } |
@Test public void parseArn_unknownType_throwsCorrectException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("invalidType"); S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("invalidType:something") .build()); } | @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 slowAcquireTimesOut() throws Exception { stubIncompleteDownstreamAcquire(); Mockito.when(eventLoopGroup.schedule(Mockito.any(Runnable.class), Mockito.eq(10), Mockito.eq(TimeUnit.MILLISECONDS))) .thenAnswer(i -> scheduledFuture); Future<Channel> acquire = channelPool.acquire(); ArgumentCaptor<Runnable> timeoutTask = ArgumentCaptor.forClass(Runnable.class); Mockito.verify(eventLoopGroup).schedule(timeoutTask.capture(), anyLong(), any()); timeoutTask.getValue().run(); try { acquire.get(5, TimeUnit.SECONDS); } catch (ExecutionException e) { } assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isFalse(); assertThat(acquire.cause()).isInstanceOf(TimeoutException.class); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); } | @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } | HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); } |
@Test public void channelRead_removesSelf() throws Exception { when(context.pipeline()).thenReturn(channelPipeline); handler.channelRead(context, object); verify(channelPipeline, times(1)).remove(eq(handler)); verify(context, times(1)).fireChannelRead(object); } | @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.pipeline().remove(this); super.channelRead(ctx, msg); } | OneTimeReadTimeoutHandler extends ReadTimeoutHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.pipeline().remove(this); super.channelRead(ctx, msg); } } | OneTimeReadTimeoutHandler extends ReadTimeoutHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.pipeline().remove(this); super.channelRead(ctx, msg); } OneTimeReadTimeoutHandler(Duration timeout); } | OneTimeReadTimeoutHandler extends ReadTimeoutHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.pipeline().remove(this); super.channelRead(ctx, msg); } OneTimeReadTimeoutHandler(Duration timeout); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } | OneTimeReadTimeoutHandler extends ReadTimeoutHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.pipeline().remove(this); super.channelRead(ctx, msg); } OneTimeReadTimeoutHandler(Duration timeout); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } |
@Test public void referenceCountIsInitiallyZero() { assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(0); } | @SdkTestInternalApi static synchronized int referenceCount() { return referenceCount; } | SharedSdkEventLoopGroup { @SdkTestInternalApi static synchronized int referenceCount() { return referenceCount; } } | SharedSdkEventLoopGroup { @SdkTestInternalApi static synchronized int referenceCount() { return referenceCount; } private SharedSdkEventLoopGroup(); } | SharedSdkEventLoopGroup { @SdkTestInternalApi static synchronized int referenceCount() { return referenceCount; } private SharedSdkEventLoopGroup(); @SdkInternalApi static synchronized SdkEventLoopGroup get(); } | SharedSdkEventLoopGroup { @SdkTestInternalApi static synchronized int referenceCount() { return referenceCount; } private SharedSdkEventLoopGroup(); @SdkInternalApi static synchronized SdkEventLoopGroup get(); } |
@Test public void sharedEventLoopGroupIsDeallocatedWhenCountReachesZero() { DelegatingEventLoopGroup group1 = (DelegatingEventLoopGroup) SharedSdkEventLoopGroup.get().eventLoopGroup(); DelegatingEventLoopGroup group2 = (DelegatingEventLoopGroup) SharedSdkEventLoopGroup.get().eventLoopGroup(); assertThat(group1.getDelegate()).isEqualTo(group2.getDelegate()); group1.shutdownGracefully(); group2.shutdownGracefully(); assertThat(group1.getDelegate().isShuttingDown()).isTrue(); } | @SdkInternalApi public static synchronized SdkEventLoopGroup get() { if (sharedSdkEventLoopGroup == null) { sharedSdkEventLoopGroup = SdkEventLoopGroup.builder().build(); } referenceCount++; return SdkEventLoopGroup.create(new ReferenceCountingEventLoopGroup(sharedSdkEventLoopGroup.eventLoopGroup()), sharedSdkEventLoopGroup.channelFactory()); } | SharedSdkEventLoopGroup { @SdkInternalApi public static synchronized SdkEventLoopGroup get() { if (sharedSdkEventLoopGroup == null) { sharedSdkEventLoopGroup = SdkEventLoopGroup.builder().build(); } referenceCount++; return SdkEventLoopGroup.create(new ReferenceCountingEventLoopGroup(sharedSdkEventLoopGroup.eventLoopGroup()), sharedSdkEventLoopGroup.channelFactory()); } } | SharedSdkEventLoopGroup { @SdkInternalApi public static synchronized SdkEventLoopGroup get() { if (sharedSdkEventLoopGroup == null) { sharedSdkEventLoopGroup = SdkEventLoopGroup.builder().build(); } referenceCount++; return SdkEventLoopGroup.create(new ReferenceCountingEventLoopGroup(sharedSdkEventLoopGroup.eventLoopGroup()), sharedSdkEventLoopGroup.channelFactory()); } private SharedSdkEventLoopGroup(); } | SharedSdkEventLoopGroup { @SdkInternalApi public static synchronized SdkEventLoopGroup get() { if (sharedSdkEventLoopGroup == null) { sharedSdkEventLoopGroup = SdkEventLoopGroup.builder().build(); } referenceCount++; return SdkEventLoopGroup.create(new ReferenceCountingEventLoopGroup(sharedSdkEventLoopGroup.eventLoopGroup()), sharedSdkEventLoopGroup.channelFactory()); } private SharedSdkEventLoopGroup(); @SdkInternalApi static synchronized SdkEventLoopGroup get(); } | SharedSdkEventLoopGroup { @SdkInternalApi public static synchronized SdkEventLoopGroup get() { if (sharedSdkEventLoopGroup == null) { sharedSdkEventLoopGroup = SdkEventLoopGroup.builder().build(); } referenceCount++; return SdkEventLoopGroup.create(new ReferenceCountingEventLoopGroup(sharedSdkEventLoopGroup.eventLoopGroup()), sharedSdkEventLoopGroup.channelFactory()); } private SharedSdkEventLoopGroup(); @SdkInternalApi static synchronized SdkEventLoopGroup get(); } |
@Test public void addedToPipeline_addsCodec() { HttpClientCodec codec = new HttpClientCodec(); Supplier<HttpClientCodec> codecSupplier = () -> codec; when(mockCtx.name()).thenReturn("foo"); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, null, codecSupplier); handler.handlerAdded(mockCtx); verify(mockPipeline).addBefore(eq("foo"), eq(null), eq(codec)); } | @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } |
@Test public void unexpectedMessage_failsPromise() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.channelRead(mockCtx, new Object()); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); } | @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); initPromise.setSuccess(ctx.channel()); return; } } ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); initPromise.setSuccess(ctx.channel()); return; } } ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); initPromise.setSuccess(ctx.channel()); return; } } ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); initPromise.setSuccess(ctx.channel()); return; } } ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); initPromise.setSuccess(ctx.channel()); return; } } ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } |
@Test public void unsuccessfulResponse_failsPromise() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); DefaultHttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN); handler.channelRead(mockCtx, resp); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); } | @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); initPromise.setSuccess(ctx.channel()); return; } } ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); initPromise.setSuccess(ctx.channel()); return; } } ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); initPromise.setSuccess(ctx.channel()); return; } } ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); initPromise.setSuccess(ctx.channel()); return; } } ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); initPromise.setSuccess(ctx.channel()); return; } } ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } |
@Test public void requestWriteFails_failsPromise() { DefaultChannelPromise writePromise = new DefaultChannelPromise(mockChannel, GROUP.next()); writePromise.setFailure(new IOException("boom")); when(mockChannel.writeAndFlush(anyObject())).thenReturn(writePromise); Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.handlerAdded(mockCtx); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); } | @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } |
@Test public void handlerRemoved_removesCodec() { HttpClientCodec codec = new HttpClientCodec(); when(mockPipeline.get(eq(HttpClientCodec.class))).thenReturn(codec); Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.handlerRemoved(mockCtx); verify(mockPipeline).remove(eq(HttpClientCodec.class)); } | @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (ctx.pipeline().get(HttpClientCodec.class) != null) { ctx.pipeline().remove(HttpClientCodec.class); } } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (ctx.pipeline().get(HttpClientCodec.class) != null) { ctx.pipeline().remove(HttpClientCodec.class); } } } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (ctx.pipeline().get(HttpClientCodec.class) != null) { ctx.pipeline().remove(HttpClientCodec.class); } } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (ctx.pipeline().get(HttpClientCodec.class) != null) { ctx.pipeline().remove(HttpClientCodec.class); } } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (ctx.pipeline().get(HttpClientCodec.class) != null) { ctx.pipeline().remove(HttpClientCodec.class); } } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } |
@Test public void handledAdded_writesRequest() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.handlerAdded(mockCtx); ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); verify(mockChannel).writeAndFlush(requestCaptor.capture()); String uri = REMOTE_HOST.getHost() + ":" + REMOTE_HOST.getPort(); HttpRequest expectedRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, uri, Unpooled.EMPTY_BUFFER, false); expectedRequest.headers().add(HttpHeaderNames.HOST, uri); assertThat(requestCaptor.getValue()).isEqualTo(expectedRequest); } | @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } | ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise,
Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); } |
@Test public void parseArn_outpostAccessPoint_slash() { S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId(ACCOUNT_ID) .resource("outpost/22222/accesspoint/foobar") .build()); assertThat(resource, instanceOf(S3AccessPointResource.class)); S3AccessPointResource s3AccessPointResource = (S3AccessPointResource) resource; assertThat(s3AccessPointResource.accessPointName(), is("foobar")); assertThat(s3AccessPointResource.parentS3Resource().get(), instanceOf(S3OutpostResource.class)); S3OutpostResource outpostResource = (S3OutpostResource)s3AccessPointResource.parentS3Resource().get(); assertThat(outpostResource.accountId(), is(Optional.of(ACCOUNT_ID))); assertThat(outpostResource.partition(), is(Optional.of("aws"))); assertThat(outpostResource.region(), is(Optional.of("us-east-1"))); assertThat(outpostResource.outpostId(), is("22222")); assertThat(outpostResource.type(), is(S3ResourceType.OUTPOST.toString())); } | @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.