index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/partition-metadata.java
package software.amazon.awssdk.regions.partitionmetadata; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.EndpointTag; import software.amazon.awssdk.regions.PartitionEndpointKey; import software.amazon.awssdk.regions.PartitionMetadata; import software.amazon.awssdk.utils.ImmutableMap; @SdkPublicApi @Generated("software.amazon.awssdk:codegen") public final class AwsPartitionMetadata implements PartitionMetadata { private static final Map<PartitionEndpointKey, String> DNS_SUFFIXES = ImmutableMap.<PartitionEndpointKey, String> builder() .put(PartitionEndpointKey.builder().build(), "amazonaws.com") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("fips")).build(), "amazonaws.com") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "api.aws") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build(), "api.aws").build(); private static final Map<PartitionEndpointKey, String> HOSTNAMES = ImmutableMap .<PartitionEndpointKey, String> builder() .put(PartitionEndpointKey.builder().build(), "{service}.{region}.{dnsSuffix}") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("fips")).build(), "{service}-fips.{region}.{dnsSuffix}") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "{service}-fips.{region}.{dnsSuffix}") .put(PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build(), "{service}.{region}.{dnsSuffix}") .build(); private static final String ID = "aws"; private static final String NAME = "AWS Standard"; private static final String REGION_REGEX = "^(us|eu|ap|sa|ca|me|af)\\-\\w+\\-\\d+$"; @Override public String id() { return ID; } @Override public String name() { return NAME; } @Override public String regionRegex() { return REGION_REGEX; } @Override public String dnsSuffix(PartitionEndpointKey key) { return DNS_SUFFIXES.get(key); } @Override public String hostname(PartitionEndpointKey key) { return HOSTNAMES.get(key); } }
3,100
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/regions.java
package software.amazon.awssdk.regions; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * An Amazon Web Services region that hosts a set of Amazon services. * <p> * An instance of this class can be retrieved by referencing one of the static constants defined in this class (eg. * {@link Region#US_EAST_1}) or by using the {@link Region#of(String)} method if the region you want is not included in * this release of the SDK. * </p> * <p> * Each AWS region corresponds to a separate geographical location where a set of Amazon services is deployed. These * regions (except for the special {@link #AWS_GLOBAL} and {@link #AWS_CN_GLOBAL} regions) are separate from each other, * with their own set of resources. This means a resource created in one region (eg. an SQS queue) is not available in * another region. * </p> * <p> * To programmatically determine whether a particular service is deployed to a region, you can use the * {@code serviceMetadata} method on the service's client interface. Additional metadata about a region can be * discovered using {@link RegionMetadata#of(Region)}. * </p> * <p> * The {@link Region#id()} will be used as the signing region for all requests to AWS services unless an explicit region * override is available in {@link RegionMetadata}. This id will also be used to construct the endpoint for accessing a * service unless an explicit endpoint is available for that region in {@link RegionMetadata}. * </p> */ @SdkPublicApi @Generated("software.amazon.awssdk:codegen") public final class Region { public static final Region AP_SOUTH_1 = Region.of("ap-south-1"); public static final Region EU_SOUTH_1 = Region.of("eu-south-1"); public static final Region US_GOV_EAST_1 = Region.of("us-gov-east-1"); public static final Region CA_CENTRAL_1 = Region.of("ca-central-1"); public static final Region EU_CENTRAL_1 = Region.of("eu-central-1"); public static final Region US_ISO_WEST_1 = Region.of("us-iso-west-1"); public static final Region US_WEST_1 = Region.of("us-west-1"); public static final Region US_WEST_2 = Region.of("us-west-2"); public static final Region AF_SOUTH_1 = Region.of("af-south-1"); public static final Region EU_NORTH_1 = Region.of("eu-north-1"); public static final Region EU_WEST_3 = Region.of("eu-west-3"); public static final Region EU_WEST_2 = Region.of("eu-west-2"); public static final Region EU_WEST_1 = Region.of("eu-west-1"); public static final Region AP_NORTHEAST_3 = Region.of("ap-northeast-3"); public static final Region AP_NORTHEAST_2 = Region.of("ap-northeast-2"); public static final Region AP_NORTHEAST_1 = Region.of("ap-northeast-1"); public static final Region ME_SOUTH_1 = Region.of("me-south-1"); public static final Region SA_EAST_1 = Region.of("sa-east-1"); public static final Region AP_EAST_1 = Region.of("ap-east-1"); public static final Region CN_NORTH_1 = Region.of("cn-north-1"); public static final Region US_GOV_WEST_1 = Region.of("us-gov-west-1"); public static final Region AP_SOUTHEAST_1 = Region.of("ap-southeast-1"); public static final Region AP_SOUTHEAST_2 = Region.of("ap-southeast-2"); public static final Region US_ISO_EAST_1 = Region.of("us-iso-east-1"); public static final Region US_EAST_1 = Region.of("us-east-1"); public static final Region US_EAST_2 = Region.of("us-east-2"); public static final Region CN_NORTHWEST_1 = Region.of("cn-northwest-1"); public static final Region US_ISOB_EAST_1 = Region.of("us-isob-east-1"); public static final Region AWS_GLOBAL = Region.of("aws-global", true); public static final Region AWS_CN_GLOBAL = Region.of("aws-cn-global", true); public static final Region AWS_US_GOV_GLOBAL = Region.of("aws-us-gov-global", true); public static final Region AWS_ISO_GLOBAL = Region.of("aws-iso-global", true); public static final Region AWS_ISO_B_GLOBAL = Region.of("aws-iso-b-global", true); private static final List<Region> REGIONS = Collections.unmodifiableList(Arrays.asList(AP_SOUTH_1, EU_SOUTH_1, US_GOV_EAST_1, CA_CENTRAL_1, EU_CENTRAL_1, US_ISO_WEST_1, US_WEST_1, US_WEST_2, AF_SOUTH_1, EU_NORTH_1, EU_WEST_3, EU_WEST_2, EU_WEST_1, AP_NORTHEAST_3, AP_NORTHEAST_2, AP_NORTHEAST_1, ME_SOUTH_1, SA_EAST_1, AP_EAST_1, CN_NORTH_1, US_GOV_WEST_1, AP_SOUTHEAST_1, AP_SOUTHEAST_2, US_ISO_EAST_1, US_EAST_1, US_EAST_2, CN_NORTHWEST_1, US_ISOB_EAST_1, AWS_GLOBAL, AWS_CN_GLOBAL, AWS_US_GOV_GLOBAL, AWS_ISO_GLOBAL, AWS_ISO_B_GLOBAL)); private final boolean isGlobalRegion; private final String id; private Region(String id, boolean isGlobalRegion) { this.id = id; this.isGlobalRegion = isGlobalRegion; } public static Region of(String value) { return of(value, false); } private static Region of(String value, boolean isGlobalRegion) { Validate.paramNotBlank(value, "region"); String urlEncodedValue = SdkHttpUtils.urlEncode(value); return RegionCache.put(urlEncodedValue, isGlobalRegion); } public static List<Region> regions() { return REGIONS; } public String id() { return this.id; } public RegionMetadata metadata() { return RegionMetadata.of(this); } public boolean isGlobalRegion() { return isGlobalRegion; } @Override public String toString() { return id; } private static class RegionCache { private static final ConcurrentHashMap<String, Region> VALUES = new ConcurrentHashMap<>(); private RegionCache() { } private static Region put(String value, boolean isGlobalRegion) { return VALUES.computeIfAbsent(value, v -> new Region(value, isGlobalRegion)); } } }
3,101
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/region-metadata-provider.java
package software.amazon.awssdk.regions; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.regionmetadata.AfSouth1; import software.amazon.awssdk.regions.regionmetadata.ApEast1; import software.amazon.awssdk.regions.regionmetadata.ApNortheast1; import software.amazon.awssdk.regions.regionmetadata.ApNortheast2; import software.amazon.awssdk.regions.regionmetadata.ApNortheast3; import software.amazon.awssdk.regions.regionmetadata.ApSouth1; import software.amazon.awssdk.regions.regionmetadata.ApSoutheast1; import software.amazon.awssdk.regions.regionmetadata.ApSoutheast2; import software.amazon.awssdk.regions.regionmetadata.CaCentral1; import software.amazon.awssdk.regions.regionmetadata.CnNorth1; import software.amazon.awssdk.regions.regionmetadata.CnNorthwest1; import software.amazon.awssdk.regions.regionmetadata.EuCentral1; import software.amazon.awssdk.regions.regionmetadata.EuNorth1; import software.amazon.awssdk.regions.regionmetadata.EuSouth1; import software.amazon.awssdk.regions.regionmetadata.EuWest1; import software.amazon.awssdk.regions.regionmetadata.EuWest2; import software.amazon.awssdk.regions.regionmetadata.EuWest3; import software.amazon.awssdk.regions.regionmetadata.MeSouth1; import software.amazon.awssdk.regions.regionmetadata.SaEast1; import software.amazon.awssdk.regions.regionmetadata.UsEast1; import software.amazon.awssdk.regions.regionmetadata.UsEast2; import software.amazon.awssdk.regions.regionmetadata.UsGovEast1; import software.amazon.awssdk.regions.regionmetadata.UsGovWest1; import software.amazon.awssdk.regions.regionmetadata.UsIsoEast1; import software.amazon.awssdk.regions.regionmetadata.UsIsoWest1; import software.amazon.awssdk.regions.regionmetadata.UsIsobEast1; import software.amazon.awssdk.regions.regionmetadata.UsWest1; import software.amazon.awssdk.regions.regionmetadata.UsWest2; import software.amazon.awssdk.utils.ImmutableMap; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class GeneratedRegionMetadataProvider implements RegionMetadataProvider { private static final Map<Region, RegionMetadata> REGION_METADATA = ImmutableMap.<Region, RegionMetadata> builder() .put(Region.AF_SOUTH_1, new AfSouth1()).put(Region.AP_EAST_1, new ApEast1()) .put(Region.AP_NORTHEAST_1, new ApNortheast1()).put(Region.AP_NORTHEAST_2, new ApNortheast2()) .put(Region.AP_NORTHEAST_3, new ApNortheast3()).put(Region.AP_SOUTH_1, new ApSouth1()) .put(Region.AP_SOUTHEAST_1, new ApSoutheast1()).put(Region.AP_SOUTHEAST_2, new ApSoutheast2()) .put(Region.CA_CENTRAL_1, new CaCentral1()).put(Region.EU_CENTRAL_1, new EuCentral1()) .put(Region.EU_NORTH_1, new EuNorth1()).put(Region.EU_SOUTH_1, new EuSouth1()).put(Region.EU_WEST_1, new EuWest1()) .put(Region.EU_WEST_2, new EuWest2()).put(Region.EU_WEST_3, new EuWest3()).put(Region.ME_SOUTH_1, new MeSouth1()) .put(Region.SA_EAST_1, new SaEast1()).put(Region.US_EAST_1, new UsEast1()).put(Region.US_EAST_2, new UsEast2()) .put(Region.US_WEST_1, new UsWest1()).put(Region.US_WEST_2, new UsWest2()).put(Region.CN_NORTH_1, new CnNorth1()) .put(Region.CN_NORTHWEST_1, new CnNorthwest1()).put(Region.US_GOV_EAST_1, new UsGovEast1()) .put(Region.US_GOV_WEST_1, new UsGovWest1()).put(Region.US_ISO_EAST_1, new UsIsoEast1()) .put(Region.US_ISO_WEST_1, new UsIsoWest1()).put(Region.US_ISOB_EAST_1, new UsIsobEast1()).build(); public RegionMetadata regionMetadata(Region region) { return REGION_METADATA.get(region); } }
3,102
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/endpoint-tags.java
package software.amazon.awssdk.regions; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; /** * A tag applied to endpoints to specify that they're to be used in certain contexts. For example, FIPS tags are applied * to endpoints discussed here: https://aws.amazon.com/compliance/fips/ and DUALSTACK tags are applied to endpoints that * can return IPv6 addresses. */ @SdkPublicApi @Generated("software.amazon.awssdk:codegen") public final class EndpointTag { public static final EndpointTag DUALSTACK = EndpointTag.of("dualstack"); public static final EndpointTag FIPS = EndpointTag.of("fips"); private static final List<EndpointTag> ENDPOINT_TAGS = Collections.unmodifiableList(Arrays.asList(DUALSTACK, FIPS)); private final String id; private EndpointTag(String id) { this.id = id; } public static EndpointTag of(String id) { return EndpointTagCache.put(id); } public static List<EndpointTag> endpointTags() { return ENDPOINT_TAGS; } public String id() { return this.id; } @Override public String toString() { return id; } private static class EndpointTagCache { private static final ConcurrentHashMap<String, EndpointTag> IDS = new ConcurrentHashMap<>(); private EndpointTagCache() { } private static EndpointTag put(String id) { return IDS.computeIfAbsent(id, EndpointTag::new); } } }
3,103
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/s3-service-metadata.java
package software.amazon.awssdk.regions.servicemetadata; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.EndpointTag; import software.amazon.awssdk.regions.PartitionEndpointKey; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceEndpointKey; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServicePartitionMetadata; import software.amazon.awssdk.regions.internal.DefaultServicePartitionMetadata; import software.amazon.awssdk.regions.internal.util.ServiceMetadataUtils; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.awssdk.utils.Pair; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class S3ServiceMetadata implements ServiceMetadata { private static final String ENDPOINT_PREFIX = "s3"; private static final List<Region> REGIONS = Collections.unmodifiableList(Arrays.asList(Region.of("af-south-1"), Region.of("ap-east-1"), Region.of("ap-northeast-1"), Region.of("ap-northeast-2"), Region.of("ap-northeast-3"), Region.of("ap-south-1"), Region.of("ap-southeast-1"), Region.of("ap-southeast-2"), Region.of("aws-global"), Region.of("ca-central-1"), Region.of("eu-central-1"), Region.of("eu-north-1"), Region.of("eu-south-1"), Region.of("eu-west-1"), Region.of("eu-west-2"), Region.of("eu-west-3"), Region.of("fips-ca-central-1"), Region.of("fips-us-east-1"), Region.of("fips-us-east-2"), Region.of("fips-us-west-1"), Region.of("fips-us-west-2"), Region.of("me-south-1"), Region.of("sa-east-1"), Region.of("us-east-1"), Region.of("us-east-2"), Region.of("us-west-1"), Region.of("us-west-2"), Region.of("cn-north-1"), Region.of("cn-northwest-1"), Region.of("fips-us-gov-east-1"), Region.of("fips-us-gov-west-1"), Region.of("us-gov-east-1"), Region.of("us-gov-west-1"), Region.of("us-iso-east-1"), Region.of("us-iso-west-1"), Region.of("us-isob-east-1"))); private static final List<ServicePartitionMetadata> PARTITIONS = Collections.unmodifiableList(Arrays.asList( new DefaultServicePartitionMetadata("aws", null), new DefaultServicePartitionMetadata("aws-cn", null), new DefaultServicePartitionMetadata("aws-us-gov", null), new DefaultServicePartitionMetadata("aws-iso", null), new DefaultServicePartitionMetadata("aws-iso-b", null))); private static final Map<ServiceEndpointKey, String> SIGNING_REGIONS_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder() .put(ServiceEndpointKey.builder().region(Region.of("aws-global")).build(), "us-east-1") .put(ServiceEndpointKey.builder().region(Region.of("fips-ca-central-1")).build(), "ca-central-1") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-east-1")).build(), "us-east-1") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-east-2")).build(), "us-east-2") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-west-1")).build(), "us-west-1") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-west-2")).build(), "us-west-2") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-gov-east-1")).build(), "us-gov-east-1") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-gov-west-1")).build(), "us-gov-west-1").build(); private static final Map<Pair<String, PartitionEndpointKey>, String> SIGNING_REGIONS_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder().build(); private static final Map<ServiceEndpointKey, String> DNS_SUFFIXES_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder().build(); private static final Map<Pair<String, PartitionEndpointKey>, String> DNS_SUFFIXES_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder() .put(Pair.of("aws", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build()), "amazonaws.com") .put(Pair.of("aws", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "amazonaws.com") .put(Pair.of("aws-cn", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "amazonaws.com.cn") .put(Pair.of("aws-us-gov", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")) .build()), "amazonaws.com") .put(Pair.of("aws-us-gov", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "amazonaws.com") .build(); private static final Map<ServiceEndpointKey, String> HOSTNAMES_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder() .put(ServiceEndpointKey.builder().region(Region.of("af-south-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.af-south-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-east-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-northeast-1")).build(), "s3.ap-northeast-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-northeast-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-northeast-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-northeast-2")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-northeast-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-northeast-3")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-northeast-3.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-south-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-south-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-southeast-1")).build(), "s3.ap-southeast-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-southeast-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-southeast-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-southeast-2")).build(), "s3.ap-southeast-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ap-southeast-2")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ap-southeast-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("aws-global")).build(), "s3.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ca-central-1")).tags(EndpointTag.of("fips")).build(), "s3-fips.ca-central-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ca-central-1")) .tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "s3-fips.dualstack.ca-central-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("ca-central-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.ca-central-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-central-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-central-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-north-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-north-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-south-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-south-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-west-1")).build(), "s3.eu-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-west-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-west-2")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("eu-west-3")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.eu-west-3.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-ca-central-1")).build(), "s3-fips.ca-central-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-east-1")).build(), "s3-fips.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-east-2")).build(), "s3-fips.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-west-1")).build(), "s3-fips.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-west-2")).build(), "s3-fips.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("me-south-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.me-south-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("sa-east-1")).build(), "s3.sa-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("sa-east-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.sa-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1")).build(), "s3.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1")) .tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "s3-fips.dualstack.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2")) .tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "s3-fips.dualstack.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1")).build(), "s3.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1")) .tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "s3-fips.dualstack.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2")).build(), "s3.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2")) .tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build(), "s3-fips.dualstack.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("cn-north-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.cn-north-1.amazonaws.com.cn") .put(ServiceEndpointKey.builder().region(Region.of("cn-northwest-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.cn-northwest-1.amazonaws.com.cn") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-gov-east-1")).build(), "s3-fips.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("fips-us-gov-west-1")).build(), "s3-fips.us-gov-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1")).build(), "s3.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1")).build(), "s3.us-gov-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1")).tags(EndpointTag.of("fips")).build(), "s3-fips.us-gov-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1")).tags(EndpointTag.of("dualstack")).build(), "s3.dualstack.us-gov-west-1.amazonaws.com").build(); private static final Map<Pair<String, PartitionEndpointKey>, String> HOSTNAMES_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder() .put(Pair.of("aws", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")).build()), "{service}-fips.dualstack.{region}.{dnsSuffix}") .put(Pair.of("aws", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "{service}.dualstack.{region}.{dnsSuffix}") .put(Pair.of("aws-cn", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "{service}.dualstack.{region}.{dnsSuffix}") .put(Pair.of("aws-us-gov", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack"), EndpointTag.of("fips")) .build()), "{service}-fips.dualstack.{region}.{dnsSuffix}") .put(Pair.of("aws-us-gov", PartitionEndpointKey.builder().tags(EndpointTag.of("dualstack")).build()), "{service}.dualstack.{region}.{dnsSuffix}").build(); @Override public List<Region> regions() { return REGIONS; } @Override public List<ServicePartitionMetadata> servicePartitions() { return PARTITIONS; } @Override public URI endpointFor(ServiceEndpointKey key) { return ServiceMetadataUtils.endpointFor(ServiceMetadataUtils.hostname(key, HOSTNAMES_BY_REGION, HOSTNAMES_BY_PARTITION), ENDPOINT_PREFIX, key.region().id(), ServiceMetadataUtils.dnsSuffix(key, DNS_SUFFIXES_BY_REGION, DNS_SUFFIXES_BY_PARTITION)); } @Override public Region signingRegion(ServiceEndpointKey key) { return ServiceMetadataUtils.signingRegion(key, SIGNING_REGIONS_BY_REGION, SIGNING_REGIONS_BY_PARTITION); } }
3,104
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/us-east-1.java
package software.amazon.awssdk.regions.regionmetadata; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.PartitionMetadata; import software.amazon.awssdk.regions.RegionMetadata; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class UsEast1 implements RegionMetadata { private static final String ID = "us-east-1"; private static final String DOMAIN = "amazonaws.com"; private static final String DESCRIPTION = "US East (N. Virginia)"; private static final String PARTITION_ID = "aws"; @Override public String id() { return ID; } @Override public String domain() { return DOMAIN; } @Override public String description() { return DESCRIPTION; } @Override public PartitionMetadata partition() { return PartitionMetadata.of(PARTITION_ID); } }
3,105
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/defaultsmode/defaults-mode-configuration.java
package software.amazon.awssdk.defaultsmode; import java.time.Duration; import java.util.EnumMap; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption; import software.amazon.awssdk.utils.AttributeMap; /** * Contains a collection of default configuration options for each DefaultsMode */ @SdkInternalApi @Generated("software.amazon.awssdk:codegen") public final class DefaultsModeConfiguration { private static final AttributeMap STANDARD_DEFAULTS = AttributeMap.builder() .put(SdkClientOption.DEFAULT_RETRY_MODE, RetryMode.STANDARD) .put(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "regional").build(); private static final AttributeMap STANDARD_HTTP_DEFAULTS = AttributeMap.builder() .put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.ofMillis(2000)) .put(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT, Duration.ofMillis(2000)).build(); private static final AttributeMap MOBILE_DEFAULTS = AttributeMap.builder() .put(SdkClientOption.DEFAULT_RETRY_MODE, RetryMode.ADAPTIVE) .put(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "regional").build(); private static final AttributeMap MOBILE_HTTP_DEFAULTS = AttributeMap.builder() .put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.ofMillis(10000)) .put(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT, Duration.ofMillis(11000)).build(); private static final AttributeMap CROSS_REGION_DEFAULTS = AttributeMap.builder() .put(SdkClientOption.DEFAULT_RETRY_MODE, RetryMode.STANDARD) .put(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "regional").build(); private static final AttributeMap CROSS_REGION_HTTP_DEFAULTS = AttributeMap.builder() .put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.ofMillis(2800)) .put(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT, Duration.ofMillis(2800)).build(); private static final AttributeMap IN_REGION_DEFAULTS = AttributeMap.builder() .put(SdkClientOption.DEFAULT_RETRY_MODE, RetryMode.STANDARD) .put(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "regional").build(); private static final AttributeMap IN_REGION_HTTP_DEFAULTS = AttributeMap.builder() .put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.ofMillis(1000)) .put(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT, Duration.ofMillis(1000)).build(); private static final AttributeMap LEGACY_DEFAULTS = AttributeMap.empty(); private static final AttributeMap LEGACY_HTTP_DEFAULTS = AttributeMap.empty(); private static final Map<DefaultsMode, AttributeMap> DEFAULT_CONFIG_BY_MODE = new EnumMap<>(DefaultsMode.class); private static final Map<DefaultsMode, AttributeMap> DEFAULT_HTTP_CONFIG_BY_MODE = new EnumMap<>(DefaultsMode.class); static { DEFAULT_CONFIG_BY_MODE.put(DefaultsMode.STANDARD, STANDARD_DEFAULTS); DEFAULT_CONFIG_BY_MODE.put(DefaultsMode.MOBILE, MOBILE_DEFAULTS); DEFAULT_CONFIG_BY_MODE.put(DefaultsMode.CROSS_REGION, CROSS_REGION_DEFAULTS); DEFAULT_CONFIG_BY_MODE.put(DefaultsMode.IN_REGION, IN_REGION_DEFAULTS); DEFAULT_CONFIG_BY_MODE.put(DefaultsMode.LEGACY, LEGACY_DEFAULTS); DEFAULT_HTTP_CONFIG_BY_MODE.put(DefaultsMode.STANDARD, STANDARD_HTTP_DEFAULTS); DEFAULT_HTTP_CONFIG_BY_MODE.put(DefaultsMode.MOBILE, MOBILE_HTTP_DEFAULTS); DEFAULT_HTTP_CONFIG_BY_MODE.put(DefaultsMode.CROSS_REGION, CROSS_REGION_HTTP_DEFAULTS); DEFAULT_HTTP_CONFIG_BY_MODE.put(DefaultsMode.IN_REGION, IN_REGION_HTTP_DEFAULTS); DEFAULT_HTTP_CONFIG_BY_MODE.put(DefaultsMode.LEGACY, LEGACY_HTTP_DEFAULTS); } private DefaultsModeConfiguration() { } /** * Return the default config options for a given defaults mode */ public static AttributeMap defaultConfig(DefaultsMode mode) { return DEFAULT_CONFIG_BY_MODE.getOrDefault(mode, AttributeMap.empty()); } /** * Return the default config options for a given defaults mode */ public static AttributeMap defaultHttpConfig(DefaultsMode mode) { return DEFAULT_HTTP_CONFIG_BY_MODE.getOrDefault(mode, AttributeMap.empty()); } }
3,106
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/defaultsmode/defaults-mode.java
package software.amazon.awssdk.defaultsmode; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.internal.EnumUtils; /** * A defaults mode determines how certain default configuration options are resolved in the SDK. Based on the provided * mode, the SDK will vend sensible default values tailored to the mode for the following settings: * <ul> * <li>retryMode: PLACEHOLDER</li> * <li>s3UsEast1RegionalEndpoints: PLACEHOLDER</li> * <li>connectTimeoutInMillis: PLACEHOLDER</li> * <li>tlsNegotiationTimeoutInMillis: PLACEHOLDER</li> * </ul> * <p> * All options above can be configured by users, and the overridden value will take precedence. * <p> * <b>Note:</b> for any mode other than {@link #LEGACY}, the vended default values might change as best practices may * evolve. As a result, it is encouraged to perform testing when upgrading the SDK if you are using a mode other than * {@link #LEGACY} * <p> * While the {@link #LEGACY} defaults mode is specific to Java, other modes are standardized across all of the AWS SDKs * </p> * <p> * The defaults mode can be configured: * <ol> * <li>Directly on a client via {@code AwsClientBuilder.Builder#defaultsMode(DefaultsMode)}.</li> * <li>On a configuration profile via the "defaults_mode" profile file property.</li> * <li>Globally via the "aws.defaultsMode" system property.</li> * <li>Globally via the "AWS_DEFAULTS_MODE" environment variable.</li> * </ol> */ @SdkPublicApi @Generated("software.amazon.awssdk:codegen") public enum DefaultsMode { /** * PLACEHOLDER */ LEGACY("legacy"), /** * PLACEHOLDER */ STANDARD("standard"), /** * PLACEHOLDER */ MOBILE("mobile"), /** * PLACEHOLDER */ CROSS_REGION("cross-region"), /** * PLACEHOLDER */ IN_REGION("in-region"), /** * PLACEHOLDER */ AUTO("auto"); private static final Map<String, DefaultsMode> VALUE_MAP = EnumUtils.uniqueIndex(DefaultsMode.class, DefaultsMode::toString); private final String value; private DefaultsMode(String value) { this.value = value; } /** * Use this in place of valueOf to convert the raw string returned by the service into the enum value. * * @param value * real value * @return DefaultsMode corresponding to the value */ public static DefaultsMode fromValue(String value) { Validate.paramNotNull(value, "value"); if (!VALUE_MAP.containsKey(value)) { throw new IllegalArgumentException("The provided value is not a valid defaults mode " + value); } return VALUE_MAP.get(value); } @Override public String toString() { return String.valueOf(value); } }
3,107
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite/PoetMatchers.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace; import com.squareup.javapoet.JavaFile; import java.io.IOException; import java.io.InputStream; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.ComparisonFailure; import software.amazon.awssdk.codegen.lite.emitters.CodeTransformer; import software.amazon.awssdk.codegen.lite.emitters.JavaCodeFormatter; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Validate; public final class PoetMatchers { private static final CodeTransformer processor = CodeTransformer.chain(new CopyrightRemover(), new JavaCodeFormatter()); public static Matcher<PoetClass> generatesTo(String expectedTestFile) { return new TypeSafeMatcher<PoetClass>() { @Override protected boolean matchesSafely(PoetClass spec) { String expectedClass = getExpectedClass(spec, expectedTestFile); String actualClass = generateClass(spec); try { assertThat(actualClass, equalToIgnoringWhiteSpace(expectedClass)); } catch (AssertionError e) { //Unfortunately for string comparisons Hamcrest doesn't really give us a nice diff. On the other hand //IDEs know how to nicely display JUnit's ComparisonFailure - makes debugging tests much easier throw new ComparisonFailure(String.format("Output class does not match expected [test-file: %s]", expectedTestFile), expectedClass, actualClass); } return true; } @Override public void describeTo(Description description) { //Since we bubble an exception this will never actually get called } }; } private static String getExpectedClass(PoetClass spec, String testFile) { try { InputStream resource = spec.getClass().getResourceAsStream(testFile); Validate.notNull(resource, "Failed to load test file: " + testFile); return processor.apply(IoUtils.toUtf8String(resource)); } catch (IOException e) { throw new RuntimeException(e); } } private static String generateClass(PoetClass spec) { StringBuilder output = new StringBuilder(); try { buildJavaFile(spec).writeTo(output); } catch (IOException e) { throw new RuntimeException("Failed to generate class", e); } return processor.apply(output.toString()); } private static class CopyrightRemover implements CodeTransformer { @Override public String apply(String input) { return input.substring(input.indexOf("package")); } } private static JavaFile buildJavaFile(PoetClass spec) { return JavaFile.builder(spec.className().packageName(), spec.poetClass()).skipJavaLangImports(true).build(); } }
3,108
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite/regions/RegionGenerationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.lite.PoetMatchers.generatesTo; import java.io.File; import java.nio.file.Paths; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.lite.regions.model.Partition; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; public class RegionGenerationTest { private static final String ENDPOINTS = "/software/amazon/awssdk/codegen/lite/test-endpoints.json"; private static final String SERVICE_METADATA_BASE = "software.amazon.awssdk.regions.servicemetadata"; private static final String REGION_METADATA_BASE = "software.amazon.awssdk.regions.regionmetadata"; private static final String PARTITION_METADATA_BASE = "software.amazon.awssdk.regions.partitionmetadata"; private static final String REGION_BASE = "software.amazon.awssdk.regions"; private File endpoints; private Partitions partitions; @BeforeEach public void before() throws Exception { this.endpoints = Paths.get(getClass().getResource(ENDPOINTS).toURI()).toFile(); this.partitions = RegionMetadataLoader.build(endpoints); } @Test public void regionClass() { RegionGenerator regions = new RegionGenerator(partitions, REGION_BASE); assertThat(regions, generatesTo("regions.java")); } @Test public void regionMetadataClass() { Partition partition = partitions.getPartitions().get(0); RegionMetadataGenerator metadataGenerator = new RegionMetadataGenerator(partition, "us-east-1", "US East (N. Virginia)", REGION_METADATA_BASE, REGION_BASE); assertThat(metadataGenerator, generatesTo("us-east-1.java")); } @Test public void regionMetadataProviderClass() { RegionMetadataProviderGenerator providerGenerator = new RegionMetadataProviderGenerator(partitions, REGION_METADATA_BASE, REGION_BASE); assertThat(providerGenerator, generatesTo("region-metadata-provider.java")); } @Test public void serviceMetadataClass() { ServiceMetadataGenerator serviceMetadataGenerator = new ServiceMetadataGenerator(partitions, "s3", SERVICE_METADATA_BASE, REGION_BASE); assertThat(serviceMetadataGenerator, generatesTo("s3-service-metadata.java")); } @Test public void serviceWithOverriddenPartitionsMetadataClass() { ServiceMetadataGenerator serviceMetadataGenerator = new ServiceMetadataGenerator(partitions, "sts", SERVICE_METADATA_BASE, REGION_BASE); assertThat(serviceMetadataGenerator, generatesTo("sts-service-metadata.java")); } @Test public void serviceMetadataProviderClass() { ServiceMetadataProviderGenerator serviceMetadataProviderGenerator = new ServiceMetadataProviderGenerator(partitions, SERVICE_METADATA_BASE, REGION_BASE); assertThat(serviceMetadataProviderGenerator, generatesTo("service-metadata-provider.java")); } @Test public void partitionMetadataClass() { PartitionMetadataGenerator partitionMetadataGenerator = new PartitionMetadataGenerator(partitions.getPartitions().get(0), PARTITION_METADATA_BASE, REGION_BASE); assertThat(partitionMetadataGenerator, generatesTo("partition-metadata.java")); } @Test public void endpointTagClass() { EndpointTagGenerator partitionMetadataGenerator = new EndpointTagGenerator(partitions, REGION_BASE); assertThat(partitionMetadataGenerator, generatesTo("endpoint-tags.java")); } @Test public void partitionMetadataProviderClass() { PartitionMetadataProviderGenerator partitionMetadataProviderGenerator = new PartitionMetadataProviderGenerator(partitions, PARTITION_METADATA_BASE, REGION_BASE); assertThat(partitionMetadataProviderGenerator, generatesTo("partition-metadata-provider.java")); } }
3,109
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite/regions/RegionValidationUtilTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class RegionValidationUtilTest { private static final String AWS_PARTITION_REGEX = "^(us|eu|ap|sa|ca)\\-\\w+\\-\\d+$"; private static final String AWS_CN_PARTITION_REGEX = "^cn\\-\\w+\\-\\d+$"; private static final String AWS_GOV_PARTITION_REGEX = "^us\\-gov\\-\\w+\\-\\d+$"; @Test public void usEast1_AwsPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-east-1", AWS_PARTITION_REGEX)); } @Test public void usWest2Fips_AwsPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-west-2-fips", AWS_PARTITION_REGEX)); } @Test public void fipsUsWest2_AwsPartition_IsNotValidRegion() { assertTrue(RegionValidationUtil.validRegion("fips-us-west-2", AWS_PARTITION_REGEX)); } @Test public void fips_AwsPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("fips", AWS_PARTITION_REGEX)); } @Test public void prodFips_AwsPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("ProdFips", AWS_PARTITION_REGEX)); } @Test public void cnNorth1_AwsCnPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("cn-north-1", AWS_PARTITION_REGEX)); } @Test public void cnNorth1_AwsCnPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("cn-north-1", AWS_CN_PARTITION_REGEX)); } @Test public void usEast1_AwsCnPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("us-east-1", AWS_CN_PARTITION_REGEX)); } @Test public void usGovWest1_AwsGovPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-gov-west-1", AWS_GOV_PARTITION_REGEX)); } @Test public void usGovWest1Fips_AwsGovPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-gov-west-1-fips", AWS_GOV_PARTITION_REGEX)); } @Test public void fipsUsGovWest1_AwsGovPartition_IsNotValidRegion() { assertTrue(RegionValidationUtil.validRegion("fips-us-gov-west-1", AWS_GOV_PARTITION_REGEX)); } @Test public void fips_AwsGovPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("fips", AWS_GOV_PARTITION_REGEX)); } @Test public void prodFips_AwsGovPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("ProdFips", AWS_GOV_PARTITION_REGEX)); } @Test public void cnNorth1_AwsGovPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("cn-north-1", AWS_GOV_PARTITION_REGEX)); } @Test public void awsGlobal_AwsPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("aws-global", AWS_PARTITION_REGEX)); } @Test public void awsGovGlobal_AwsGovPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("aws-us-gov-global", AWS_GOV_PARTITION_REGEX)); } @Test public void awsCnGlobal_AwsCnPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("aws-cn-global", AWS_CN_PARTITION_REGEX)); } }
3,110
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/java/software/amazon/awssdk/codegen/lite/defaultsmode/DefaultsModeGenerationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.defaultsmode; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.lite.PoetMatchers.generatesTo; import java.io.File; import java.nio.file.Paths; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class DefaultsModeGenerationTest { private static final String DEFAULT_CONFIGURATION = "/software/amazon/awssdk/codegen/lite/test-sdk-default-configuration.json"; private static final String DEFAULTS_MODE_BASE = "software.amazon.awssdk.defaultsmode"; private File file; private DefaultConfiguration defaultConfiguration; @BeforeEach public void before() throws Exception { this.file = Paths.get(getClass().getResource(DEFAULT_CONFIGURATION).toURI()).toFile(); this.defaultConfiguration = DefaultsLoader.load(file); } @Test public void defaultsModeEnum() { DefaultsModeGenerator generator = new DefaultsModeGenerator(DEFAULTS_MODE_BASE, defaultConfiguration); assertThat(generator, generatesTo("defaults-mode.java")); } @Test public void defaultsModeConfigurationClass() { DefaultsModeConfigurationGenerator generator = new DefaultsModeConfigurationGenerator(DEFAULTS_MODE_BASE, DEFAULTS_MODE_BASE, defaultConfiguration); assertThat(generator, generatesTo("defaults-mode-configuration.java")); } }
3,111
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/Utils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite; import java.io.Closeable; import java.io.File; import java.io.IOException; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.StringUtils; public final class Utils { private Utils() { } public static String capitalize(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } return name.length() < 2 ? StringUtils.upperCase(name) : StringUtils.upperCase(name.substring(0, 1)) + name.substring(1); } public static File createDirectory(String path) { if (isNullOrEmpty(path)) { throw new IllegalArgumentException( "Invalid path directory. Path directory cannot be null or empty"); } File dir = new File(path); createDirectory(dir); return dir; } public static void createDirectory(File dir) { if (!(dir.exists())) { if (!dir.mkdirs()) { throw new RuntimeException("Not able to create directory. " + dir.getAbsolutePath()); } } } public static File createFile(String dir, String fileName) throws IOException { if (isNullOrEmpty(fileName)) { throw new IllegalArgumentException( "Invalid file name. File name cannot be null or empty"); } createDirectory(dir); File file = new File(dir, fileName); if (!(file.exists())) { if (!(file.createNewFile())) { throw new RuntimeException("Not able to create file . " + file.getAbsolutePath()); } } return file; } public static boolean isNullOrEmpty(String str) { return str == null || str.trim().isEmpty(); } public static void closeQuietly(Closeable closeable) { IoUtils.closeQuietly(closeable, null); } }
3,112
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/PoetClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeSpec; public interface PoetClass { /** * @return The actual class specification generated from a <code>PoetSpec.builder()...</code> implementation */ TypeSpec poetClass(); ClassName className(); }
3,113
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/CodeGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite; import static software.amazon.awssdk.codegen.lite.Utils.closeQuietly; import com.squareup.javapoet.JavaFile; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.time.ZonedDateTime; import software.amazon.awssdk.codegen.lite.emitters.CodeWriter; import software.amazon.awssdk.utils.IoUtils; public final class CodeGenerator { private final Writer writer; private final PoetClass poetClass; public CodeGenerator(String outputDirectory, PoetClass poetClass) { this.writer = new CodeWriter(outputDirectory, poetClass.className().simpleName()); this.poetClass = poetClass; } public void generate() { try { writer.write(loadDefaultFileHeader() + "\n"); JavaFile.builder(poetClass.className().packageName(), poetClass.poetClass()) .skipJavaLangImports(true) .build() .writeTo(writer); writer.flush(); } catch (IOException e) { throw new RuntimeException(String.format("Error creating class %s", poetClass.className().simpleName()), e); } finally { closeQuietly(writer); } } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/lite/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } }
3,114
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/RegionValidationUtil.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.Set; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.lite.regions.model.Endpoint; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; @SdkInternalApi public final class RegionValidationUtil { private static final Set<String> DEPRECATED_REGIONS_ALLOWSLIST = new HashSet<>(); private static final String FIPS_SUFFIX = "-fips"; private static final String FIPS_PREFIX = "fips-"; static { try (InputStream allowListStream = RegionValidationUtil.class.getResourceAsStream("/software/amazon/awssdk/codegen/lite" + "/DeprecatedRegionsAllowlist.txt")) { Validate.notNull(allowListStream, "Failed to load deprecated regions allowlist."); try (BufferedReader br = new BufferedReader(new InputStreamReader(allowListStream, StandardCharsets.UTF_8))) { String line; while ((line = br.readLine()) != null) { DEPRECATED_REGIONS_ALLOWSLIST.add(StringUtils.trim(line)); } } } catch (IOException e) { throw new UncheckedIOException(e); } } private RegionValidationUtil() { } /** * Determines if a given region string is a "valid" AWS region. * * The region string must either match the partition regex, end with fips * and match the partition regex with that included, or include the word "global". * * @param regex - Regex for regions in a given partition. * @param region - Region string being checked. * @return true if the region string should be included as a region. */ public static boolean validRegion(String region, String regex) { return matchesRegex(region, regex) || matchesRegexFipsSuffix(region, regex) || matchesRegexFipsPrefix(region, regex) || isGlobal(region); } public static boolean validEndpoint(String region, Endpoint endpoint) { boolean invalidEndpoint = Boolean.TRUE.equals(endpoint.getDeprecated()) && !DEPRECATED_REGIONS_ALLOWSLIST.contains(region); return !invalidEndpoint; } private static boolean matchesRegex(String region, String regex) { return region.matches(regex); } private static boolean matchesRegexFipsSuffix(String region, String regex) { return region.replace(FIPS_SUFFIX, "").matches(regex); } private static boolean matchesRegexFipsPrefix(String region, String regex) { return region.replace(FIPS_PREFIX, "").matches(regex); } private static boolean isGlobal(String region) { return region.contains("global"); } }
3,115
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/ServiceMetadataProviderGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.utils.ImmutableMap; public class ServiceMetadataProviderGenerator implements PoetClass { private final Partitions partitions; private final String basePackage; private final String regionBasePackage; public ServiceMetadataProviderGenerator(Partitions partitions, String basePackage, String regionBasePackage) { this.partitions = partitions; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; } @Override public TypeSpec poetClass() { TypeName mapOfServiceMetadata = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), ClassName.get(regionBasePackage, "ServiceMetadata")); return TypeSpec.classBuilder(className()) .addModifiers(PUBLIC) .addSuperinterface(ClassName.get(regionBasePackage, "ServiceMetadataProvider")) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addAnnotation(SdkPublicApi.class) .addModifiers(FINAL) .addField(FieldSpec.builder(mapOfServiceMetadata, "SERVICE_METADATA") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(regions(partitions)) .build()) .addMethod(getter()) .build(); } @Override public ClassName className() { return ClassName.get(regionBasePackage, "GeneratedServiceMetadataProvider"); } private CodeBlock regions(Partitions partitions) { CodeBlock.Builder builder = CodeBlock.builder().add("$T.<String, ServiceMetadata>builder()", ImmutableMap.class); Set<String> seenServices = new HashSet<>(); partitions.getPartitions() .forEach(p -> p.getServices() .keySet() .forEach(s -> { if (!seenServices.contains(s)) { builder.add(".put($S, new $T())", s, serviceMetadataClass(s)); seenServices.add(s); } })); return builder.add(".build()").build(); } private ClassName serviceMetadataClass(String service) { if ("s3".equals(service)) { // This class contains extra logic for detecting the regional endpoint flag return ClassName.get(basePackage, "EnhancedS3ServiceMetadata"); } String sanitizedServiceName = service.replace(".", "-"); return ClassName.get(basePackage, Stream.of(sanitizedServiceName.split("-")) .map(Utils::capitalize) .collect(Collectors.joining()) + "ServiceMetadata"); } private MethodSpec getter() { return MethodSpec.methodBuilder("serviceMetadata") .addModifiers(PUBLIC) .addParameter(String.class, "endpointPrefix") .returns(ClassName.get(regionBasePackage, "ServiceMetadata")) .addStatement("return $L.get($L)", "SERVICE_METADATA", "endpointPrefix") .build(); } }
3,116
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/ServiceMetadataGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import static java.util.Collections.emptyList; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Endpoint; import software.amazon.awssdk.codegen.lite.regions.model.Partition; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.codegen.lite.regions.model.Service; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.Validate; public class ServiceMetadataGenerator implements PoetClass { private final Partitions partitions; private final String serviceEndpointPrefix; private final String basePackage; private final String regionBasePackage; public ServiceMetadataGenerator(Partitions partitions, String serviceEndpointPrefix, String basePackage, String regionBasePackage) { this.partitions = partitions; this.serviceEndpointPrefix = serviceEndpointPrefix; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; removeBadRegions(); } private void removeBadRegions() { partitions.getPartitions().forEach(partition -> { partition.getServices().values().forEach(service -> { Iterator<Map.Entry<String, Endpoint>> endpointIterator = service.getEndpoints().entrySet().iterator(); while (endpointIterator.hasNext()) { Map.Entry<String, Endpoint> entry = endpointIterator.next(); String endpointName = entry.getKey(); Endpoint endpoint = entry.getValue(); if (!RegionValidationUtil.validRegion(endpointName, partition.getRegionRegex()) || !RegionValidationUtil.validEndpoint(endpointName, endpoint)) { endpointIterator.remove(); } } }); }); } @Override public TypeSpec poetClass() { TypeName listOfRegions = ParameterizedTypeName.get(ClassName.get(List.class), ClassName.get(regionBasePackage, "Region")); TypeName mapByServiceEndpointKey = ParameterizedTypeName.get(ClassName.get(Map.class), serviceEndpointKeyClass(), ClassName.get(String.class)); TypeName mapByPair = ParameterizedTypeName.get(ClassName.get(Map.class), byPartitionKeyClass(), ClassName.get(String.class)); TypeName listOfServicePartitionMetadata = ParameterizedTypeName.get(ClassName.get(List.class), ClassName.get(regionBasePackage, "ServicePartitionMetadata")); return TypeSpec.classBuilder(className()) .addModifiers(Modifier.PUBLIC) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addAnnotation(SdkPublicApi.class) .addModifiers(FINAL) .addSuperinterface(ClassName.get(regionBasePackage, "ServiceMetadata")) .addField(FieldSpec.builder(String.class, "ENDPOINT_PREFIX") .addModifiers(PRIVATE, FINAL, STATIC) .initializer("$S", serviceEndpointPrefix) .build()) .addField(FieldSpec.builder(listOfRegions, "REGIONS") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(regionsField(partitions)) .build()) .addField(FieldSpec.builder(listOfServicePartitionMetadata, "PARTITIONS") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(servicePartitions(partitions)) .build()) .addField(FieldSpec.builder(mapByServiceEndpointKey, "SIGNING_REGIONS_BY_REGION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(signingRegionsByRegion(partitions)) .build()) .addField(FieldSpec.builder(mapByPair, "SIGNING_REGIONS_BY_PARTITION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(signingRegionsByPartition(partitions)) .build()) .addField(FieldSpec.builder(mapByServiceEndpointKey, "DNS_SUFFIXES_BY_REGION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(dnsSuffixesByRegion(partitions)) .build()) .addField(FieldSpec.builder(mapByPair, "DNS_SUFFIXES_BY_PARTITION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(dnsSuffixesByPartition(partitions)) .build()) .addField(FieldSpec.builder(mapByServiceEndpointKey, "HOSTNAMES_BY_REGION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(hostnamesByRegion(partitions)) .build()) .addField(FieldSpec.builder(mapByPair, "HOSTNAMES_BY_PARTITION") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(hostnamesByPartition(partitions)) .build()) .addMethod(regions()) .addMethod(partitions(listOfServicePartitionMetadata)) .addMethod(endpointFor()) .addMethod(signingRegion()) .build(); } @Override public ClassName className() { String sanitizedServiceName = serviceEndpointPrefix.replace(".", "-"); return ClassName.get(basePackage, Stream.of(sanitizedServiceName.split("-")) .map(Utils::capitalize) .collect(Collectors.joining()) + "ServiceMetadata"); } private CodeBlock signingRegionsByRegion(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, serviceEndpointKeyClass(), String.class); services.forEach((partition, service) -> { service.getEndpoints().forEach((region, endpoint) -> { if (endpoint.getCredentialScope() != null && endpoint.getCredentialScope().getRegion() != null) { builder.add(".put(") .add(serviceEndpointKey(region, emptyList())) .add(", $S)\n", endpoint.getCredentialScope().getRegion()); endpoint.getVariants().forEach(variant -> { builder.add(".put(") .add(serviceEndpointKey(region, variant.getTags())) .add(", $S)\n", endpoint.getCredentialScope().getRegion()); }); } }); }); return builder.add(".build()").build(); } private CodeBlock signingRegionsByPartition(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, byPartitionKeyClass(), String.class); services.forEach((partition, service) -> { Endpoint partitionDefaults = service.getDefaults(); if (partitionDefaults != null && partitionDefaults.getCredentialScope() != null && partitionDefaults.getCredentialScope().getRegion() != null) { builder.add(".put($T.of($S, ", Pair.class, partition.getPartition()) .add(partitionEndpointKey(emptyList())) .add("), $S)\n", partitionDefaults.getCredentialScope().getRegion()); partitionDefaults.getVariants().forEach(variant -> { builder.add(".put($T.of($S, ", Pair.class, partition.getPartition()) .add(partitionEndpointKey(variant.getTags())) .add("), $S)\n", partitionDefaults.getCredentialScope().getRegion()); }); } }); return builder.add(".build()").build(); } private CodeBlock dnsSuffixesByRegion(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, serviceEndpointKeyClass(), String.class); services.forEach((partition, service) -> { service.getEndpoints().forEach((region, endpoint) -> { endpoint.getVariants().forEach(variant -> { if (variant.getDnsSuffix() != null) { builder.add(".put(") .add(serviceEndpointKey(region, variant.getTags())) .add(", $S)\n", variant.getDnsSuffix()); } }); }); }); return builder.add(".build()").build(); } private CodeBlock dnsSuffixesByPartition(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, byPartitionKeyClass(), String.class); services.forEach((partition, service) -> { if (service.getDefaults() != null) { service.getDefaults().getVariants().forEach(variant -> { if (variant.getDnsSuffix() != null) { builder.add(".put($T.of($S, ", Pair.class, partition.getPartition()) .add(partitionEndpointKey(variant.getTags())) .add("), $S)\n", variant.getDnsSuffix()); } }); } }); return builder.add(".build()").build(); } private CodeBlock hostnamesByRegion(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, serviceEndpointKeyClass(), String.class); services.forEach((partition, service) -> { service.getEndpoints().forEach((region, endpoint) -> { if (endpoint.getHostname() != null) { builder.add(".put(") .add(serviceEndpointKey(region, emptyList())) .add(", $S)\n", endpoint.getHostname()); } endpoint.getVariants().forEach(variant -> { if (variant.getHostname() != null) { builder.add(".put(") .add(serviceEndpointKey(region, variant.getTags())) .add(", $S)\n", variant.getHostname()); } }); }); }); return builder.add(".build()").build(); } private CodeBlock hostnamesByPartition(Partitions partitions) { Map<Partition, Service> services = getServiceData(partitions); CodeBlock.Builder builder = CodeBlock.builder().add("$T.<$T, $T>builder()", ImmutableMap.class, byPartitionKeyClass(), String.class); services.forEach((partition, service) -> { if (service.getDefaults() != null) { if (service.getDefaults().getHostname() != null) { builder.add(".put($T.of($S, ", Pair.class, partition.getPartition()) .add(partitionEndpointKey(emptyList())) .add(", $S)\n", service.getDefaults().getHostname()); } service.getDefaults().getVariants().forEach(variant -> { if (variant.getHostname() != null) { builder.add(".put($T.of($S, ", Pair.class, partition.getPartition()) .add(partitionEndpointKey(variant.getTags())) .add("), $S)\n", variant.getHostname()); } }); } }); return builder.add(".build()").build(); } private CodeBlock serviceEndpointKey(String region, Collection<String> tags) { Validate.paramNotBlank(region, "region"); CodeBlock.Builder result = CodeBlock.builder(); result.add("$T.builder()", serviceEndpointKeyClass()) .add(".region($T.of($S))", regionClass(), region); if (!tags.isEmpty()) { CodeBlock tagsParameter = tags.stream() .map(tag -> CodeBlock.of("$T.of($S)", endpointTagClass(), tag)) .collect(CodeBlock.joining(", ")); result.add(".tags(").add(tagsParameter).add(")"); } result.add(".build()"); return result.build(); } private CodeBlock partitionEndpointKey(Collection<String> tags) { CodeBlock.Builder result = CodeBlock.builder(); result.add("$T.builder()", partitionEndpointKeyClass()); if (!tags.isEmpty()) { CodeBlock tagsParameter = tags.stream() .map(tag -> CodeBlock.of("$T.of($S)", endpointTagClass(), tag)) .collect(CodeBlock.joining(", ")); result.add(".tags(").add(tagsParameter).add(")"); } result.add(".build()"); return result.build(); } private CodeBlock regionsField(Partitions partitions) { ClassName regionClass = ClassName.get(regionBasePackage, "Region"); CodeBlock.Builder builder = CodeBlock.builder().add("$T.unmodifiableList($T.asList(", Collections.class, Arrays.class); ArrayList<String> regions = new ArrayList<>(); partitions.getPartitions() .stream() .filter(p -> p.getServices().containsKey(serviceEndpointPrefix)) .forEach(p -> regions.addAll(p.getServices().get(serviceEndpointPrefix).getEndpoints().keySet())); for (int i = 0; i < regions.size(); i++) { builder.add("$T.of($S)", regionClass, regions.get(i)); if (i != regions.size() - 1) { builder.add(","); } } return builder.add("))").build(); } private CodeBlock servicePartitions(Partitions partitions) { return CodeBlock.builder() .add("$T.unmodifiableList($T.asList(", Collections.class, Arrays.class) .add(commaSeparatedServicePartitions(partitions)) .add("))") .build(); } private CodeBlock commaSeparatedServicePartitions(Partitions partitions) { ClassName defaultServicePartitionMetadata = ClassName.get(regionBasePackage + ".internal", "DefaultServicePartitionMetadata"); return partitions.getPartitions() .stream() .filter(p -> p.getServices().containsKey(serviceEndpointPrefix)) .map(p -> CodeBlock.of("new $T($S, $L)", defaultServicePartitionMetadata, p.getPartition(), globalRegion(p))) .collect(CodeBlock.joining(",")); } private CodeBlock globalRegion(Partition partition) { ClassName region = ClassName.get(regionBasePackage, "Region"); Service service = partition.getServices().get(this.serviceEndpointPrefix); boolean hasGlobalRegionForPartition = service.isRegionalized() != null && !service.isRegionalized() && service.isPartitionWideEndpointAvailable(); String globalRegionForPartition = hasGlobalRegionForPartition ? service.getPartitionEndpoint() : null; return globalRegionForPartition == null ? CodeBlock.of("null") : CodeBlock.of("$T.of($S)", region, globalRegionForPartition); } private MethodSpec regions() { TypeName listOfRegions = ParameterizedTypeName.get(ClassName.get(List.class), ClassName.get(regionBasePackage, "Region")); return MethodSpec.methodBuilder("regions") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(listOfRegions) .addStatement("return $L", "REGIONS") .build(); } private MethodSpec endpointFor() { return MethodSpec.methodBuilder("endpointFor") .addModifiers(Modifier.PUBLIC) .addParameter(serviceEndpointKeyClass(), "key") .addAnnotation(Override.class) .returns(URI.class) .addCode("return $T.endpointFor(", serviceMetadataUtilsClass()) .addCode("$T.hostname(key, HOSTNAMES_BY_REGION, HOSTNAMES_BY_PARTITION), ", serviceMetadataUtilsClass()) .addCode("ENDPOINT_PREFIX, ") .addCode("key.region().id(), ") .addCode("$T.dnsSuffix(key, DNS_SUFFIXES_BY_REGION, DNS_SUFFIXES_BY_PARTITION));", serviceMetadataUtilsClass()) .build(); } private MethodSpec signingRegion() { return MethodSpec.methodBuilder("signingRegion") .addModifiers(Modifier.PUBLIC) .addParameter(serviceEndpointKeyClass(), "key") .addAnnotation(Override.class) .returns(ClassName.get(regionBasePackage, "Region")) .addStatement("return $T.signingRegion(key, SIGNING_REGIONS_BY_REGION, SIGNING_REGIONS_BY_PARTITION)", serviceMetadataUtilsClass()) .build(); } private MethodSpec partitions(TypeName listOfServicePartitionMetadata) { return MethodSpec.methodBuilder("servicePartitions") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(listOfServicePartitionMetadata) .addStatement("return $L", "PARTITIONS") .build(); } private Map<Partition, Service> getServiceData(Partitions partitions) { Map<Partition, Service> serviceData = new TreeMap<>(Comparator.comparing(Partition::getPartition)); partitions.getPartitions() .forEach(p -> p.getServices() .entrySet() .stream() .filter(s -> s.getKey().equalsIgnoreCase(serviceEndpointPrefix)) .forEach(s -> serviceData.put(p, s.getValue()))); return serviceData; } private ClassName serviceEndpointKeyClass() { return ClassName.get(regionBasePackage, "ServiceEndpointKey"); } private ClassName partitionEndpointKeyClass() { return ClassName.get(regionBasePackage, "PartitionEndpointKey"); } private ClassName regionClass() { return ClassName.get(regionBasePackage, "Region"); } private ClassName endpointTagClass() { return ClassName.get(regionBasePackage, "EndpointTag"); } private TypeName byPartitionKeyClass() { return ParameterizedTypeName.get(ClassName.get(Pair.class), ClassName.get(String.class), partitionEndpointKeyClass()); } private ClassName serviceMetadataUtilsClass() { return ClassName.get(regionBasePackage + ".internal.util", "ServiceMetadataUtils"); } }
3,117
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/RegionGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.http.SdkHttpUtils; public class RegionGenerator implements PoetClass { private final Partitions partitions; private final String basePackage; public RegionGenerator(Partitions partitions, String basePackage) { this.partitions = partitions; this.basePackage = basePackage; } @Override public TypeSpec poetClass() { TypeSpec.Builder builder = TypeSpec.classBuilder(className()) .addModifiers(FINAL, PUBLIC) .addJavadoc(documentation()) .addAnnotation(SdkPublicApi.class) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addMethod(MethodSpec.constructorBuilder() .addModifiers(PRIVATE) .addParameter(String.class, "id") .addParameter(boolean.class, "isGlobalRegion") .addStatement("this.id = id") .addStatement("this.isGlobalRegion = isGlobalRegion") .build()); regions(builder); builder.addField(FieldSpec.builder(boolean.class, "isGlobalRegion") .addModifiers(FINAL, PRIVATE) .build()) .addField(FieldSpec.builder(String.class, "id") .addModifiers(FINAL, PRIVATE) .build()) .addMethod(regionOf()) .addMethod(regionOfGlobal()) .addMethod(regionsGetter()) .addMethod(id()) .addMethod(metadata()) .addMethod(isGlobalRegion()) .addMethod(regionToString()); return builder.addType(cache()).build(); } private void regions(TypeSpec.Builder builder) { Set<String> regions = partitions.getPartitions() .stream() .flatMap(p -> p.getRegions().keySet().stream()) .collect(Collectors.toSet()); CodeBlock.Builder regionsArray = CodeBlock.builder() .add("$T.unmodifiableList($T.asList(", Collections.class, Arrays.class); String regionsCodeBlock = regions.stream().map(r -> { builder.addField(FieldSpec.builder(className(), regionName(r)) .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S)", className(), r) .build()); return regionName(r); }).collect(Collectors.joining(", ")); addGlobalRegions(builder); regionsArray.add(regionsCodeBlock + ", ") .add("AWS_GLOBAL, ") .add("AWS_CN_GLOBAL, ") .add("AWS_US_GOV_GLOBAL, ") .add("AWS_ISO_GLOBAL, ") .add("AWS_ISO_B_GLOBAL"); regionsArray.add("))"); TypeName listOfRegions = ParameterizedTypeName.get(ClassName.get(List.class), className()); builder.addField(FieldSpec.builder(listOfRegions, "REGIONS") .addModifiers(PRIVATE, STATIC, FINAL) .initializer(regionsArray.build()).build()); } private void addGlobalRegions(TypeSpec.Builder builder) { builder.addField(FieldSpec.builder(className(), "AWS_GLOBAL") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S, true)", className(), "aws-global") .build()) .addField(FieldSpec.builder(className(), "AWS_CN_GLOBAL") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S, true)", className(), "aws-cn-global") .build()) .addField(FieldSpec.builder(className(), "AWS_US_GOV_GLOBAL") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S, true)", className(), "aws-us-gov-global") .build()) .addField(FieldSpec.builder(className(), "AWS_ISO_GLOBAL") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S, true)", className(), "aws-iso-global") .build()) .addField(FieldSpec.builder(className(), "AWS_ISO_B_GLOBAL") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S, true)", className(), "aws-iso-b-global") .build()); } private String regionName(String region) { return region.replace("-", "_").toUpperCase(Locale.US); } private MethodSpec regionOf() { return MethodSpec.methodBuilder("of") .addModifiers(PUBLIC, STATIC) .addParameter(String.class, "value") .returns(className()) .addStatement("return of($L, false)", "value") .build(); } private MethodSpec regionOfGlobal() { return MethodSpec.methodBuilder("of") .addModifiers(PRIVATE, STATIC) .addParameter(String.class, "value") .addParameter(boolean.class, "isGlobalRegion") .returns(className()) .addStatement("$T.paramNotBlank($L, $S)", Validate.class, "value", "region") .addStatement("$T $L = $T.urlEncode($L)", String.class, "urlEncodedValue", SdkHttpUtils.class, "value") .addStatement("return $L.put($L, $L)", "RegionCache", "urlEncodedValue", "isGlobalRegion") .build(); } private MethodSpec id() { return MethodSpec.methodBuilder("id") .addModifiers(PUBLIC) .returns(String.class) .addStatement("return this.id") .build(); } private MethodSpec metadata() { ClassName regionMetadataClass = ClassName.get("software.amazon.awssdk.regions", "RegionMetadata"); return MethodSpec.methodBuilder("metadata") .addModifiers(PUBLIC) .returns(regionMetadataClass) .addStatement("return $T.of(this)", regionMetadataClass) .build(); } private MethodSpec regionsGetter() { return MethodSpec.methodBuilder("regions") .addModifiers(PUBLIC, STATIC) .returns(ParameterizedTypeName.get(ClassName.get(List.class), className())) .addStatement("return $L", "REGIONS") .build(); } private MethodSpec isGlobalRegion() { return MethodSpec.methodBuilder("isGlobalRegion") .addModifiers(PUBLIC) .returns(boolean.class) .addStatement("return $L", "isGlobalRegion") .build(); } private MethodSpec regionToString() { return MethodSpec.methodBuilder("toString") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(String.class) .addStatement("return $L", "id") .build(); } private TypeSpec cache() { ParameterizedTypeName mapOfStringRegion = ParameterizedTypeName.get(ClassName.get(ConcurrentHashMap.class), ClassName.get(String.class), className()); return TypeSpec.classBuilder("RegionCache") .addModifiers(PRIVATE, STATIC) .addField(FieldSpec.builder(mapOfStringRegion, "VALUES") .addModifiers(PRIVATE, STATIC, FINAL) .initializer("new $T<>()", ConcurrentHashMap.class) .build()) .addMethod(MethodSpec.constructorBuilder().addModifiers(PRIVATE).build()) .addMethod(MethodSpec.methodBuilder("put") .addModifiers(PRIVATE, STATIC) .addParameter(String.class, "value") .addParameter(boolean.class, "isGlobalRegion") .returns(className()) .addStatement("return $L.computeIfAbsent(value, v -> new $T(value, isGlobalRegion))", "VALUES", className()) .build()) .build(); } private CodeBlock documentation() { return CodeBlock.builder() .add("An Amazon Web Services region that hosts a set of Amazon services.") .add(System.lineSeparator()) .add("<p>An instance of this class can be retrieved by referencing one of the static constants defined in" + " this class (eg. {@link Region#US_EAST_1}) or by using the {@link Region#of(String)} method if " + "the region you want is not included in this release of the SDK.</p>") .add(System.lineSeparator()) .add("<p>Each AWS region corresponds to a separate geographical location where a set of Amazon services " + "is deployed. These regions (except for the special {@link #AWS_GLOBAL} and {@link #AWS_CN_GLOBAL}" + " regions) are separate from each other, with their own set of resources. This means a resource " + "created in one region (eg. an SQS queue) is not available in another region.</p>") .add(System.lineSeparator()) .add("<p>To programmatically determine whether a particular service is deployed to a region, you can use " + "the {@code serviceMetadata} method on the service's client interface. Additional metadata about " + "a region can be discovered using {@link RegionMetadata#of(Region)}.</p>") .add(System.lineSeparator()) .add("<p>The {@link Region#id()} will be used as the signing region for all requests to AWS services " + "unless an explicit region override is available in {@link RegionMetadata}. This id will also be " + "used to construct the endpoint for accessing a service unless an explicit endpoint is available " + "for that region in {@link RegionMetadata}.</p>") .build(); } @Override public ClassName className() { return ClassName.get(basePackage, "Region"); } }
3,118
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/RegionMetadataProviderGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.utils.ImmutableMap; public class RegionMetadataProviderGenerator implements PoetClass { private final Partitions partitions; private final String basePackage; private final String regionBasePackage; public RegionMetadataProviderGenerator(Partitions partitions, String basePackage, String regionBasePackage) { this.partitions = partitions; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; } @Override public TypeSpec poetClass() { TypeName mapOfRegionMetadata = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(regionBasePackage, "Region"), ClassName.get(regionBasePackage, "RegionMetadata")); return TypeSpec.classBuilder(className()) .addModifiers(PUBLIC) .addSuperinterface(ClassName.get(regionBasePackage, "RegionMetadataProvider")) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addAnnotation(SdkPublicApi.class) .addModifiers(FINAL) .addField(FieldSpec.builder(mapOfRegionMetadata, "REGION_METADATA") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(regions(partitions)) .build()) .addMethod(getter()) .build(); } @Override public ClassName className() { return ClassName.get(regionBasePackage, "GeneratedRegionMetadataProvider"); } private CodeBlock regions(Partitions partitions) { CodeBlock.Builder builder = CodeBlock.builder().add("$T.<Region, RegionMetadata>builder()", ImmutableMap.class); partitions.getPartitions() .forEach(p -> p.getRegions() .keySet() .forEach(r -> builder.add(".put(Region.$L, new $T())", regionClass(r), regionMetadataClass(r)))); return builder.add(".build()").build(); } private String regionClass(String region) { return region.replace("-", "_").toUpperCase(Locale.US); } private ClassName regionMetadataClass(String region) { return ClassName.get(basePackage, Stream.of(region.split("-")).map(Utils::capitalize).collect(Collectors.joining())); } private MethodSpec getter() { return MethodSpec.methodBuilder("regionMetadata") .addModifiers(PUBLIC) .addParameter(ClassName.get(regionBasePackage, "Region"), "region") .returns(ClassName.get(regionBasePackage, "RegionMetadata")) .addStatement("return $L.get($L)", "REGION_METADATA", "region") .build(); } }
3,119
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/RegionMetadataGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import java.util.Locale; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Partition; public class RegionMetadataGenerator implements PoetClass { private final Partition partition; private final String region; private final String regionDescription; private final String basePackage; private final String regionBasePackage; public RegionMetadataGenerator(Partition partition, String region, String regionDescription, String basePackage, String regionBasePackage) { this.partition = partition; this.region = region; this.regionDescription = regionDescription; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; } @Override public TypeSpec poetClass() { return TypeSpec.classBuilder(className()) .addModifiers(Modifier.PUBLIC) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addAnnotation(SdkPublicApi.class) .addModifiers(FINAL) .addSuperinterface(ClassName.get(regionBasePackage, "RegionMetadata")) .addField(staticFinalField("ID", region)) .addField(staticFinalField("DOMAIN", partition.getDnsSuffix())) .addField(staticFinalField("DESCRIPTION", regionDescription)) .addField(staticFinalField("PARTITION_ID", partition.getPartition())) .addMethod(getter("id", "ID")) .addMethod(getter("domain", "DOMAIN")) .addMethod(getter("description", "DESCRIPTION")) .addMethod(partition()) .build(); } private MethodSpec partition() { ClassName regionMetadataClass = ClassName.get("software.amazon.awssdk.regions", "PartitionMetadata"); return MethodSpec.methodBuilder("partition") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(regionMetadataClass) .addStatement("return $T.of(PARTITION_ID)", regionMetadataClass) .build(); } @Override public ClassName className() { return ClassName.get(basePackage, Stream.of(region.split("-")).map(Utils::capitalize).collect(Collectors.joining())); } private FieldSpec staticFinalField(String fieldName, String fieldValue) { return FieldSpec.builder(String.class, fieldName) .addModifiers(PRIVATE, FINAL, STATIC) .initializer("$S", fieldValue) .build(); } private MethodSpec getter(String getterName, String fieldName) { return MethodSpec.methodBuilder(getterName) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(String.class) .addStatement("return $L", fieldName.toUpperCase(Locale.US)) .build(); } }
3,120
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/PartitionMetadataGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import static java.util.Collections.emptyList; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Collection; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Partition; import software.amazon.awssdk.utils.ImmutableMap; public class PartitionMetadataGenerator implements PoetClass { private final Partition partition; private final String basePackage; private final String regionBasePackage; public PartitionMetadataGenerator(Partition partition, String basePackage, String regionBasePackage) { this.partition = partition; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; } @Override public TypeSpec poetClass() { TypeName mapByPartitionEndpointKey = ParameterizedTypeName.get(ClassName.get(Map.class), partitionEndpointKeyClass(), ClassName.get(String.class)); return TypeSpec.classBuilder(className()) .addModifiers(FINAL, PUBLIC) .addSuperinterface(ClassName.get(regionBasePackage, "PartitionMetadata")) .addAnnotation(SdkPublicApi.class) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addField(FieldSpec.builder(mapByPartitionEndpointKey, "DNS_SUFFIXES") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(dnsSuffixes()) .build()) .addField(FieldSpec.builder(mapByPartitionEndpointKey, "HOSTNAMES") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(hostnames()) .build()) .addField(FieldSpec.builder(String.class, "ID") .addModifiers(PRIVATE, FINAL, STATIC) .initializer("$S", partition.getPartition()) .build()) .addField(FieldSpec.builder(String.class, "NAME") .addModifiers(PRIVATE, FINAL, STATIC) .initializer("$S", partition.getPartitionName()) .build()) .addField(FieldSpec.builder(String.class, "REGION_REGEX") .addModifiers(PRIVATE, FINAL, STATIC) .initializer("$S", partition.getRegionRegex()) .build()) .addMethod(getter("id", "ID")) .addMethod(getter("name", "NAME")) .addMethod(getter("regionRegex", "REGION_REGEX")) .addMethod(dnsSuffixGetter()) .addMethod(hostnameGetter()) .build(); } private CodeBlock dnsSuffixes() { CodeBlock.Builder builder = CodeBlock.builder() .add("$T.<$T, $T>builder()", ImmutableMap.class, partitionEndpointKeyClass(), String.class); builder.add(".put(") .add(partitionEndpointKey(emptyList())) .add(", $S)", partition.getDnsSuffix()); if (partition.getDefaults() != null) { partition.getDefaults().getVariants().forEach(variant -> { if (variant.getDnsSuffix() != null) { builder.add(".put(") .add(partitionEndpointKey(variant.getTags())) .add(", $S)", variant.getDnsSuffix()); } }); } return builder.add(".build()").build(); } private CodeBlock hostnames() { CodeBlock.Builder builder = CodeBlock.builder() .add("$T.<$T, $T>builder()", ImmutableMap.class, partitionEndpointKeyClass(), String.class); if (partition.getDefaults() != null) { builder.add(".put(") .add(partitionEndpointKey(emptyList())) .add(", $S)", partition.getDefaults().getHostname()); partition.getDefaults().getVariants().forEach(variant -> { if (variant.getHostname() != null) { builder.add(".put(") .add(partitionEndpointKey(variant.getTags())) .add(", $S)", variant.getHostname()); } }); } return builder.add(".build()").build(); } private MethodSpec dnsSuffixGetter() { return MethodSpec.methodBuilder("dnsSuffix") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(String.class) .addParameter(partitionEndpointKeyClass(), "key") .addStatement("return DNS_SUFFIXES.get(key)") .build(); } private MethodSpec hostnameGetter() { return MethodSpec.methodBuilder("hostname") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(String.class) .addParameter(partitionEndpointKeyClass(), "key") .addStatement("return HOSTNAMES.get(key)") .build(); } @Override public ClassName className() { return ClassName.get(basePackage, Stream.of(partition.getPartition().split("-")) .map(Utils::capitalize) .collect(Collectors.joining()) + "PartitionMetadata"); } private MethodSpec getter(String methodName, String field) { return MethodSpec.methodBuilder(methodName) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(String.class) .addStatement("return $L", field) .build(); } private CodeBlock partitionEndpointKey(Collection<String> tags) { CodeBlock.Builder result = CodeBlock.builder(); result.add("$T.builder()", partitionEndpointKeyClass()); if (!tags.isEmpty()) { CodeBlock tagsParameter = tags.stream() .map(tag -> CodeBlock.of("$T.of($S)", endpointTagClass(), tag)) .collect(CodeBlock.joining(", ")); result.add(".tags(").add(tagsParameter).add(")"); } result.add(".build()"); return result.build(); } private ClassName endpointTagClass() { return ClassName.get(regionBasePackage, "EndpointTag"); } private ClassName partitionEndpointKeyClass() { return ClassName.get(regionBasePackage, "PartitionEndpointKey"); } }
3,121
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/PartitionMetadataProviderGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.utils.ImmutableMap; public class PartitionMetadataProviderGenerator implements PoetClass { private final Partitions partitions; private final String basePackage; private final String regionBasePackage; public PartitionMetadataProviderGenerator(Partitions partitions, String basePackage, String regionBasePackage) { this.partitions = partitions; this.basePackage = basePackage; this.regionBasePackage = regionBasePackage; } @Override public TypeSpec poetClass() { TypeName mapOfPartitionMetadata = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), ClassName.get(regionBasePackage, "PartitionMetadata")); return TypeSpec.classBuilder(className()) .addModifiers(PUBLIC) .addSuperinterface(ClassName.get(regionBasePackage, "PartitionMetadataProvider")) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addAnnotation(SdkPublicApi.class) .addModifiers(FINAL) .addField(FieldSpec.builder(mapOfPartitionMetadata, "PARTITION_METADATA") .addModifiers(PRIVATE, FINAL, STATIC) .initializer(partitions(partitions)) .build()) .addMethod(getter()) .addMethod(partitionMetadata()) .build(); } @Override public ClassName className() { return ClassName.get(regionBasePackage, "GeneratedPartitionMetadataProvider"); } private CodeBlock partitions(Partitions partitions) { CodeBlock.Builder builder = CodeBlock.builder().add("$T.<String, PartitionMetadata>builder()", ImmutableMap.class); partitions.getPartitions() .forEach(p -> builder.add(".put($S, new $T())", p.getPartition(), partitionMetadataClass(p.getPartition()))); return builder.add(".build()").build(); } private ClassName partitionMetadataClass(String partition) { return ClassName.get(basePackage, Stream.of(partition.split("-")) .map(Utils::capitalize) .collect(Collectors.joining()) + "PartitionMetadata"); } private MethodSpec partitionMetadata() { return MethodSpec.methodBuilder("partitionMetadata") .addModifiers(PUBLIC) .addParameter(ClassName.get(regionBasePackage, "Region"), "region") .returns(ClassName.get(regionBasePackage, "PartitionMetadata")) .addStatement("return $L.values().stream().filter(p -> $L.id().matches(p.regionRegex()))" + ".findFirst().orElse(new $L())", "PARTITION_METADATA", "region", "AwsPartitionMetadata") .build(); } private MethodSpec getter() { return MethodSpec.methodBuilder("partitionMetadata") .addModifiers(PUBLIC) .addParameter(String.class, "partition") .returns(ClassName.get(regionBasePackage, "PartitionMetadata")) .addStatement("return $L.get($L)", "PARTITION_METADATA", "partition") .build(); } }
3,122
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/EndpointTagGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.codegen.lite.regions.model.Endpoint; import software.amazon.awssdk.codegen.lite.regions.model.Partition; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; import software.amazon.awssdk.codegen.lite.regions.model.Service; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.internal.CodegenNamingUtils; public class EndpointTagGenerator implements PoetClass { private final Partitions partitions; private final String basePackage; public EndpointTagGenerator(Partitions partitions, String basePackage) { this.partitions = partitions; this.basePackage = basePackage; } @Override public TypeSpec poetClass() { TypeSpec.Builder builder = TypeSpec.classBuilder(className()) .addModifiers(FINAL, PUBLIC) .addJavadoc(documentation()) .addAnnotation(SdkPublicApi.class) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addMethod(MethodSpec.constructorBuilder() .addModifiers(PRIVATE) .addParameter(String.class, "id") .addStatement("this.id = id") .build()); endpointTags(builder); builder.addField(FieldSpec.builder(String.class, "id") .addModifiers(FINAL, PRIVATE) .build()) .addMethod(tagOf()) .addMethod(tagGetter()) .addMethod(id()) .addMethod(tagToString()); return builder.addType(cache()).build(); } private void endpointTags(TypeSpec.Builder builder) { Stream<Endpoint> endpointsFromPartitions = partitions.getPartitions().stream().map(Partition::getDefaults); Stream<Endpoint> endpointsFromServices = partitions.getPartitions().stream() .flatMap(p -> p.getServices().values().stream()) .flatMap(s -> s.getEndpoints().values().stream()); Stream<Endpoint> endpointsFromServiceDefaults = partitions.getPartitions().stream() .flatMap(p -> p.getServices().values().stream()) .map(Service::getDefaults) .filter(Objects::nonNull); Set<String> allTags = Stream.concat(endpointsFromPartitions, Stream.concat(endpointsFromServices, endpointsFromServiceDefaults)) .flatMap(e -> e.getVariants().stream()) .flatMap(v -> v.getTags().stream()) .collect(Collectors.toCollection(TreeSet::new)); // Add each tag as a separate entry in the endpoint tags allTags.forEach(tag -> builder.addField(FieldSpec.builder(className(), enumValueForTagId(tag)) .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$T.of($S)", className(), tag) .build())); String tagsCodeBlock = allTags.stream() .map(this::enumValueForTagId) .collect(Collectors.joining(", ")); CodeBlock initializer = CodeBlock.builder() .add("$T.unmodifiableList($T.asList(", Collections.class, Arrays.class) .add(tagsCodeBlock) .add("))") .build(); TypeName listOfTags = ParameterizedTypeName.get(ClassName.get(List.class), className()); builder.addField(FieldSpec.builder(listOfTags, "ENDPOINT_TAGS") .addModifiers(PRIVATE, STATIC, FINAL) .initializer(initializer) .build()); } private String enumValueForTagId(String tag) { return Stream.of(CodegenNamingUtils.splitOnWordBoundaries(tag)) .map(StringUtils::upperCase) .collect(Collectors.joining("_")); } private MethodSpec tagOf() { return MethodSpec.methodBuilder("of") .addModifiers(PUBLIC, STATIC) .addParameter(String.class, "id") .returns(className()) .addStatement("return EndpointTagCache.put($L)", "id") .build(); } private MethodSpec id() { return MethodSpec.methodBuilder("id") .addModifiers(PUBLIC) .returns(String.class) .addStatement("return this.id") .build(); } private MethodSpec tagGetter() { return MethodSpec.methodBuilder("endpointTags") .addModifiers(PUBLIC, STATIC) .returns(ParameterizedTypeName.get(ClassName.get(List.class), className())) .addStatement("return $L", "ENDPOINT_TAGS") .build(); } private MethodSpec tagToString() { return MethodSpec.methodBuilder("toString") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(String.class) .addStatement("return $L", "id") .build(); } private TypeSpec cache() { ParameterizedTypeName mapOfStringTags = ParameterizedTypeName.get(ClassName.get(ConcurrentHashMap.class), ClassName.get(String.class), className()); return TypeSpec.classBuilder("EndpointTagCache") .addModifiers(PRIVATE, STATIC) .addField(FieldSpec.builder(mapOfStringTags, "IDS") .addModifiers(PRIVATE, STATIC, FINAL) .initializer("new $T<>()", ConcurrentHashMap.class) .build()) .addMethod(MethodSpec.constructorBuilder().addModifiers(PRIVATE).build()) .addMethod(MethodSpec.methodBuilder("put") .addModifiers(PRIVATE, STATIC) .addParameter(String.class, "id") .returns(className()) .addStatement("return $L.computeIfAbsent(id, $T::new)", "IDS", className()) .build()) .build(); } private CodeBlock documentation() { return CodeBlock.builder() .add("A tag applied to endpoints to specify that they're to be used in certain contexts. For example, " + "FIPS tags are applied to endpoints discussed here: https://aws.amazon.com/compliance/fips/ and " + "DUALSTACK tags are applied to endpoints that can return IPv6 addresses.") .build(); } @Override public ClassName className() { return ClassName.get(basePackage, "EndpointTag"); } }
3,123
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/RegionMetadataLoader.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions; import com.fasterxml.jackson.jr.ob.JSON; import java.io.File; import java.io.IOException; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.lite.regions.model.Partitions; /** * Loads all the partition files into memory. */ @SdkInternalApi public final class RegionMetadataLoader { private RegionMetadataLoader() { } public static Partitions build(File path) { return loadPartitionFromStream(path, path.toString()); } private static Partitions loadPartitionFromStream(File stream, String location) { try { return JSON.std.with(JSON.Feature.USE_IS_GETTERS) .beanFrom(Partitions.class, stream); } catch (IOException | RuntimeException e) { throw new RuntimeException("Error while loading partitions file from " + location, e); } } }
3,124
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/EndpointVariant.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class EndpointVariant { private String dnsSuffix; private String hostname; private List<String> tags; public String getDnsSuffix() { return dnsSuffix; } @JsonProperty(value = "dnsSuffix") public void setDnsSuffix(String dnsSuffix) { this.dnsSuffix = dnsSuffix; } public String getHostname() { return hostname; } @JsonProperty(value = "hostname") public void setHostname(String hostname) { this.hostname = hostname; } public List<String> getTags() { return tags; } @JsonProperty(value = "tags") public void setTags(List<String> tags) { this.tags = tags; } }
3,125
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/Partitions.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * Metadata of all partitions. */ @SdkInternalApi public final class Partitions { /** * the version of json schema for the partition metadata. */ private String version; /** * list of partitions. */ private List<Partition> partitions; public Partitions() { } public Partitions(@JsonProperty(value = "version") String version, @JsonProperty(value = "partitions") List<Partition> partitions) { this.version = Validate.paramNotNull(version, "version"); this.partitions = Validate.paramNotNull(partitions, "version"); } /** * returns the version of the json schema for the partition metadata document. */ public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } /** * returns the list of all partitions loaded from the partition metadata document. */ public List<Partition> getPartitions() { return partitions; } public void setPartitions(List<Partition> partitions) { this.partitions = partitions; } }
3,126
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/PartitionRegion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * Metadata about a region in partition. */ @SdkInternalApi public final class PartitionRegion { /** * description of the region. */ private String description; public PartitionRegion() { } public PartitionRegion(@JsonProperty(value = "description") String description) { this.description = Validate.notNull(description, "Region description"); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
3,127
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/CredentialScope.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions.model; import software.amazon.awssdk.annotations.SdkInternalApi; /** * credential scope associated with an endpoint. */ @SdkInternalApi public final class CredentialScope { /** * region string to be used when signing a request for an endpoint. */ private String region; /** * service name string to be used when signing a request for an endpoint */ private String service; /** * Returns the region string to be used when signing a request for an * endpoint. */ public String getRegion() { return region; } /** * Sets the region string to be used when signing a request for an * endpoint. */ public void setRegion(String region) { this.region = region; } /** * Returns the service name string to be used when signing a request for an * endpoint. */ public String getService() { return service; } /** * Sets the service name string to be used when signing a request for an * endpoint. */ public void setService(String service) { this.service = service; } }
3,128
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/Service.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * Endpoint configuration for a service in a partition. */ @SdkInternalApi public final class Service { /** * endpoint configuration for every region in a partition. */ private Map<String, Endpoint> endpoints; /** * default endpoint configuration for a service across all regions in the * partition */ private Endpoint defaults; /** * the region name if the service is enabled partition wide. */ private String partitionEndpoint; /** * Returns true if the service is regionalized. */ private Boolean isRegionalized; public Service() { } public Service(@JsonProperty(value = "endpoints") Map<String, Endpoint> endpoints) { this.endpoints = Validate.paramNotNull(endpoints, "endpoints"); } /** * Returns the endpoints configuration for all regions in a partition * that service supports. */ public Map<String, Endpoint> getEndpoints() { return endpoints; } public void setEndpoints(Map<String, Endpoint> endpoints) { this.endpoints = endpoints; } /** * returns the default endpoints configuration for all regions in a * partition. */ public Endpoint getDefaults() { return defaults; } /** * Sets the default endpoints configuration for all regions in a * partition. */ public void setDefaults(Endpoint defaults) { this.defaults = defaults; } /** * returns the region name if the service is enabled partition wide. */ public String getPartitionEndpoint() { return partitionEndpoint; } /** * sets the region name if the service is enabled partition wide. */ @JsonProperty(value = "partitionEndpoint") public void setPartitionEndpoint(String partitionEndpoint) { this.partitionEndpoint = partitionEndpoint; } /** * returns true if the service is regionalized. */ public Boolean isRegionalized() { return isRegionalized; } /** * sets the regionalized property for a service.. */ @JsonProperty(value = "isRegionalized") public void setIsRegionalized(Boolean regionalized) { isRegionalized = regionalized; } /** * A convenient method that returns true if a service has a partition * wide endpoint available. */ public boolean isPartitionWideEndpointAvailable() { return this.partitionEndpoint != null; } }
3,129
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/Endpoint.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Endpoint configuration. */ @SdkInternalApi public final class Endpoint implements Cloneable { private static final String HTTP = "http"; private static final String HTTPS = "https"; /** * endpoint string. */ private String hostname; /** * credential scope for the endpoint. */ private CredentialScope credentialScope; /** * supported schemes for the endpoint. */ private List<String> protocols; /** * supported signature versions of the endpoint. */ private List<String> signatureVersions; /** * ssl common name for the endpoint. */ private String sslCommonName; private List<EndpointVariant> variants = new ArrayList<>(); private Boolean deprecated; public Endpoint() { } /** * Merges the given endpoints and returns the merged one. */ public Endpoint merge(Endpoint higher) { if (higher == null) { higher = new Endpoint(); } Endpoint merged = this.clone(); merged.setCredentialScope(higher.getCredentialScope() != null ? higher.getCredentialScope() : merged.getCredentialScope()); merged.setHostname(higher.getHostname() != null ? higher.getHostname() : merged.getHostname()); merged.setSslCommonName(higher.getSslCommonName() != null ? higher.getSslCommonName() : merged.getSslCommonName()); merged.setProtocols(higher.getProtocols() != null ? higher.getProtocols() : merged.getProtocols()); merged.setSignatureVersions(higher.getSignatureVersions() != null ? higher.getSignatureVersions() : merged.getSignatureVersions()); return merged; } /** * returns the endpoint string. */ public String getHostname() { return hostname; } /** * sets the endpoint string. */ @JsonProperty(value = "hostname") public void setHostname(String hostname) { this.hostname = hostname; } /** * returns credential scope for the endpoint. */ public CredentialScope getCredentialScope() { return credentialScope; } /** * sets the credential scope for the endpoint. */ @JsonProperty(value = "credentialScope") public void setCredentialScope(CredentialScope credentialScope) { this.credentialScope = credentialScope; } /** * returns the supported schemes for the endpoint. */ public List<String> getProtocols() { return protocols; } /** * sets the supported schemes for the endpoint. */ public void setProtocols(List<String> protocols) { this.protocols = protocols; } /** * returns the supported signature versions of the endpoint. */ public List<String> getSignatureVersions() { return signatureVersions; } /** * returns the supported signature versions of the endpoint. */ @JsonProperty(value = "signatureVersions") public void setSignatureVersions(List<String> signatureVersions) { this.signatureVersions = signatureVersions; } /** * returns the ssl common name for the endpoint. */ public String getSslCommonName() { return sslCommonName; } /** * sets the ssl common name for the endpoint. */ @JsonProperty(value = "sslCommonName") public void setSslCommonName(String sslCommonName) { this.sslCommonName = sslCommonName; } /** * A convenient method that returns true if the endpoint support HTTPS * scheme. Returns false otherwise. */ public boolean hasHttpsSupport() { return isProtocolSupported(HTTPS); } /** * A convenient method that returns true if the endpoint support HTTP * scheme. Returns false otherwise. */ public boolean hasHttpSupport() { return isProtocolSupported(HTTP); } private boolean isProtocolSupported(String protocol) { return protocols != null && protocols.contains(protocol); } @Override protected Endpoint clone() { try { return (Endpoint) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() even though we're Cloneable!", e); } } public List<EndpointVariant> getVariants() { return variants; } public void setVariants(List<EndpointVariant> variants) { this.variants = variants; } public Boolean getDeprecated() { return deprecated; } public void setDeprecated(Boolean deprecated) { this.deprecated = deprecated; } }
3,130
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/regions/model/Partition.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.regions.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * This class models a AWS partition and contains all metadata about it. */ @SdkInternalApi public final class Partition { /** * The name of the partition. */ private String partition; /** * Supported regions. */ private Map<String, PartitionRegion> regions; /** * Supported services; */ private Map<String, Service> services; /** * description of the partition. */ private String partitionName; /** * dns suffix for the endpoints in the partition. */ private String dnsSuffix; /** * region name regex for regions in the partition. */ private String regionRegex; /** * default endpoint configuration. */ private Endpoint defaults; public Partition() { } public Partition(@JsonProperty(value = "partition") String partition, @JsonProperty(value = "regions") Map<String, PartitionRegion> regions, @JsonProperty(value = "services") Map<String, Service> services) { this.partition = Validate.paramNotNull(partition, "Partition"); this.regions = regions; this.services = services; } /** * Returns the name of the partition. */ public String getPartition() { return partition; } public void setPartition(String partition) { this.partition = partition; } /** * Returns the description of the partition. */ public String getPartitionName() { return partitionName; } /** * Sets the description of the partition. */ public void setPartitionName(String partitionName) { this.partitionName = partitionName; } /** * Returns the dns suffix of the partition. */ public String getDnsSuffix() { return dnsSuffix; } /** * Sets the dns suffix of the partition. */ public void setDnsSuffix(String dnsSuffix) { this.dnsSuffix = dnsSuffix; } /** * Returns the regex for the regions in the partition. */ public String getRegionRegex() { return regionRegex; } /** * Sets the regex for the regions in the partition. */ public void setRegionRegex(String regionRegex) { this.regionRegex = regionRegex; } /** * Returns the default endpoint configuration of the partition. */ public Endpoint getDefaults() { return defaults; } /** * Sets the default endpoint configuration of the partition. */ public void setDefaults(Endpoint defaults) { this.defaults = defaults; } /** * Returns the set of regions associated with the partition. */ public Map<String, PartitionRegion> getRegions() { return regions; } public void setRegions(Map<String, PartitionRegion> regions) { this.regions = regions; } /** * Returns the set of services supported by the partition. */ public Map<String, Service> getServices() { return services; } public void setServices(Map<String, Service> services) { this.services = services; } /** * Returns true if the region is explicitly configured in the partition * or if the region matches the {@link #regionRegex} of the partition. */ public boolean hasRegion(String region) { return regions.containsKey(region) || matchesRegionRegex(region) || hasServiceEndpoint(region); } private boolean matchesRegionRegex(String region) { Pattern p = Pattern.compile(regionRegex); return p.matcher(region).matches(); } @Deprecated private boolean hasServiceEndpoint(String endpoint) { for (Service s : services.values()) { if (s.getEndpoints().containsKey(endpoint)) { return true; } } return false; } }
3,131
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/defaultsmode/DefaultsModeGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.defaultsmode; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.util.Locale; import java.util.Map; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.internal.EnumUtils; /** * Generates DefaultsMode enum */ public class DefaultsModeGenerator implements PoetClass { private static final String VALUE = "value"; private static final String VALUE_MAP = "VALUE_MAP"; private final String basePackage; private final DefaultConfiguration configuration; public DefaultsModeGenerator(String basePackage, DefaultConfiguration configuration) { this.basePackage = basePackage; this.configuration = configuration; } @Override public TypeSpec poetClass() { TypeSpec.Builder builder = TypeSpec.enumBuilder(className()) .addField(valueMapField()) .addField(String.class, VALUE, Modifier.PRIVATE, Modifier.FINAL) .addModifiers(PUBLIC) .addJavadoc(documentation()) .addAnnotation(SdkPublicApi.class) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember(VALUE, "$S", "software.amazon.awssdk:codegen") .build()) .addMethod(fromValueSpec()) .addMethod(toStringBuilder().addStatement("return $T.valueOf($N)", String.class, VALUE).build()) .addMethod(createConstructor()); builder.addEnumConstant("LEGACY", enumValueTypeSpec("legacy", javaDocForMode("legacy"))); configuration.modeDefaults().keySet().forEach(k -> { String enumKey = sanitizeEnum(k); builder.addEnumConstant(enumKey, enumValueTypeSpec(k, javaDocForMode(k))); }); builder.addEnumConstant("AUTO", enumValueTypeSpec("auto", javaDocForMode("auto"))); return builder.build(); } @Override public ClassName className() { return ClassName.get(basePackage, "DefaultsMode"); } private TypeSpec enumValueTypeSpec(String value, String documentation) { return TypeSpec.anonymousClassBuilder("$S", value) .addJavadoc(documentation) .build(); } private FieldSpec valueMapField() { ParameterizedTypeName mapType = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), className()); return FieldSpec.builder(mapType, VALUE_MAP) .addModifiers(PRIVATE, STATIC, FINAL) .initializer("$1T.uniqueIndex($2T.class, $2T::toString)", EnumUtils.class, className()) .build(); } private String sanitizeEnum(String str) { return str.replace('-', '_').toUpperCase(Locale.US); } private String javaDocForMode(String mode) { return configuration.modesDocumentation().getOrDefault(mode, ""); } private CodeBlock documentation() { CodeBlock.Builder builder = CodeBlock.builder() .add("A defaults mode determines how certain default configuration options are " + "resolved in " + "the SDK. " + "Based on the provided " + "mode, the SDK will vend sensible default values tailored to the mode for " + "the following settings:") .add(System.lineSeparator()); builder.add("<ul>"); configuration.configurationDocumentation().forEach((k, v) -> { builder.add("<li>" + k + ": " + v + "</li>"); }); builder.add("</ul>").add(System.lineSeparator()); builder.add("<p>All options above can be configured by users, and the overridden value will take precedence.") .add("<p><b>Note:</b> for any mode other than {@link #LEGACY}, the vended default values might change " + "as best practices may evolve. As a result, it is encouraged to perform testing when upgrading the SDK if" + " you are using a mode other than {@link #LEGACY}") .add(System.lineSeparator()); return builder.add("<p>While the {@link #LEGACY} defaults mode is specific to Java, other modes are " + "standardized across " + "all of the AWS SDKs</p>") .add(System.lineSeparator()) .add("<p>The defaults mode can be configured:") .add(System.lineSeparator()) .add("<ol>") .add("<li>Directly on a client via {@code AwsClientBuilder.Builder#defaultsMode" + "(DefaultsMode)}.</li>") .add(System.lineSeparator()) .add("<li>On a configuration profile via the \"defaults_mode\" profile file property.</li>") .add(System.lineSeparator()) .add("<li>Globally via the \"aws.defaultsMode\" system property.</li>") .add("<li>Globally via the \"AWS_DEFAULTS_MODE\" environment variable.</li>") .add("</ol>") .build(); } private MethodSpec fromValueSpec() { return MethodSpec.methodBuilder("fromValue") .returns(className()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addJavadoc("Use this in place of valueOf to convert the raw string returned by the service into the " + "enum value.\n\n" + "@param $N real value\n" + "@return $T corresponding to the value\n", VALUE, className()) .addParameter(String.class, VALUE) .addStatement("$T.paramNotNull(value, $S)", Validate.class, VALUE) .beginControlFlow("if (!VALUE_MAP.containsKey(value))") .addStatement("throw new IllegalArgumentException($S + value)", "The provided value is not a" + " valid " + "defaults mode ") .endControlFlow() .addStatement("return $N.get($N)", VALUE_MAP, VALUE) .build(); } private MethodSpec createConstructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(String.class, VALUE) .addStatement("this.$1N = $1N", VALUE) .build(); } private static MethodSpec.Builder toStringBuilder() { return MethodSpec.methodBuilder("toString") .returns(String.class) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class); } }
3,132
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/defaultsmode/DefaultsLoader.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.defaultsmode; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor; import software.amazon.awssdk.utils.Logger; /** * Loads sdk-default-configuration.json into memory. It filters out unsupported configuration options from the file */ @SdkInternalApi public final class DefaultsLoader { private static final Logger log = Logger.loggerFor(DefaultsLoader.class); private static final Set<String> UNSUPPORTED_OPTIONS = new HashSet<>(); static { UNSUPPORTED_OPTIONS.add("stsRegionalEndpoints"); } private DefaultsLoader() { } public static DefaultConfiguration load(File path) { return loadDefaultsFromFile(path); } private static DefaultConfiguration loadDefaultsFromFile(File path) { DefaultConfiguration defaultsResolution = new DefaultConfiguration(); Map<String, Map<String, String>> resolvedDefaults = new HashMap<>(); try (FileInputStream fileInputStream = new FileInputStream(path)) { JsonNodeParser jsonNodeParser = JsonNodeParser.builder().build(); Map<String, JsonNode> sdkDefaultConfiguration = jsonNodeParser.parse(fileInputStream) .asObject(); Map<String, JsonNode> base = sdkDefaultConfiguration.get("base").asObject(); Map<String, JsonNode> modes = sdkDefaultConfiguration.get("modes").asObject(); modes.forEach((mode, modifiers) -> applyModificationToOneMode(resolvedDefaults, base, mode, modifiers)); Map<String, JsonNode> documentation = sdkDefaultConfiguration.get("documentation").asObject(); Map<String, JsonNode> modesDocumentation = documentation.get("modes").asObject(); Map<String, JsonNode> configDocumentation = documentation.get("configuration").asObject(); defaultsResolution.modesDocumentation( modesDocumentation.entrySet() .stream() .collect(HashMap::new, (m, e) -> m.put(e.getKey(), e.getValue().asString()), Map::putAll)); defaultsResolution.configurationDocumentation( configDocumentation.entrySet() .stream() .filter(e -> !UNSUPPORTED_OPTIONS.contains(e.getKey())) .collect(HashMap::new, (m, e) -> m.put(e.getKey(), e.getValue().asString()), Map::putAll)); } catch (IOException e) { throw new RuntimeException(e); } defaultsResolution.modeDefaults(resolvedDefaults); return defaultsResolution; } private static void applyModificationToOneConfigurationOption(Map<String, String> resolvedDefaultsForCurrentMode, String option, JsonNode modifier) { String resolvedValue; String baseValue = resolvedDefaultsForCurrentMode.get(option); if (UNSUPPORTED_OPTIONS.contains(option)) { return; } Map<String, JsonNode> modifierMap = modifier.asObject(); if (modifierMap.size() != 1) { throw new IllegalStateException("More than one modifier exists for option " + option); } String modifierString = modifierMap.keySet().iterator().next(); switch (modifierString) { case "override": resolvedValue = modifierMap.get("override").visit(new StringJsonNodeVisitor()); break; case "multiply": resolvedValue = processMultiply(baseValue, modifierMap); break; case "add": resolvedValue = processAdd(baseValue, modifierMap); break; default: throw new UnsupportedOperationException("Unsupported modifier: " + modifierString); } resolvedDefaultsForCurrentMode.put(option, resolvedValue); } private static void applyModificationToOneMode(Map<String, Map<String, String>> resolvedDefaults, Map<String, JsonNode> base, String mode, JsonNode modifiers) { log.info(() -> "Apply modification for mode: " + mode); Map<String, String> resolvedDefaultsForCurrentMode = base.entrySet().stream().filter(e -> !UNSUPPORTED_OPTIONS.contains(e.getKey())) .collect(HashMap::new, (m, e) -> m.put(e.getKey(), e.getValue().visit(new StringJsonNodeVisitor())), Map::putAll); // Iterate the configuration options and apply modification. modifiers.asObject().forEach((option, modifier) -> applyModificationToOneConfigurationOption( resolvedDefaultsForCurrentMode, option, modifier)); resolvedDefaults.put(mode, resolvedDefaultsForCurrentMode); } private static String processAdd(String baseValue, Map<String, JsonNode> modifierMap) { String resolvedValue; String add = modifierMap.get("add").asNumber(); int parsedAdd = Integer.parseInt(add); int number = Math.addExact(Integer.parseInt(baseValue), parsedAdd); resolvedValue = String.valueOf(number); return resolvedValue; } private static String processMultiply(String baseValue, Map<String, JsonNode> modifierMap) { String resolvedValue; String multiply = modifierMap.get("multiply").asNumber(); double parsedValue = Double.parseDouble(multiply); double resolvedNumber = Integer.parseInt(baseValue) * parsedValue; int castValue = (int) resolvedNumber; if (castValue != resolvedNumber) { throw new IllegalStateException("The transformed value must be be a float number: " + castValue); } resolvedValue = String.valueOf(castValue); return resolvedValue; } private static final class StringJsonNodeVisitor implements JsonNodeVisitor<String> { @Override public String visitNull() { throw new IllegalStateException("Invalid type encountered"); } @Override public String visitBoolean(boolean b) { throw new IllegalStateException("Invalid type (boolean) encountered " + b); } @Override public String visitNumber(String s) { return s; } @Override public String visitString(String s) { return s; } @Override public String visitArray(List<JsonNode> list) { throw new IllegalStateException("Invalid type (list) encountered: " + list); } @Override public String visitObject(Map<String, JsonNode> map) { throw new IllegalStateException("Invalid type (map) encountered: " + map); } @Override public String visitEmbeddedObject(Object o) { throw new IllegalStateException("Invalid type (embedded) encountered: " + o); } } }
3,133
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/defaultsmode/DefaultsModeConfigurationGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.defaultsmode; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.util.EnumMap; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.lite.PoetClass; import software.amazon.awssdk.utils.AttributeMap; /** * Generates DefaultsModeConfiguration class that contains default options for each mode */ public class DefaultsModeConfigurationGenerator implements PoetClass { private static final String DEFAULT_CONFIG_BY_MODE_ENUM_MAP = "DEFAULT_CONFIG_BY_MODE"; private static final String DEFAULT_HTTP_CONFIG_BY_MODE_ENUM_MAP = "DEFAULT_HTTP_CONFIG_BY_MODE"; private static final String DEFAULTS_VAR_SUFFIX = "_DEFAULTS"; private static final String HTTP_DEFAULTS_VAR_SUFFIX = "_HTTP_DEFAULTS"; private static final Map<String, OptionMetadata> CONFIGURATION_MAPPING = new HashMap<>(); private static final Map<String, OptionMetadata> HTTP_CONFIGURATION_MAPPING = new HashMap<>(); private static final String CONNECT_TIMEOUT_IN_MILLIS = "connectTimeoutInMillis"; private static final String TLS_NEGOTIATION_TIMEOUT_IN_MILLIS = "tlsNegotiationTimeoutInMillis"; private static final String S3_US_EAST_1_REGIONAL_ENDPOINTS = "s3UsEast1RegionalEndpoints"; private final String basePackage; private final String defaultsModeBase; private final DefaultConfiguration configuration; static { HTTP_CONFIGURATION_MAPPING.put(CONNECT_TIMEOUT_IN_MILLIS, new OptionMetadata(ClassName.get("java.time", "Duration"), ClassName.get("software.amazon.awssdk.http", "SdkHttpConfigurationOption", "CONNECTION_TIMEOUT"))); HTTP_CONFIGURATION_MAPPING.put(TLS_NEGOTIATION_TIMEOUT_IN_MILLIS, new OptionMetadata(ClassName.get("java.time", "Duration"), ClassName.get("software.amazon.awssdk.http", "SdkHttpConfigurationOption", "TLS_NEGOTIATION_TIMEOUT"))); CONFIGURATION_MAPPING.put("retryMode", new OptionMetadata(ClassName.get("software.amazon.awssdk.core.retry", "RetryMode" ), ClassName.get("software.amazon.awssdk.core.client.config", "SdkClientOption", "DEFAULT_RETRY_MODE"))); CONFIGURATION_MAPPING.put(S3_US_EAST_1_REGIONAL_ENDPOINTS, new OptionMetadata(ClassName.get(String.class), ClassName.get("software.amazon.awssdk.regions", "ServiceMetadataAdvancedOption", "DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT"))); } public DefaultsModeConfigurationGenerator(String basePackage, String defaultsModeBase, DefaultConfiguration configuration) { this.basePackage = basePackage; this.configuration = configuration; this.defaultsModeBase = defaultsModeBase; } @Override public TypeSpec poetClass() { TypeSpec.Builder builder = TypeSpec.classBuilder(className()) .addModifiers(PUBLIC, FINAL) .addJavadoc(documentation()) .addAnnotation(SdkInternalApi.class) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build()) .addMethod(defaultConfigMethod(DEFAULT_CONFIG_BY_MODE_ENUM_MAP, "defaultConfig")) .addMethod(defaultConfigMethod(DEFAULT_HTTP_CONFIG_BY_MODE_ENUM_MAP, "defaultHttpConfig")) .addMethod(createConstructor()); configuration.modeDefaults().entrySet().forEach(entry -> { builder.addField(addDefaultsFieldForMode(entry)); builder.addField(addHttpDefaultsFieldForMode(entry)); }); addDefaultsFieldForLegacy(builder, "LEGACY_DEFAULTS"); addDefaultsFieldForLegacy(builder, "LEGACY_HTTP_DEFAULTS"); addEnumMapField(builder, DEFAULT_CONFIG_BY_MODE_ENUM_MAP); addEnumMapField(builder, DEFAULT_HTTP_CONFIG_BY_MODE_ENUM_MAP); addStaticEnumMapBlock(builder); return builder.build(); } private void addStaticEnumMapBlock(TypeSpec.Builder builder) { CodeBlock.Builder staticCodeBlock = CodeBlock.builder(); putItemsToEnumMap(staticCodeBlock, configuration.modeDefaults().keySet(), DEFAULTS_VAR_SUFFIX, DEFAULT_CONFIG_BY_MODE_ENUM_MAP); putItemsToEnumMap(staticCodeBlock, configuration.modeDefaults().keySet(), HTTP_DEFAULTS_VAR_SUFFIX, DEFAULT_HTTP_CONFIG_BY_MODE_ENUM_MAP); builder.addStaticBlock(staticCodeBlock.build()); } private void addEnumMapField(TypeSpec.Builder builder, String name) { ParameterizedTypeName map = ParameterizedTypeName.get(ClassName.get(Map.class), defaultsModeClassName(), ClassName.get(AttributeMap.class)); FieldSpec field = FieldSpec.builder(map, name, PRIVATE, STATIC, FINAL) .initializer("new $T<>(DefaultsMode.class)", EnumMap.class).build(); builder.addField(field); } private void putItemsToEnumMap(CodeBlock.Builder codeBlock, Set<String> modes, String suffix, String mapName) { modes.forEach(m -> { String mode = sanitizeMode(m); codeBlock.addStatement("$N.put(DefaultsMode.$N, $N)", mapName, mode, mode + suffix); }); // Add LEGACY since LEGACY is not in the modes set codeBlock.addStatement("$N.put(DefaultsMode.LEGACY, LEGACY$N)", mapName, suffix); } @Override public ClassName className() { return ClassName.get(basePackage, "DefaultsModeConfiguration"); } private FieldSpec addDefaultsFieldForMode(Map.Entry<String, Map<String, String>> modeEntry) { String mode = modeEntry.getKey(); String fieldName = sanitizeMode(mode) + DEFAULTS_VAR_SUFFIX; CodeBlock.Builder attributeBuilder = CodeBlock.builder() .add("$T.builder()", AttributeMap.class); modeEntry.getValue() .entrySet() .stream() .filter(e -> CONFIGURATION_MAPPING.containsKey(e.getKey())) .forEach(e -> attributeMapBuilder(e.getKey(), e.getValue(), attributeBuilder)); FieldSpec.Builder fieldSpec = FieldSpec.builder(AttributeMap.class, fieldName, PRIVATE, STATIC, FINAL) .initializer(attributeBuilder .add(".build()") .build()); return fieldSpec.build(); } private void addDefaultsFieldForLegacy(TypeSpec.Builder builder, String name) { FieldSpec field = FieldSpec.builder(AttributeMap.class, name, PRIVATE, STATIC, FINAL) .initializer("$T.empty()", AttributeMap.class).build(); builder.addField(field); } private void attributeMapBuilder(String option, String value, CodeBlock.Builder attributeBuilder) { OptionMetadata optionMetadata = CONFIGURATION_MAPPING.get(option); switch (option) { case "retryMode": attributeBuilder.add(".put($T, $T.$N)", optionMetadata.attribute, optionMetadata.type, value.toUpperCase(Locale.US)); break; case S3_US_EAST_1_REGIONAL_ENDPOINTS: attributeBuilder.add(".put($T, $S)", optionMetadata.attribute, value); break; default: throw new IllegalStateException("Unsupported option " + option); } } private void httpAttributeMapBuilder(String option, String value, CodeBlock.Builder attributeBuilder) { OptionMetadata optionMetadata = HTTP_CONFIGURATION_MAPPING.get(option); switch (option) { case CONNECT_TIMEOUT_IN_MILLIS: case TLS_NEGOTIATION_TIMEOUT_IN_MILLIS: attributeBuilder.add(".put($T, $T.ofMillis($N))", optionMetadata.attribute, optionMetadata.type, value); break; default: throw new IllegalStateException("Unsupported option " + option); } } private FieldSpec addHttpDefaultsFieldForMode(Map.Entry<String, Map<String, String>> modeEntry) { String mode = modeEntry.getKey(); String fieldName = sanitizeMode(mode) + HTTP_DEFAULTS_VAR_SUFFIX; CodeBlock.Builder attributeBuilder = CodeBlock.builder() .add("$T.builder()", AttributeMap.class); modeEntry.getValue() .entrySet() .stream() .filter(e -> HTTP_CONFIGURATION_MAPPING.containsKey(e.getKey())) .forEach(e -> httpAttributeMapBuilder(e.getKey(), e.getValue(), attributeBuilder)); FieldSpec.Builder fieldSpec = FieldSpec.builder(AttributeMap.class, fieldName, PRIVATE, STATIC, FINAL) .initializer(attributeBuilder .add(".build()") .build()); return fieldSpec.build(); } private String sanitizeMode(String str) { return str.replace('-', '_').toUpperCase(Locale.US); } private CodeBlock documentation() { CodeBlock.Builder builder = CodeBlock.builder() .add("Contains a collection of default configuration options for each " + "DefaultsMode"); return builder.build(); } private MethodSpec defaultConfigMethod(String enumMap, String methodName) { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName) .returns(AttributeMap.class) .addModifiers(PUBLIC, STATIC) .addJavadoc("Return the default config options for a given defaults " + "mode") .addParameter(defaultsModeClassName(), "mode") .addStatement("return $N.getOrDefault(mode, $T.empty())", enumMap, AttributeMap.class); return methodBuilder.build(); } private ClassName defaultsModeClassName() { return ClassName.get(defaultsModeBase, "DefaultsMode"); } private MethodSpec createConstructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .build(); } private static final class OptionMetadata { private final ClassName type; private final ClassName attribute; OptionMetadata(ClassName type, ClassName attribute) { this.type = type; this.attribute = attribute; } } }
3,134
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/defaultsmode/DefaultConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.defaultsmode; import java.util.Map; /** * Container for default configuration */ public class DefaultConfiguration { /** * The transformed configuration values for each mode */ private Map<String, Map<String, String>> modeDefaults; /** * The documentation for each mode */ private Map<String, String> modesDocumentation; /* * The documentation for each configuration option */ private Map<String, String> configurationDocumentation; public Map<String, Map<String, String>> modeDefaults() { return modeDefaults; } public DefaultConfiguration modeDefaults(Map<String, Map<String, String>> modeDefaults) { this.modeDefaults = modeDefaults; return this; } public Map<String, String> modesDocumentation() { return modesDocumentation; } public DefaultConfiguration modesDocumentation(Map<String, String> documentation) { this.modesDocumentation = documentation; return this; } public Map<String, String> configurationDocumentation() { return configurationDocumentation; } public DefaultConfiguration configurationDocumentation(Map<String, String> configurationDocumentation) { this.configurationDocumentation = configurationDocumentation; return this; } }
3,135
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/emitters/CodeWriter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.emitters; import static software.amazon.awssdk.codegen.lite.Utils.closeQuietly; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import software.amazon.awssdk.codegen.lite.Utils; import software.amazon.awssdk.utils.StringUtils; /** * Formats the generated code and write it to the underlying file. The caller should call the flush * method to write the contents to the file. This class is intended to be used only by the code * generation system and is not to be used for public use. */ public class CodeWriter extends StringWriter { /** * The code transformation that should be applied before code is written. */ private final CodeTransformer codeWriteTransformer = CodeTransformer.chain(new UnusedImportRemover(), new JavaCodeFormatter()); /** * The code transformation that should be applied before source code is "compared" for equality. This is only used when * attempting to clobber a file that has already been generated. */ private final CodeTransformer codeComparisonTransformer = new LinkRemover(); private final String dir; private final String file; /** * Constructor to use for .java files. * @param dir * output directory where the file is to be created. * @param file * name of the file without .java suffix. */ public CodeWriter(String dir, String file) { this(dir, file, ".java"); } /** * Constructor to use for custom file suffixes. * * @param dir * output directory where the file is to be created. * @param file * name of the file excluding suffix. * @param fileNameSuffix * suffix to be appended at the end of file name. */ public CodeWriter(String dir, String file, String fileNameSuffix) { if (dir == null) { throw new IllegalArgumentException( "Output Directory cannot be null."); } if (file == null) { throw new IllegalArgumentException("File name cannot be null."); } if (fileNameSuffix == null) { throw new IllegalArgumentException("File name suffix cannot be null."); } if (!file.endsWith(fileNameSuffix)) { file = file + fileNameSuffix; } this.dir = dir; this.file = file; Utils.createDirectory(dir); } /** * This method is expected to be called only once during the code generation process after the * template processing is done. */ @Override public void flush() { PrintWriter out = null; try { File outputFile = Utils.createFile(dir, this.file); String contents = getBuffer().toString(); String formattedContents = codeWriteTransformer.apply(contents); if (outputFile.length() == 0) { out = new PrintWriter(outputFile, "UTF-8"); out.write(formattedContents); } else { validateFileContentMatches(outputFile, formattedContents); } } catch (IOException e) { throw new IllegalStateException(e); } finally { closeQuietly(out); } } private void validateFileContentMatches(File outputFile, String newFileContents) throws IOException { byte[] currentFileBytes = Files.readAllBytes(outputFile.toPath()); String currentFileContents = new String(currentFileBytes, StandardCharsets.UTF_8); String currentContentForComparison = codeComparisonTransformer.apply(currentFileContents); String newContentForComparison = codeComparisonTransformer.apply(newFileContents); if (!StringUtils.equals(currentContentForComparison, newContentForComparison)) { throw new IllegalStateException("Attempted to clobber existing file (" + outputFile + ") with a new file that has " + "different content. This may indicate forgetting to clean up old generated files " + "before running the generator?\n" + "Existing file: \n" + currentContentForComparison + "\n\n" + "New file: \n" + newContentForComparison); } } }
3,136
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/emitters/LinkRemover.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.emitters; import java.util.regex.Pattern; /** * Removes HTML "anchor" tags from a string. This is used to compare files during clobbering while ignoring their documentation * links, which will pretty much always differ. */ public class LinkRemover implements CodeTransformer { private static final Pattern LINK_PATTERN = Pattern.compile("(<a[ \n]*/>|<a[> \n].*?</a>)", Pattern.DOTALL); @Override public String apply(String input) { return LINK_PATTERN.matcher(input).replaceAll(""); } }
3,137
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/emitters/JavaCodeFormatter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.emitters; import java.util.HashMap; import java.util.Map; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.text.edits.TextEdit; /** * Formats the generated java source code. Uses Eclipse JDT core plugin from the Eclipse SDK. */ @SuppressWarnings("unchecked") public class JavaCodeFormatter implements CodeTransformer { private static final Map<String, Object> DEFAULT_FORMATTER_OPTIONS; static { DEFAULT_FORMATTER_OPTIONS = DefaultCodeFormatterConstants.getEclipseDefaultSettings(); DEFAULT_FORMATTER_OPTIONS.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8); DEFAULT_FORMATTER_OPTIONS.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8); DEFAULT_FORMATTER_OPTIONS.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8); DEFAULT_FORMATTER_OPTIONS.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); DEFAULT_FORMATTER_OPTIONS.put( DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_PARAMETER_DESCRIPTION, DefaultCodeFormatterConstants.FALSE); DEFAULT_FORMATTER_OPTIONS.put( DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, DefaultCodeFormatterConstants.createAlignmentValue(true, DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE, DefaultCodeFormatterConstants.INDENT_ON_COLUMN)); DEFAULT_FORMATTER_OPTIONS.put( DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION, DefaultCodeFormatterConstants.createAlignmentValue(false, DefaultCodeFormatterConstants.WRAP_COMPACT, DefaultCodeFormatterConstants.INDENT_DEFAULT)); // Formats custom file headers if provided DEFAULT_FORMATTER_OPTIONS .put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER, DefaultCodeFormatterConstants.TRUE); DEFAULT_FORMATTER_OPTIONS.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, "130"); DEFAULT_FORMATTER_OPTIONS.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "120"); } private final CodeFormatter codeFormatter; /** * Creates a JavaCodeFormatter using the default formatter options. */ public JavaCodeFormatter() { this(new HashMap<>()); } /** * Creates a JavaCodeFormatter using the default formatter options and * optionally applying user provided options on top. * * @param overrideOptions user provided options to apply on top of defaults */ public JavaCodeFormatter(final Map<String, Object> overrideOptions) { Map formatterOptions = new HashMap<>(DEFAULT_FORMATTER_OPTIONS); if (overrideOptions != null) { formatterOptions.putAll(overrideOptions); } this.codeFormatter = ToolFactory.createCodeFormatter(formatterOptions, ToolFactory.M_FORMAT_EXISTING); } @Override public String apply(String contents) { TextEdit edit = codeFormatter.format( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0, contents.length(), 0, System.lineSeparator()); if (edit == null) { // TODO log a fatal or warning here. Throwing an exception is causing the actual freemarker error to be lost return contents; } IDocument document = new Document(contents); try { edit.apply(document); } catch (Exception e) { throw new RuntimeException( "Failed to format the generated source code.", e); } return document.get(); } }
3,138
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/emitters/CodeTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.emitters; import java.util.function.Function; import java.util.stream.Stream; public interface CodeTransformer extends Function<String, String> { static CodeTransformer chain(CodeTransformer... processors) { return input -> Stream.of(processors).map(p -> (Function<String, String>) p) .reduce(Function.identity(), Function::andThen).apply(input); } @Override String apply(String input); }
3,139
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/main/java/software/amazon/awssdk/codegen/lite/emitters/UnusedImportRemover.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.lite.emitters; import static java.util.stream.Collectors.toSet; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; public class UnusedImportRemover implements CodeTransformer { private static Pattern IMPORT_PATTERN = Pattern.compile("import(?:\\s+)(?:static\\s+)?(.*)(?:\\s*);"); @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } private Function<String, String> removeImportFunction(String importToRemove) { return c -> c.replaceFirst(findSpecificImportRegex(importToRemove), ""); } private Set<String> findUnusedImports(String content) { return findImports(content).stream().filter(isUnused(content)).collect(toSet()); } private List<String> findImports(String content) { Matcher m = IMPORT_PATTERN.matcher(content); List<String> imports = new ArrayList<>(); while (m.find()) { imports.add(m.group(1)); } return imports; } private String removeAllImports(String content) { return content.replaceAll(IMPORT_PATTERN.pattern(), ""); } private Predicate<String> isUnused(String content) { String contentWithoutImports = removeAllImports(content); return importToCheck -> !importToCheck.contains("*") && (isNotReferenced(contentWithoutImports, importToCheck) || isDuplicate(content, importToCheck)); } private boolean isNotReferenced(String contentWithoutImports, String importToCheck) { String symbol = importToCheck.substring(importToCheck.lastIndexOf('.') + 1); return !Pattern.compile(String.format("\\b%s\\b", symbol)).matcher(contentWithoutImports).find(); } private boolean isDuplicate(String content, String importToCheck) { Matcher m = Pattern.compile(findSpecificImportRegex(importToCheck)).matcher(content); return m.find() && m.find(); } private String findSpecificImportRegex(String specificImport) { return String.format("import(?:\\s+)(?:static )?(?:%s)(?:\\s*);", specificImport); } }
3,140
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/test/java/software/amazonaws/test/AppTest.java
package software.amazonaws.test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class AppTest { @Test public void handleRequest_shouldReturnConstantValue() { App function = new App(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
3,141
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; /** * The module containing all dependencies required by the {@link App}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of S3Client */ public static S3Client s3Client() { return S3Client.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.US_WEST_2) .httpClientBuilder(UrlConnectionHttpClient.builder()) .build(); } }
3,142
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws/test/App.java
package software.amazonaws.test; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.s3.S3Client; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class App implements RequestHandler<Object, Object> { private final S3Client s3Client; public App() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. s3Client = DependencyFactory.s3Client(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using s3Client. return input; } }
3,143
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/test/java/software/amazonaws/test/MyWafRegionalFunctionTest.java
package software.amazonaws.test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class MyWafRegionalFunctionTest { @Test public void handleRequest_shouldReturnConstantValue() { MyWafRegionalFunction function = new MyWafRegionalFunction(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
3,144
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.waf.regional.WafRegionalClient; /** * The module containing all dependencies required by the {@link MyWafRegionalFunction}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of WafRegionalClient */ public static WafRegionalClient wafRegionalClient() { return WafRegionalClient.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.AP_SOUTHEAST_1) .httpClientBuilder(ApacheHttpClient.builder()) .build(); } }
3,145
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/wafregionalclient/reference/src/main/java/software/amazonaws/test/MyWafRegionalFunction.java
package software.amazonaws.test; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.waf.regional.WafRegionalClient; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class MyWafRegionalFunction implements RequestHandler<Object, Object> { private final WafRegionalClient wafRegionalClient; public MyWafRegionalFunction() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. wafRegionalClient = DependencyFactory.wafRegionalClient(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using wafRegionalClient. return input; } }
3,146
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/test/java/software/amazonaws/test/MyNettyFunctionTest.java
package software.amazonaws.test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class MyNettyFunctionTest { @Test public void handleRequest_shouldReturnConstantValue() { MyNettyFunction function = new MyNettyFunction(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
3,147
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisAsyncClient; /** * The module containing all dependencies required by the {@link MyNettyFunction}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of KinesisAsyncClient */ public static KinesisAsyncClient kinesisClient() { return KinesisAsyncClient.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.US_EAST_1) .httpClientBuilder(NettyNioAsyncHttpClient.builder()) .build(); } }
3,148
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws/test/MyNettyFunction.java
package software.amazonaws.test; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.kinesis.KinesisAsyncClient; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class MyNettyFunction implements RequestHandler<Object, Object> { private final KinesisAsyncClient kinesisClient; public MyNettyFunction() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. kinesisClient = DependencyFactory.kinesisClient(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using kinesisClient. return input; } }
3,149
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/test/java/software/amazonaws/test/MyApacheFunctionTest.java
package software.amazonaws.test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class MyApacheFunctionTest { @Test public void handleRequest_shouldReturnConstantValue() { MyApacheFunction function = new MyApacheFunction(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
3,150
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; /** * The module containing all dependencies required by the {@link MyApacheFunction}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of DynamoDbClient */ public static DynamoDbClient dynamoDbClient() { return DynamoDbClient.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable()))) .httpClientBuilder(ApacheHttpClient.builder()) .build(); } }
3,151
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws/test/MyApacheFunction.java
package software.amazonaws.test; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class MyApacheFunction implements RequestHandler<Object, Object> { private final DynamoDbClient dynamoDbClient; public MyApacheFunction() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. dynamoDbClient = DependencyFactory.dynamoDbClient(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using dynamoDbClient. return input; } }
3,152
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/test/java/software/amazonaws/test/MyDynamoDbStreamsFunctionTest.java
package software.amazonaws.test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class MyDynamoDbStreamsFunctionTest { @Test public void handleRequest_shouldReturnConstantValue() { MyDynamoDbStreamsFunction function = new MyDynamoDbStreamsFunction(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
3,153
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/main/java/software/amazonaws/test/MyDynamoDbStreamsFunction.java
package software.amazonaws.test; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsClient; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class MyDynamoDbStreamsFunction implements RequestHandler<Object, Object> { private final DynamoDbStreamsClient dynamoDbStreamsClient; public MyDynamoDbStreamsFunction() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. dynamoDbStreamsClient = DependencyFactory.dynamoDbStreamsClient(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using dynamoDbStreamsClient. return input; } }
3,154
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/test/resources/projects/dynamodbstreamsclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsClient; /** * The module containing all dependencies required by the {@link MyDynamoDbStreamsFunction}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of DynamoDbStreamsClient */ public static DynamoDbStreamsClient dynamoDbStreamsClient() { return DynamoDbStreamsClient.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(Region.AP_SOUTHEAST_1) .httpClientBuilder(ApacheHttpClient.builder()) .build(); } }
3,155
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/test
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/test/java/__handlerClassName__Test.java
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class ${handlerClassName}Test { @Test public void handleRequest_shouldReturnConstantValue() { ${handlerClassName} function = new ${handlerClassName}(); Object result = function.handleRequest("echo", null); assertEquals("echo", result); } }
3,156
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/main
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/main/java/DependencyFactory.java
#parse ( "global.vm") package ${package}; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; #if ($region == 'null') import software.amazon.awssdk.core.SdkSystemSetting; #end import software.amazon.awssdk.http.${httpClientPackageName}; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.${servicePackage}.${serviceClientClassName}; /** * The module containing all dependencies required by the {@link ${handlerClassName}}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of ${serviceClientClassName} */ public static ${serviceClientClassName} ${serviceClientVariable}Client() { return ${serviceClientClassName}.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) #if ($region == 'null') .region(Region.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable()))) #else .region(Region.${regionEnum}) #end .httpClientBuilder(${httpClientClassName}.builder()) .build(); } }
3,157
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/main
Create_ds/aws-sdk-java-v2/archetypes/archetype-lambda/src/main/resources/archetype-resources/src/main/java/__handlerClassName__.java
#parse ( "global.vm") package ${package}; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.services.${servicePackage}.${serviceClientClassName}; /** * Lambda function entry point. You can change to use other pojo type or implement * a different RequestHandler. * * @see <a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html>Lambda Java Handler</a> for more information */ public class ${handlerClassName} implements RequestHandler<Object, Object> { private final ${serviceClientClassName} ${serviceClientVariable}Client; public ${handlerClassName}() { // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations. // It is initialized when the class is loaded. ${serviceClientVariable}Client = DependencyFactory.${serviceClientVariable}Client(); // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables } @Override public Object handleRequest(final Object input, final Context context) { // TODO: invoking the api call using ${serviceClientVariable}Client. return input; } }
3,158
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/test/java/software/amazonaws/test/HandlerTest.java
package software.amazonaws.test; import org.junit.jupiter.api.Test; public class HandlerTest { //TODO add tests here }
3,159
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws/test/Handler.java
package software.amazonaws.test; import software.amazon.awssdk.services.s3.S3Client; public class Handler { private final S3Client s3Client; public Handler() { s3Client = DependencyFactory.s3Client(); } public void sendRequest() { // TODO: invoking the api calls using s3Client. } }
3,160
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.services.s3.S3Client; /** * The module containing all dependencies required by the {@link Handler}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of S3Client */ public static S3Client s3Client() { return S3Client.builder() .httpClientBuilder(ApacheHttpClient.builder()) .build(); } }
3,161
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/identitycenter/reference/src/main/java/software/amazonaws/test/App.java
package software.amazonaws.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String... args) { logger.info("Application starts"); Handler handler = new Handler(); handler.sendRequest(); logger.info("Application ends"); } }
3,162
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/test/java/software/amazonaws/test/HandlerTest.java
package software.amazonaws.test; import org.junit.jupiter.api.Test; public class HandlerTest { //TODO add tests here }
3,163
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws/test/Handler.java
package software.amazonaws.test; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; public class Handler { private final DynamoDbClient dynamoDbClient; public Handler() { dynamoDbClient = DependencyFactory.dynamoDbClient(); } public void sendRequest() { // TODO: invoking the api calls using dynamoDbClient. } }
3,164
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; /** * The module containing all dependencies required by the {@link Handler}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of DynamoDbClient */ public static DynamoDbClient dynamoDbClient() { return DynamoDbClient.builder() .httpClientBuilder(UrlConnectionHttpClient.builder()) .build(); } }
3,165
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/src/main/java/software/amazonaws/test/App.java
package software.amazonaws.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String... args) { logger.info("Application starts"); Handler handler = new Handler(); handler.sendRequest(); logger.info("Application ends"); } }
3,166
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/test/java/software/amazonaws/test/HandlerTest.java
package software.amazonaws.test; import org.junit.jupiter.api.Test; public class HandlerTest { //TODO add tests here }
3,167
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws/test/Handler.java
package software.amazonaws.test; import software.amazon.awssdk.services.s3.S3AsyncClient; public class Handler { private final S3AsyncClient s3Client; public Handler() { s3Client = DependencyFactory.s3Client(); } public void sendRequest() { // TODO: invoking the api calls using s3Client. } }
3,168
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; /** * The module containing all dependencies required by the {@link Handler}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of S3AsyncClient */ public static S3AsyncClient s3Client() { return S3AsyncClient.builder() .httpClientBuilder(NettyNioAsyncHttpClient.builder()) .build(); } }
3,169
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/nettyclient/reference/src/main/java/software/amazonaws/test/App.java
package software.amazonaws.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String... args) { logger.info("Application starts"); Handler handler = new Handler(); handler.sendRequest(); logger.info("Application ends"); } }
3,170
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/test/java/software/amazonaws/test/HandlerTest.java
package software.amazonaws.test; import org.junit.jupiter.api.Test; public class HandlerTest { //TODO add tests here }
3,171
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws/test/Handler.java
package software.amazonaws.test; import software.amazon.awssdk.services.s3.S3Client; public class Handler { private final S3Client s3Client; public Handler() { s3Client = DependencyFactory.s3Client(); } public void sendRequest() { // TODO: invoking the api calls using s3Client. } }
3,172
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.services.s3.S3Client; /** * The module containing all dependencies required by the {@link Handler}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of S3Client */ public static S3Client s3Client() { return S3Client.builder() .httpClientBuilder(ApacheHttpClient.builder()) .build(); } }
3,173
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws/test/App.java
package software.amazonaws.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String... args) { logger.info("Application starts"); Handler handler = new Handler(); handler.sendRequest(); logger.info("Application ends"); } }
3,174
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/test/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/test/java/software/amazonaws/test/HandlerTest.java
package software.amazonaws.test; import org.junit.jupiter.api.Test; public class HandlerTest { //TODO add tests here }
3,175
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws/test/Handler.java
package software.amazonaws.test; import software.amazon.awssdk.services.s3.S3Client; public class Handler { private final S3Client s3Client; public Handler() { s3Client = DependencyFactory.s3Client(); } public void sendRequest() { // TODO: invoking the api calls using s3Client. } }
3,176
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws/test/DependencyFactory.java
package software.amazonaws.test; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.services.s3.S3Client; /** * The module containing all dependencies required by the {@link Handler}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of S3Client */ public static S3Client s3Client() { return S3Client.builder() .httpClientBuilder(ApacheHttpClient.builder()) .build(); } }
3,177
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws/test/App.java
package software.amazonaws.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String... args) { logger.info("Application starts"); Handler handler = new Handler(); handler.sendRequest(); logger.info("Application ends"); } }
3,178
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/test
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/test/java/HandlerTest.java
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}; import org.junit.jupiter.api.Test; public class HandlerTest { //TODO add tests here }
3,179
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main/java/Handler.java
#parse ( "global.vm") package ${package}; import software.amazon.awssdk.services.${servicePackage}.${serviceClientClassName}; public class Handler { private final ${serviceClientClassName} ${serviceClientVariable}Client; public Handler() { ${serviceClientVariable}Client = DependencyFactory.${serviceClientVariable}Client(); } public void sendRequest() { // TODO: invoking the api calls using ${serviceClientVariable}Client. } }
3,180
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main/java/DependencyFactory.java
#parse ( "global.vm") package ${package}; import software.amazon.awssdk.http.${httpClientPackageName}; import software.amazon.awssdk.services.${servicePackage}.${serviceClientClassName}; /** * The module containing all dependencies required by the {@link Handler}. */ public class DependencyFactory { private DependencyFactory() {} /** * @return an instance of ${serviceClientClassName} */ public static ${serviceClientClassName} ${serviceClientVariable}Client() { return ${serviceClientClassName}.builder() .httpClientBuilder(${httpClientClassName}.builder()) .build(); } }
3,181
0
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main
Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main/java/App.java
#parse ( "global.vm") package ${package}; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String... args) { logger.info("Application starts"); Handler handler = new Handler(); handler.sendRequest(); logger.info("Application ends"); } }
3,182
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/CloudWatchMetricPublisherTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import java.time.Duration; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.metrics.MetricCategory; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.MetricLevel; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.MetricCollectionAggregator; import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient; import software.amazon.awssdk.services.cloudwatch.model.Dimension; import software.amazon.awssdk.services.cloudwatch.model.MetricDatum; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataResponse; public class CloudWatchMetricPublisherTest { private CloudWatchAsyncClient cloudWatch; private CloudWatchMetricPublisher.Builder publisherBuilder; @Before public void setup() { cloudWatch = Mockito.mock(CloudWatchAsyncClient.class); publisherBuilder = CloudWatchMetricPublisher.builder() .cloudWatchClient(cloudWatch) .uploadFrequency(Duration.ofMinutes(60)); Mockito.when(cloudWatch.putMetricData(any(PutMetricDataRequest.class))) .thenReturn(CompletableFuture.completedFuture(PutMetricDataResponse.builder().build())); } @Test public void noMetricsNoCalls() { try (CloudWatchMetricPublisher publisher = publisherBuilder.build()) { publisher.publish(MetricCollector.create("test").collect()); } assertNoPutMetricCalls(); } @Test public void interruptedShutdownStillTerminates() { CloudWatchMetricPublisher publisher = publisherBuilder.build(); Thread.currentThread().interrupt(); publisher.close(); assertThat(publisher.isShutdown()).isTrue(); Thread.interrupted(); // Clear interrupt flag } @Test public void closeDoesNotCloseConfiguredClient() { CloudWatchMetricPublisher.builder().cloudWatchClient(cloudWatch).build().close(); Mockito.verify(cloudWatch, never()).close(); } @Test(timeout = 10_000) public void closeWaitsForUploadToComplete() throws InterruptedException { CountDownLatch cloudwatchPutCalledLatch = new CountDownLatch(1); CompletableFuture<PutMetricDataResponse> result = new CompletableFuture<>(); CloudWatchAsyncClient cloudWatch = Mockito.mock(CloudWatchAsyncClient.class); try (CloudWatchMetricPublisher publisher = CloudWatchMetricPublisher.builder() .cloudWatchClient(cloudWatch) .uploadFrequency(Duration.ofMinutes(60)) .build()) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5); publisher.publish(new FixedTimeMetricCollection(collector.collect())); Mockito.when(cloudWatch.putMetricData(any(PutMetricDataRequest.class))).thenAnswer(x -> { cloudwatchPutCalledLatch.countDown(); return result; }); publisher.publish(MetricCollector.create("test").collect()); Thread closeThread = new Thread(publisher::close); assertThat(publisher.isShutdown()).isFalse(); closeThread.start(); // Wait until cloudwatch is called cloudwatchPutCalledLatch.await(); // Wait to make sure the close thread seems to be waiting for the cloudwatch call to complete Thread.sleep(1_000); assertThat(closeThread.isAlive()).isTrue(); // Complete the cloudwatch call result.complete(null); // Make sure the close thread finishes closeThread.join(5_000); assertThat(closeThread.isAlive()).isFalse(); } } @Test public void defaultNamespaceIsCorrect() { try (CloudWatchMetricPublisher publisher = CloudWatchMetricPublisher.builder() .cloudWatchClient(cloudWatch) .build()) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } PutMetricDataRequest call = getPutMetricCall(); assertThat(call.namespace()).isEqualTo("AwsSdk/JavaSdk2"); } @Test public void defaultDimensionsIsCorrect() { try (CloudWatchMetricPublisher publisher = CloudWatchMetricPublisher.builder() .cloudWatchClient(cloudWatch) .build()) { MetricCollector collector = newCollector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName"); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } PutMetricDataRequest call = getPutMetricCall(); assertThat(call.metricData().get(0).dimensions()) .containsExactlyInAnyOrder(Dimension.builder() .name(CoreMetric.SERVICE_ID.name()) .value("ServiceId") .build(), Dimension.builder() .name(CoreMetric.OPERATION_NAME.name()) .value("OperationName") .build()); } @Test public void namespaceSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.namespace("namespace").build()) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } assertThat(getPutMetricCall().namespace()).isEqualTo("namespace"); } @Test public void dimensionsSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.dimensions(CoreMetric.SERVICE_ID).build()) { MetricCollector collector = newCollector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName"); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } PutMetricDataRequest call = getPutMetricCall(); assertThat(call.metricData().get(0).dimensions()).containsExactly(Dimension.builder() .name(CoreMetric.SERVICE_ID.name()) .value("ServiceId") .build()); } @Test public void metricCategoriesSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.metricCategories(MetricCategory.HTTP_CLIENT).build()) { MetricCollector collector = newCollector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(CoreMetric.API_CALL_SUCCESSFUL, true); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } PutMetricDataRequest call = getPutMetricCall(); MetricDatum metric = call.metricData().get(0); assertThat(call.metricData()).hasSize(1); assertThat(metric.dimensions()).containsExactly(Dimension.builder() .name(CoreMetric.SERVICE_ID.name()) .value("ServiceId") .build()); assertThat(metric.metricName()).isEqualTo(HttpMetric.AVAILABLE_CONCURRENCY.name()); } @Test public void metricLevelSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.metricLevel(MetricLevel.INFO).build()) { MetricCollector collector = newCollector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(CoreMetric.API_CALL_SUCCESSFUL, true); collector.reportMetric(HttpMetric.HTTP_STATUS_CODE, 404); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } PutMetricDataRequest call = getPutMetricCall(); MetricDatum metric = call.metricData().get(0); assertThat(call.metricData()).hasSize(1); assertThat(metric.dimensions()).containsExactly(Dimension.builder() .name(CoreMetric.SERVICE_ID.name()) .value("ServiceId") .build()); assertThat(metric.metricName()).isEqualTo(CoreMetric.API_CALL_SUCCESSFUL.name()); } @Test public void maximumCallsPerPublishSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.maximumCallsPerUpload(1) .detailedMetrics(HttpMetric.AVAILABLE_CONCURRENCY) .build()) { for (int i = 0; i < MetricCollectionAggregator.MAX_VALUES_PER_REQUEST + 1; ++i) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, i); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } } assertThat(getPutMetricCalls()).hasSize(1); } @Test public void detailedMetricsSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.detailedMetrics(HttpMetric.AVAILABLE_CONCURRENCY).build()) { for (int i = 0; i < 10; ++i) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 10); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, i); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } } PutMetricDataRequest call = getPutMetricCall(); MetricDatum concurrencyMetric = getDatum(call, HttpMetric.MAX_CONCURRENCY); MetricDatum availableConcurrency = getDatum(call, HttpMetric.AVAILABLE_CONCURRENCY); assertThat(concurrencyMetric.values()).isEmpty(); assertThat(concurrencyMetric.counts()).isEmpty(); assertThat(concurrencyMetric.statisticValues()).isNotNull(); assertThat(availableConcurrency.values()).isNotEmpty(); assertThat(availableConcurrency.counts()).isNotEmpty(); assertThat(availableConcurrency.statisticValues()).isNull(); } private MetricDatum getDatum(PutMetricDataRequest call, SdkMetric<?> metric) { return call.metricData().stream().filter(m -> m.metricName().equals(metric.name())).findAny().get(); } private PutMetricDataRequest getPutMetricCall() { List<PutMetricDataRequest> calls = getPutMetricCalls(); assertThat(calls).hasSize(1); return calls.get(0); } private List<PutMetricDataRequest> getPutMetricCalls() { ArgumentCaptor<PutMetricDataRequest> captor = ArgumentCaptor.forClass(PutMetricDataRequest.class); Mockito.verify(cloudWatch).putMetricData(captor.capture()); return captor.getAllValues(); } private void assertNoPutMetricCalls() { Mockito.verify(cloudWatch, never()).putMetricData(any(PutMetricDataRequest.class)); } private MetricCollector newCollector() { return MetricCollector.create("test"); } }
3,183
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/FixedTimeMetricCollection.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch; import java.time.Instant; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricRecord; import software.amazon.awssdk.metrics.SdkMetric; /** * An implementation of {@link MetricCollection} that sets a static time for the {@link #creationTime()}. This makes it easier * to test aggregation behavior, because the times can be fixed instead of regenerated each time the {@code MetricCollection} is * created. */ public class FixedTimeMetricCollection implements MetricCollection { private final MetricCollection delegate; private final Instant creationTime; public FixedTimeMetricCollection(MetricCollection delegate) { this(delegate, Instant.EPOCH); } public FixedTimeMetricCollection(MetricCollection delegate, Instant creationTime) { this.delegate = delegate; this.creationTime = creationTime; } @Override public String name() { return delegate.name(); } @Override public <T> List<T> metricValues(SdkMetric<T> metric) { return delegate.metricValues(metric); } @Override public List<MetricCollection> children() { return delegate.children() .stream() .map(c -> new FixedTimeMetricCollection(c, creationTime)) .collect(Collectors.toList()); } @Override public Instant creationTime() { return creationTime; } @Override public Iterator<MetricRecord<?>> iterator() { return delegate.iterator(); } }
3,184
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/MetricUploaderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataResponse; public class MetricUploaderTest { private List<CompletableFuture<PutMetricDataResponse>> putMetricDataResponseFutures = new ArrayList<>(); private CloudWatchAsyncClient client; private MetricUploader uploader; @BeforeEach public void setUp() { client = Mockito.mock(CloudWatchAsyncClient.class); uploader = new MetricUploader(client); Mockito.when(client.putMetricData(any(PutMetricDataRequest.class))).thenAnswer(p -> { CompletableFuture<PutMetricDataResponse> result = new CompletableFuture<>(); putMetricDataResponseFutures.add(result); return result; }); } @Test public void uploadSuccessIsPropagated() { CompletableFuture<Void> uploadFuture = uploader.upload(Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build())); assertThat(putMetricDataResponseFutures).hasSize(2); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(0).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(1).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isCompleted(); } @Test public void uploadFailureIsPropagated() { CompletableFuture<Void> uploadFuture = uploader.upload(Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build())); assertThat(putMetricDataResponseFutures).hasSize(2); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(0).completeExceptionally(new Throwable()); putMetricDataResponseFutures.get(1).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isCompletedExceptionally(); } @Test public void closeFalseDoesNotCloseClient() { uploader.close(false); Mockito.verify(client, never()).close(); } @Test public void closeTrueClosesClient() { uploader.close(true); Mockito.verify(client, times(1)).close(); } }
3,185
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/task/UploadMetricsTasksTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.task; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.MetricUploader; import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.MetricCollectionAggregator; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest; public class UploadMetricsTasksTest { private MetricCollectionAggregator aggregator; private MetricUploader uploader; private UploadMetricsTasks task; @BeforeEach public void setUp() { aggregator = Mockito.mock(MetricCollectionAggregator.class); uploader = Mockito.mock(MetricUploader.class); task = new UploadMetricsTasks(aggregator, uploader, 2); } @Test public void extraTasksAboveMaximumAreDropped() { List<PutMetricDataRequest> requests = Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build()); Mockito.when(aggregator.getRequests()).thenReturn(requests); task.call(); ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class); Mockito.verify(uploader).upload(captor.capture()); List<PutMetricDataRequest> uploadedRequests = captor.getValue(); assertThat(uploadedRequests).hasSize(2); assertThat(uploadedRequests).containsOnlyElementsOf(requests); } }
3,186
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/MetricCollectionAggregatorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform; import static java.time.temporal.ChronoUnit.HOURS; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.fail; import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.metrics.MetricCategory; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.MetricLevel; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.metrics.publishers.cloudwatch.FixedTimeMetricCollection; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest; import software.amazon.awssdk.services.cloudwatch.model.StatisticSet; public class MetricCollectionAggregatorTest { private static final String DEFAULT_NAMESPACE = "namespace"; private static final Set<SdkMetric<String>> DEFAULT_DIMENSIONS = Stream.of(CoreMetric.SERVICE_ID, CoreMetric.OPERATION_NAME) .collect(Collectors.toSet()); private static final MetricLevel DEFAULT_METRIC_LEVEL = MetricLevel.INFO; private static final Set<MetricCategory> DEFAULT_CATEGORIES = Collections.singleton(MetricCategory.HTTP_CLIENT); private static final Set<SdkMetric<?>> DEFAULT_DETAILED_METRICS = Collections.emptySet(); @Test public void maximumRequestsIsHonored() { List<PutMetricDataRequest> requests; requests = aggregatorWithUniqueMetricsAdded(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST).getRequests(); assertThat(requests).hasOnlyOneElementSatisfying(request -> { assertThat(request.metricData()).hasSize(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST); }); requests = aggregatorWithUniqueMetricsAdded(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST + 1).getRequests(); assertThat(requests).hasSize(2); assertThat(requests.get(0).metricData()).hasSize(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST); assertThat(requests.get(1).metricData()).hasSize(1); } @Test public void maximumMetricValuesIsHonored() { List<PutMetricDataRequest> requests; requests = aggregatorWithUniqueValuesAdded(HttpMetric.MAX_CONCURRENCY, MetricCollectionAggregator.MAX_VALUES_PER_REQUEST).getRequests(); assertThat(requests).hasSize(1); validateValuesCount(requests.get(0), MetricCollectionAggregator.MAX_VALUES_PER_REQUEST); requests = aggregatorWithUniqueValuesAdded(HttpMetric.MAX_CONCURRENCY, MetricCollectionAggregator.MAX_VALUES_PER_REQUEST + 1).getRequests(); assertThat(requests).hasSize(2); validateValuesCount(requests.get(0), MetricCollectionAggregator.MAX_VALUES_PER_REQUEST); validateValuesCount(requests.get(1), 1); } private void validateValuesCount(PutMetricDataRequest request, int valuesExpected) { assertThat(request.metricData().stream().flatMap(m -> m.values().stream())) .hasSize(valuesExpected); } @Test public void smallValuesAreNormalizedToZeroWithSummaryMetrics() { // Really small values (close to 0) result in CloudWatch failing with an "unsupported value" error. Make sure that we // floor those values to 0 to prevent that error. MetricCollectionAggregator aggregator = defaultAggregator(); MetricCollector collector = collector(); SdkMetric<Double> metric = someMetric(Double.class); collector.reportMetric(metric, -1E-10); collector.reportMetric(metric, 1E-10); aggregator.addCollection(collectToFixedTime(collector)); assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> { assertThat(request.metricData()).hasOnlyOneElementSatisfying(metricData -> { StatisticSet stats = metricData.statisticValues(); assertThat(stats.minimum()).isEqualTo(0.0); assertThat(stats.maximum()).isEqualTo(0.0); assertThat(stats.sum()).isEqualTo(0.0); assertThat(stats.sampleCount()).isEqualTo(2.0); }); }); } @Test public void smallValuesAreNormalizedToZeroWithDetailedMetrics() { // Really small values (close to 0) result in CloudWatch failing with an "unsupported value" error. Make sure that we // floor those values to 0 to prevent that error. SdkMetric<Double> metric = someMetric(Double.class); MetricCollectionAggregator aggregator = aggregatorWithCustomDetailedMetrics(metric); MetricCollector collector = collector(); collector.reportMetric(metric, -1E-10); collector.reportMetric(metric, 1E-10); aggregator.addCollection(collectToFixedTime(collector)); assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> { assertThat(request.metricData()).hasOnlyOneElementSatisfying(metricData -> { assertThat(metricData.values()).hasOnlyOneElementSatisfying(metricValue -> { assertThat(metricValue).isEqualTo(0.0); }); assertThat(metricData.counts()).hasOnlyOneElementSatisfying(metricCount -> { assertThat(metricCount).isEqualTo(2.0); }); }); }); } @Test public void dimensionOrderInCollectionDoesNotMatter() { MetricCollectionAggregator aggregator = defaultAggregator(); MetricCollector collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1); aggregator.addCollection(collectToFixedTime(collector)); collector = collector(); collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName"); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 2); aggregator.addCollection(collectToFixedTime(collector)); assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> { assertThat(request.metricData()).hasSize(1); }); } @Test public void metricsAreAggregatedByDimensionMetricAndTime() { MetricCollectionAggregator aggregator = defaultAggregator(); MetricCollector collector = collector(); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1); aggregator.addCollection(collectToFixedTimeBucket(collector, 0)); collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 2); aggregator.addCollection(collectToFixedTimeBucket(collector, 0)); collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 3); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 4); aggregator.addCollection(collectToFixedTimeBucket(collector, 0)); collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 5); aggregator.addCollection(collectToFixedTimeBucket(collector, 1)); assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> { assertThat(request.namespace()).isEqualTo(DEFAULT_NAMESPACE); assertThat(request.metricData()).hasSize(5).allSatisfy(data -> { assertThat(data.values()).isEmpty(); assertThat(data.counts()).isEmpty(); if (data.dimensions().isEmpty()) { assertThat(data.metricName()).isEqualTo(HttpMetric.MAX_CONCURRENCY.name()); assertThat(data.statisticValues().sampleCount()).isEqualTo(1); assertThat(data.statisticValues().sum()).isEqualTo(1); } else if (data.dimensions().size() == 1) { assertThat(data.metricName()).isEqualTo(HttpMetric.MAX_CONCURRENCY.name()); assertThat(data.statisticValues().sampleCount()).isEqualTo(1); assertThat(data.statisticValues().sum()).isEqualTo(2); } else { assertThat(data.dimensions().size()).isEqualTo(2); if (data.timestamp().equals(Instant.EPOCH)) { // Time bucket 0 if (data.metricName().equals(HttpMetric.MAX_CONCURRENCY.name())) { assertThat(data.statisticValues().sampleCount()).isEqualTo(1); assertThat(data.statisticValues().sum()).isEqualTo(3); } else { assertThat(data.metricName()).isEqualTo(HttpMetric.AVAILABLE_CONCURRENCY.name()); assertThat(data.statisticValues().sampleCount()).isEqualTo(1); assertThat(data.statisticValues().sum()).isEqualTo(4); } } else { // Time bucket 1 assertThat(data.metricName()).isEqualTo(HttpMetric.MAX_CONCURRENCY.name()); assertThat(data.statisticValues().sampleCount()).isEqualTo(1); assertThat(data.statisticValues().sum()).isEqualTo(5); } } }); }); } @Test public void metricSummariesAreCorrectWithValuesInSameCollector() { MetricCollectionAggregator aggregator = defaultAggregator(); MetricCollector collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 2); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 3); aggregator.addCollection(collectToFixedTime(collector)); assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> { assertThat(request.namespace()).isEqualTo(DEFAULT_NAMESPACE); assertThat(request.metricData()).hasOnlyOneElementSatisfying(metricData -> { assertThat(metricData.dimensions()).hasOnlyOneElementSatisfying(dimension -> { assertThat(dimension.name()).isEqualTo(CoreMetric.SERVICE_ID.name()); assertThat(dimension.value()).isEqualTo("ServiceId"); }); assertThat(metricData.values()).isEmpty(); assertThat(metricData.counts()).isEmpty(); assertThat(metricData.statisticValues()).isEqualTo(StatisticSet.builder() .minimum(1.0) .maximum(4.0) .sum(14.0) .sampleCount(5.0) .build()); }); }); } @Test public void metricSummariesAreCorrectWithValuesInDifferentCollector() { MetricCollectionAggregator aggregator = defaultAggregator(); MetricCollector collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 2); aggregator.addCollection(collectToFixedTime(collector)); collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1); aggregator.addCollection(collectToFixedTime(collector)); collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4); aggregator.addCollection(collectToFixedTime(collector)); collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4); aggregator.addCollection(collectToFixedTime(collector)); collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 3); aggregator.addCollection(collectToFixedTime(collector)); assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> { assertThat(request.namespace()).isEqualTo(DEFAULT_NAMESPACE); assertThat(request.metricData()).hasOnlyOneElementSatisfying(metricData -> { assertThat(metricData.dimensions()).hasOnlyOneElementSatisfying(dimension -> { assertThat(dimension.name()).isEqualTo(CoreMetric.SERVICE_ID.name()); assertThat(dimension.value()).isEqualTo("ServiceId"); }); assertThat(metricData.values()).isEmpty(); assertThat(metricData.counts()).isEmpty(); assertThat(metricData.statisticValues()).isEqualTo(StatisticSet.builder() .minimum(1.0) .maximum(4.0) .sum(14.0) .sampleCount(5.0) .build()); }); }); } @Test public void detailedMetricsAreCorrect() { MetricCollectionAggregator aggregator = aggregatorWithCustomDetailedMetrics(HttpMetric.MAX_CONCURRENCY); MetricCollector collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 2); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 3); aggregator.addCollection(collectToFixedTime(collector)); assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> { assertThat(request.namespace()).isEqualTo(DEFAULT_NAMESPACE); assertThat(request.metricData()).hasOnlyOneElementSatisfying(metricData -> { assertThat(metricData.dimensions()).hasOnlyOneElementSatisfying(dimension -> { assertThat(dimension.name()).isEqualTo(CoreMetric.SERVICE_ID.name()); assertThat(dimension.value()).isEqualTo("ServiceId"); }); assertThat(metricData.values()).hasSize(4); assertThat(metricData.statisticValues()).isNull(); for (int i = 0; i < metricData.values().size(); i++) { Double value = metricData.values().get(i); Double count = metricData.counts().get(i); switch (value.toString()) { case "1.0": case "2.0": case "3.0": assertThat(count).isEqualTo(1.0); break; case "4.0": assertThat(count).isEqualTo(2.0); break; default: fail(); } } }); }); } @Test public void metricsFromOtherCategoriesAreIgnored() { MetricCollectionAggregator aggregator = defaultAggregator(); MetricCollector collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(HttpMetric.HTTP_STATUS_CODE, 404); aggregator.addCollection(collectToFixedTime(collector)); assertThat(aggregator.getRequests()).isEmpty(); } @Test public void getRequestsResetsState() { MetricCollectionAggregator aggregator = defaultAggregator(); MetricCollector collector = collector(); collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId"); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1); aggregator.addCollection(collectToFixedTime(collector)); assertThat(aggregator.getRequests()).hasSize(1); assertThat(aggregator.getRequests()).isEmpty(); } @Test public void numberTypesAreTransformedCorrectly() { SdkMetric<CustomNumber> metric = someMetric(CustomNumber.class); assertThat(transformMetricValueUsingAggregator(metric, new CustomNumber(-1000.5))).isEqualTo(-1000.5); assertThat(transformMetricValueUsingAggregator(metric, new CustomNumber(0))).isEqualTo(0); assertThat(transformMetricValueUsingAggregator(metric, new CustomNumber(1000.5))).isEqualTo(1000.5); } @Test public void durationsAreTransformedCorrectly() { SdkMetric<Duration> metric = someMetric(Duration.class); assertThat(transformMetricValueUsingAggregator(metric, Duration.ofSeconds(-10))).isEqualTo(-10_000); assertThat(transformMetricValueUsingAggregator(metric, Duration.ofSeconds(0))).isEqualTo(0); assertThat(transformMetricValueUsingAggregator(metric, Duration.ofSeconds(10))).isEqualTo(10_000); } @Test public void booleansAreTransformedCorrectly() { SdkMetric<Boolean> metric = someMetric(Boolean.class); assertThat(transformMetricValueUsingAggregator(metric, false)).isEqualTo(0.0); assertThat(transformMetricValueUsingAggregator(metric, true)).isEqualTo(1.0); } private <T> Double transformMetricValueUsingAggregator(SdkMetric<T> metric, T input) { MetricCollectionAggregator aggregator = aggregatorWithCustomDetailedMetrics(metric); MetricCollector collector = collector(); collector.reportMetric(metric, input); aggregator.addCollection(collectToFixedTime(collector)); return aggregator.getRequests().get(0).metricData().get(0).values().get(0); } private MetricCollectionAggregator aggregatorWithUniqueValuesAdded(SdkMetric<Integer> metric, int numValues) { MetricCollectionAggregator aggregator = aggregatorWithCustomDetailedMetrics(metric); for (int i = 0; i < numValues; i++) { MetricCollector collector = collector(); collector.reportMetric(metric, i); aggregator.addCollection(collectToFixedTime(collector)); } return aggregator; } private MetricCollectionAggregator aggregatorWithUniqueMetricsAdded(int numMetrics) { MetricCollectionAggregator aggregator = defaultAggregator(); MetricCollector collector = collector(); for (int i = 0; i < numMetrics; i++) { collector.reportMetric(someMetric(), 0); } aggregator.addCollection(collectToFixedTime(collector)); return aggregator; } private MetricCollectionAggregator defaultAggregator() { return new MetricCollectionAggregator(DEFAULT_NAMESPACE, DEFAULT_DIMENSIONS, DEFAULT_CATEGORIES, DEFAULT_METRIC_LEVEL, DEFAULT_DETAILED_METRICS); } private MetricCollectionAggregator aggregatorWithCustomDetailedMetrics(SdkMetric<?>... detailedMetrics) { return new MetricCollectionAggregator(DEFAULT_NAMESPACE, DEFAULT_DIMENSIONS, DEFAULT_CATEGORIES, DEFAULT_METRIC_LEVEL, Stream.of(detailedMetrics).collect(Collectors.toSet())); } private MetricCollector collector() { return MetricCollector.create("test"); } private SdkMetric<Integer> someMetric() { return someMetric(Integer.class); } private <T> SdkMetric<T> someMetric(Class<T> clazz) { return SdkMetric.create(getClass().getSimpleName() + UUID.randomUUID().toString(), clazz, MetricLevel.INFO, MetricCategory.HTTP_CLIENT); } private MetricCollection collectToFixedTime(MetricCollector collector) { return new FixedTimeMetricCollection(collector.collect()); } private MetricCollection collectToFixedTimeBucket(MetricCollector collector, int timeBucket) { // Make sure collectors in different "time buckets" are in a different minute than other collectors. We also offset the // hour by a few seconds, to make sure the metric collection aggregator is actually ignoring the "seconds" portion of // the collection time. Instant metricTime = Instant.EPOCH.plus(timeBucket, HOURS) .plusSeconds(Math.max(59, timeBucket)); return new FixedTimeMetricCollection(collector.collect(), metricTime); } private static class CustomNumber extends Number { private final double value; public CustomNumber(double value) { this.value = value; } @Override public int intValue() { throw new UnsupportedOperationException(); } @Override public long longValue() { throw new UnsupportedOperationException(); } @Override public float floatValue() { throw new UnsupportedOperationException(); } @Override public double doubleValue() { return value; } } }
3,187
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/CloudWatchMetricPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch; import static software.amazon.awssdk.metrics.publishers.cloudwatch.internal.CloudWatchMetricLogger.METRIC_LOGGER; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.metrics.MetricCategory; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.MetricLevel; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.MetricUploader; import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.task.AggregateMetricsTask; import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.task.UploadMetricsTasks; import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.MetricCollectionAggregator; import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient; import software.amazon.awssdk.services.cloudwatch.model.Dimension; import software.amazon.awssdk.services.cloudwatch.model.MetricDatum; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest; import software.amazon.awssdk.services.cloudwatch.model.StatisticSet; import software.amazon.awssdk.utils.ThreadFactoryBuilder; /** * An implementation of {@link MetricPublisher} that aggregates and uploads metrics to Amazon CloudWatch on a periodic basis. * * <p>This simplifies the process of uploading custom metrics to CloudWatch, and can also be configured on the AWS * SDK clients directly to upload AWS SDK-specific metrics (e.g. request latencies, failure rates) to CloudWatch. * * <p><b>Overview</b> * * <p>This publisher aggregates metric data in memory, and periodically uploads it to CloudWatch in a background thread. This * minimizes the work necessary to upload metrics, allowing the caller to focus on collecting the data. * * <p>The default settings of the metrics publisher are meant to minimize memory usage and CloudWatch cost, while still * providing a useful amount of insight into the metric data. Care should be taken when overriding the default values on the * publisher, because they can result in an associated increased in memory usage and CloudWatch cost. * * <p>By default, all metrics are uploaded using summary statistics. This means that only count, maximum, minimum, sum and * average data is available in CloudWatch. Metric details (e.g. p90, p99) can be enabled on a per-metric basis using * {@link Builder#detailedMetrics(Collection)}. * * <p>See {@link Builder} for the configuration values that are available for the publisher, and how they can be used to * increase the functionality or decrease the cost the publisher. * * <p><b>Logging</b> * * The CloudWatchMetricPublisher logs all aggregation and upload-related logs to the * {@code software.amazon.awssdk.metrics.publishers.cloudwatch} namespace. To determine how many metrics are being uploaded * successfully without checking the CloudWatch console, you can check for a "success" message at the DEBUG level. At the TRACE * level, you can see exactly which metrics are being uploaded. * * <p><b>Configuring AWS SDK clients to upload client metrics</b> * * <p> * Create a {@link CloudWatchMetricPublisher}, and configure it via * {@link ClientOverrideConfiguration.Builder#addMetricPublisher(MetricPublisher)} * * <pre> * CloudWatchMetricPublisher cloudWatchMetricPublisher = CloudWatchMetricPublisher.create(); * S3Client s3 = S3Client.builder() * .overrideConfiguration(o -> o.addMetricPublisher(cloudWatchMetricPublisher)) * .build(); * </pre> * <p><b>Uploading your own custom metrics</b> * * <i>Step 1: Define which metrics you wish to collect</i> * * <p>Metrics are described using the {@link SdkMetric#create} method. When you describe your metric, you specify * the name that will appear in CloudWatch and the Java data-type of the metric. The metric should be described once for your * entire application. * * <p>Supported types: (1) {@link Number} types (e.g. {@link Integer}, {@link Double}, etc.), (2) {@link Duration}. * * <pre> * // In this and the following examples, we want to collect metrics about calls to a method we have defined: "myMethod" * public static final class MyMethodMetrics { * // The number of times "myMethod" has been called. * private static final SdkMetric&lt;Integer&gt; MY_METHOD_CALL_COUNT = * SdkMetric.create("MyMethodCallCount", Integer.class, MetricLevel.INFO, MetricCategory.CUSTOM); * * // The amount of time that "myMethod" took to execute. * private static final SdkMetric&lt;Duration&gt; MY_METHOD_LATENCY = * SdkMetric.create("MyMethodLatency", Duration.class, MetricLevel.INFO, MetricCategory.CUSTOM); * } * </pre> * * <p><i>Step 2: Create a {@code CloudWatchMetricPublisher}</i> * * <p>A {@code CloudWatchMetricPublisher} should be created once for your entire application, and be reused wherever it is * needed. {@code CloudWatchMetricPublisher}s are thread-safe, so there should be no need to create multiple instances. Most * people create and manage the publisher in their inversion-of-control (IoC) container (e.g. Spring/Dagger/Guice). * * <p>Note: When your application is finished with the {@code CloudWatchMetricPublisher}, make sure to {@link #close()} it. Your * inversion-of-control container may handle this for you on JVM shutdown. * * <p>See {@link CloudWatchMetricPublisher.Builder} for all available configuration options. * * <pre> * // Create a CloudWatchMetricPublisher using a custom namespace. * MetricPublisher metricPublisher = CloudWatchMetricPublisher.builder() * .namespace("MyApplication") * .build(); * </pre> * * <p><i>Step 3: Collect and Publish Metrics</i> * * <p>Create and use a {@link MetricCollector} to collect data about your configured metrics. * * <pre> * // Call "myMethod" and collect metrics about the call. * Instant methodCallStartTime = Instant.now(); * myMethod(); * Duration methodCallDuration = Duration.between(methodCallStartTime, Instant.now()); * * // Write the metrics to the CloudWatchMetricPublisher. * MetricCollector metricCollector = MetricCollector.create("MyMethodCall"); * metricCollector.reportMetric(MyCustomMetrics.MY_METHOD_CALL_COUNT, 1); * metricCollector.reportMetric(MyCustomMetrics.MY_METHOD_LATENCY, methodCallDuration); * MetricCollection metricCollection = metricCollector.collect(); * * metricPublisher.publish(metricCollection); * </pre> * * <p><b>Warning:</b> Make sure the {@link #close()} this publisher when it is done being used to release all resources it * consumes. Failure to do so will result in possible thread or file descriptor leaks. */ @ThreadSafe @Immutable @SdkPublicApi public final class CloudWatchMetricPublisher implements MetricPublisher { /** * The maximum queue size for the internal {@link #executor} that is used to aggregate metric data and upload it to * CloudWatch. If this value is too high, memory is wasted. If this value is too low, metrics could be dropped. * * This value is not currently configurable, because it's unlikely that this is a value that customers should need to modify. * If customers really need control over this value, we might consider letting them instead configure the * {@link BlockingQueue} used on the executor. The value here depends on the type of {@code BlockingQueue} in use, and * we should probably not indirectly couple people to the type of blocking queue we're using. */ private static final int MAXIMUM_TASK_QUEUE_SIZE = 128; private static final String DEFAULT_NAMESPACE = "AwsSdk/JavaSdk2"; private static final int DEFAULT_MAXIMUM_CALLS_PER_UPLOAD = 10; private static final Duration DEFAULT_UPLOAD_FREQUENCY = Duration.ofMinutes(1); private static final Set<SdkMetric<String>> DEFAULT_DIMENSIONS = Stream.of(CoreMetric.SERVICE_ID, CoreMetric.OPERATION_NAME) .collect(Collectors.toSet()); private static final Set<MetricCategory> DEFAULT_METRIC_CATEGORIES = Collections.singleton(MetricCategory.ALL); private static final MetricLevel DEFAULT_METRIC_LEVEL = MetricLevel.INFO; private static final Set<SdkMetric<?>> DEFAULT_DETAILED_METRICS = Collections.emptySet(); /** * Whether {@link #close()} should call {@link CloudWatchAsyncClient#close()}. This is false when * {@link Builder#cloudWatchClient(CloudWatchAsyncClient)} was specified, meaning the customer has to close the client * themselves. */ private final boolean closeClientWithPublisher; /** * The aggregator that takes {@link MetricCollection}s and converts them into {@link PutMetricDataRequest}s. This aggregator * is *not* thread safe, so it should only ever be accessed from the {@link #executor}'s thread. */ private final MetricCollectionAggregator metricAggregator; /** * The uploader that takes {@link PutMetricDataRequest}s and sends them to a {@link CloudWatchAsyncClient}. */ private final MetricUploader metricUploader; /** * The executor that executes {@link AggregateMetricsTask}s and {@link UploadMetricsTasks}s. */ private final ExecutorService executor; /** * A scheduled executor that periodically schedules a {@link UploadMetricsTasks} on the {@link #executor} thread. Note: this * executor should never execute the flush task itself, because that needs access to the {@link #metricAggregator}, and the * {@code metricAggregator} should only ever be accessed from the {@link #executor} thread. */ private final ScheduledExecutorService scheduledExecutor; /** * The maximum number of {@link PutMetricDataRequest}s that should ever be executed as part of a single * {@link UploadMetricsTasks}. */ private final int maximumCallsPerUpload; private CloudWatchMetricPublisher(Builder builder) { this.closeClientWithPublisher = resolveCloseClientWithPublisher(builder); this.metricAggregator = new MetricCollectionAggregator(resolveNamespace(builder), resolveDimensions(builder), resolveMetricCategories(builder), resolveMetricLevel(builder), resolveDetailedMetrics(builder)); this.metricUploader = new MetricUploader(resolveClient(builder)); this.maximumCallsPerUpload = resolveMaximumCallsPerUpload(builder); ThreadFactory threadFactory = new ThreadFactoryBuilder().threadNamePrefix("cloud-watch-metric-publisher").build(); this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(threadFactory); // Do not increase above 1 thread: access to MetricCollectionAggregator is not thread safe. this.executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(MAXIMUM_TASK_QUEUE_SIZE), threadFactory); long flushFrequencyInMillis = resolveUploadFrequency(builder).toMillis(); this.scheduledExecutor.scheduleAtFixedRate(this::flushMetricsQuietly, flushFrequencyInMillis, flushFrequencyInMillis, TimeUnit.MILLISECONDS); } private Set<MetricCategory> resolveMetricCategories(Builder builder) { return builder.metricCategories == null ? DEFAULT_METRIC_CATEGORIES : new HashSet<>(builder.metricCategories); } private MetricLevel resolveMetricLevel(Builder builder) { return builder.metricLevel == null ? DEFAULT_METRIC_LEVEL : builder.metricLevel; } private Set<SdkMetric<?>> resolveDetailedMetrics(Builder builder) { return builder.detailedMetrics == null ? DEFAULT_DETAILED_METRICS : new HashSet<>(builder.detailedMetrics); } private Set<SdkMetric<String>> resolveDimensions(Builder builder) { return builder.dimensions == null ? DEFAULT_DIMENSIONS : new HashSet<>(builder.dimensions); } private boolean resolveCloseClientWithPublisher(Builder builder) { return builder.client == null; } private CloudWatchAsyncClient resolveClient(Builder builder) { return builder.client == null ? CloudWatchAsyncClient.create() : builder.client; } private Duration resolveUploadFrequency(Builder builder) { return builder.uploadFrequency == null ? DEFAULT_UPLOAD_FREQUENCY : builder.uploadFrequency; } private String resolveNamespace(Builder builder) { return builder.namespace == null ? DEFAULT_NAMESPACE : builder.namespace; } private int resolveMaximumCallsPerUpload(Builder builder) { return builder.maximumCallsPerUpload == null ? DEFAULT_MAXIMUM_CALLS_PER_UPLOAD : builder.maximumCallsPerUpload; } @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } /** * Flush the metrics (via a {@link UploadMetricsTasks}). In the event that the {@link #executor} task queue is full, this * this will retry automatically. * * This returns when the {@code UploadMetricsTask} has been submitted to the executor. The returned future is completed * when the metrics upload to cloudwatch has started. The inner-most future is finally completed when the upload to cloudwatch * has finished. */ private Future<CompletableFuture<?>> flushMetrics() throws InterruptedException { while (!executor.isShutdown()) { try { return executor.submit(new UploadMetricsTasks(metricAggregator, metricUploader, maximumCallsPerUpload)); } catch (RejectedExecutionException e) { Thread.sleep(100); } } return CompletableFuture.completedFuture(CompletableFuture.completedFuture(null)); } private void flushMetricsQuietly() { try { flushMetrics(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); METRIC_LOGGER.error(() -> "Interrupted during metric flushing.", e); } } @Override public void close() { try { scheduledExecutor.shutdownNow(); Future<CompletableFuture<?>> flushFuture = flushMetrics(); executor.shutdown(); flushFuture.get(60, TimeUnit.SECONDS) // Wait for flush to start .get(60, TimeUnit.SECONDS); // Wait for flush to finish if (!executor.awaitTermination(60, TimeUnit.SECONDS)) { throw new TimeoutException("Internal executor did not shut down in 60 seconds."); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); METRIC_LOGGER.error(() -> "Interrupted during graceful metric publisher shutdown.", e); } catch (ExecutionException e) { METRIC_LOGGER.error(() -> "Failed during graceful metric publisher shutdown.", e); } catch (TimeoutException e) { METRIC_LOGGER.error(() -> "Timed out during graceful metric publisher shutdown.", e); } finally { runQuietly(scheduledExecutor::shutdownNow, "shutting down scheduled executor"); runQuietly(executor::shutdownNow, "shutting down executor"); runQuietly(() -> metricUploader.close(closeClientWithPublisher), "closing metric uploader"); } } private void runQuietly(Runnable runnable, String taskName) { try { runnable.run(); } catch (Exception e) { METRIC_LOGGER.warn(() -> "Failed while " + taskName + ".", e); } } /** * Create a new {@link Builder} that can be used to create {@link CloudWatchMetricPublisher}s. */ public static Builder builder() { return new Builder(); } /** * Create a {@link CloudWatchMetricPublisher} using all default values. */ public static CloudWatchMetricPublisher create() { return builder().build(); } /** * Returns {@code true} when the internal executors for this publisher are shut down. */ boolean isShutdown() { return scheduledExecutor.isShutdown() && executor.isShutdown(); } /** * Builder class to construct {@link CloudWatchMetricPublisher} instances. See the individual properties for which * configuration settings are available. */ public static final class Builder { private CloudWatchAsyncClient client; private Duration uploadFrequency; private String namespace; private Integer maximumCallsPerUpload; private Collection<SdkMetric<String>> dimensions; private Collection<MetricCategory> metricCategories; private MetricLevel metricLevel; private Collection<SdkMetric<?>> detailedMetrics; private Builder() { } /** * Configure the {@link PutMetricDataRequest#namespace()} used for all put-metric-data calls from this publisher. * * <p>If this is not specified, {@code AwsSdk/JavaSdk2} will be used. */ public Builder namespace(String namespace) { this.namespace = namespace; return this; } /** * Configure the {@link CloudWatchAsyncClient} instance that should be used to communicate with CloudWatch. * * <p>If this is not specified, the {@code CloudWatchAsyncClient} will be created via * {@link CloudWatchAsyncClient#create()} (and will be closed when {@link #close()} is invoked). * * <p>If you specify a {@code CloudWatchAsyncClient} via this method, it <i>will not</i> be closed when this publisher * is closed. You will need to need to manage the lifecycle of the client yourself. */ public Builder cloudWatchClient(CloudWatchAsyncClient client) { this.client = client; return this; } /** * Configure the frequency at which aggregated metrics are uploaded to CloudWatch and released from memory. * * <p>If this is not specified, metrics will be uploaded once per minute. * * <p>Smaller values will: (1) reduce the amount of memory used by the library (particularly when * {@link #detailedMetrics(Collection)} are enabled), (2) increase the number of CloudWatch calls (and therefore * increase CloudWatch usage cost). * * <p>Larger values will: (1) increase the amount of memory used by the library (particularly when * {@code detailedMetrics} are enabled), (2) increase the time it takes for metric data to appear in * CloudWatch, (3) reduce the number of CloudWatch calls (and therefore decrease CloudWatch usage cost). * * <p><b>Warning:</b> When {@code detailedMetrics} are enabled, all unique metric values are stored in memory until they * can be published to CloudWatch. A high {@code uploadFrequency} with multiple {@code detailedMetrics} enabled can * quickly consume heap memory while the values wait to be published to CloudWatch. In memory constrained environments, it * is recommended to minimize the number of {@code detailedMetrics} configured on the publisher, or to upload metric data * more frequently. As with all performance and resource concerns, profiling in a production-like environment is * encouraged. */ public Builder uploadFrequency(Duration uploadFrequency) { this.uploadFrequency = uploadFrequency; return this; } /** * Configure the maximum number of {@link CloudWatchAsyncClient#putMetricData(PutMetricDataRequest)} calls that an * individual "upload" event can make to CloudWatch. Any metrics that would exceed this limit are dropped during the * upload, logging a warning on the {@code software.amazon.awssdk.metrics.publishers.cloudwatch} namespace. * * <p>The SDK will always attempt to maximize the number of metrics per put-metric-data call, but uploads will be split * into multiple put-metric-data calls if they include a lot of different metrics or if there are a lot of high-value- * distribution {@link #detailedMetrics(Collection)} being monitored. * * <p>This value combined with the {@link #uploadFrequency(Duration)} effectively provide a "hard cap" on the number of * put-metric-data calls, to prevent unbounded cost in the event that too many metrics are enabled by the user. * * <p>If this is not specified, put-metric-data calls will be capped at 10 per upload. */ public Builder maximumCallsPerUpload(Integer maximumCallsPerUpload) { this.maximumCallsPerUpload = maximumCallsPerUpload; return this; } /** * Configure the {@link SdkMetric}s that are used to define the {@link Dimension}s metrics are aggregated under. * * <p>If this is not specified, {@link CoreMetric#SERVICE_ID} and {@link CoreMetric#OPERATION_NAME} are used, allowing * you to compare metrics for different services and operations. * * <p><b>Warning:</b> Configuring the dimensions incorrectly can result in a large increase in the number of unique * metrics and put-metric-data calls to cloudwatch, which have an associated monetary cost. Be sure you're choosing your * metric dimensions wisely, and that you always evaluate the cost of modifying these values on your monthly usage costs. * * <p><b>Example useful settings:</b> * <ul> * <li>{@code CoreMetric.SERVICE_ID} and {@code CoreMetric.OPERATION_NAME} (default): Separate metrics by service and * operation, so that you can compare latencies between AWS services and operations.</li> * <li>{@code CoreMetric.SERVICE_ID}, {@code CoreMetric.OPERATION_NAME} and {@code CoreMetric.HOST_NAME}: Separate * metrics by service, operation and host so that you can compare latencies across hosts in your fleet. Note: This should * only be used when your fleet is relatively small. Large fleets result in a large number of unique metrics being * generated.</li> * <li>{@code CoreMetric.SERVICE_ID}, {@code CoreMetric.OPERATION_NAME} and {@code HttpMetric.HTTP_CLIENT_NAME}: Separate * metrics by service, operation and HTTP client type so that you can compare latencies between different HTTP client * implementations.</li> * </ul> */ public Builder dimensions(Collection<SdkMetric<String>> dimensions) { this.dimensions = new ArrayList<>(dimensions); return this; } /** * @see #dimensions(SdkMetric[]) */ @SafeVarargs public final Builder dimensions(SdkMetric<String>... dimensions) { return dimensions(Arrays.asList(dimensions)); } /** * Configure the {@link MetricCategory}s that should be uploaded to CloudWatch. * * <p>If this is not specified, {@link MetricCategory#ALL} is used. * * <p>All {@link SdkMetric}s are associated with at least one {@code MetricCategory}. This setting determines which * category of metrics uploaded to CloudWatch. Any metrics {@link #publish(MetricCollection)}ed that do not fall under * these configured categories are ignored. * * <p>Note: If there are {@link #dimensions(Collection)} configured that do not fall under these {@code MetricCategory} * values, the dimensions will NOT be ignored. In other words, the metric category configuration only affects which * metrics are uploaded to CloudWatch, not which values can be used for {@code dimensions}. */ public Builder metricCategories(Collection<MetricCategory> metricCategories) { this.metricCategories = new ArrayList<>(metricCategories); return this; } /** * @see #metricCategories(Collection) */ public Builder metricCategories(MetricCategory... metricCategories) { return metricCategories(Arrays.asList(metricCategories)); } /** * Configure the {@link MetricLevel} that should be uploaded to CloudWatch. * * <p>If this is not specified, {@link MetricLevel#INFO} is used. * * <p>All {@link SdkMetric}s are associated with one {@code MetricLevel}. This setting determines which level of metrics * uploaded to CloudWatch. Any metrics {@link #publish(MetricCollection)}ed that do not fall under these configured * categories are ignored. * * <p>Note: If there are {@link #dimensions(Collection)} configured that do not fall under this {@code MetricLevel} * values, the dimensions will NOT be ignored. In other words, the metric category configuration only affects which * metrics are uploaded to CloudWatch, not which values can be used for {@code dimensions}. */ public Builder metricLevel(MetricLevel metricLevel) { this.metricLevel = metricLevel; return this; } /** * Configure the set of metrics for which detailed values and counts are uploaded to CloudWatch, instead of summaries. * * <p>By default, all metrics published to this publisher are summarized using {@link StatisticSet}s. This saves memory, * because it allows the publisher to store a fixed amount of information in memory, no matter how many different metric * values are published. The drawback is that metrics other than count, sum, average, maximum and minimum are not made * available in CloudWatch. The {@code detailedMetrics} setting instructs the publisher to store and publish itemized * {@link MetricDatum#values()} and {@link MetricDatum#counts()}, which enables other metrics like p90 and p99 to be * queried in CloudWatch. * * <p><b>Warning:</b> When {@code detailedMetrics} are enabled, all unique metric values are stored in memory until they * can be published to CloudWatch. A high {@code uploadFrequency} with multiple {@code detailedMetrics} enabled can * quickly consume heap memory while the values wait to be published to CloudWatch. In memory constrained environments, it * is recommended to minimize the number of {@code detailedMetrics} configured on the publisher, or to upload metric data * more frequently. As with all performance and resource concerns, profiling in a production-like environment is * encouraged. * * <p>In addition to additional heap memory usage, detailed metrics can result in more requests being sent to CloudWatch, * which can also introduce additional usage cost. The {@link #maximumCallsPerUpload(Integer)} acts as a safeguard against * too many calls being made, but if you configure multiple {@code detailedMetrics}, you may need to increase the * {@code maximumCallsPerUpload} limit. */ public Builder detailedMetrics(Collection<SdkMetric<?>> detailedMetrics) { this.detailedMetrics = new ArrayList<>(detailedMetrics); return this; } /** * @see #detailedMetrics(Collection) */ public Builder detailedMetrics(SdkMetric<?>... detailedMetrics) { return detailedMetrics(Arrays.asList(detailedMetrics)); } /** * Build a {@link CloudWatchMetricPublisher} using the configuration currently configured on this publisher. */ public CloudWatchMetricPublisher build() { return new CloudWatchMetricPublisher(this); } } }
3,188
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/MetricUploader.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal; import static software.amazon.awssdk.metrics.publishers.cloudwatch.internal.CloudWatchMetricLogger.METRIC_LOGGER; import java.util.List; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest; /** * Uploads {@link PutMetricDataRequest}s to a {@link CloudWatchAsyncClient}, logging whether it was successful or a failure to * the {@link CloudWatchMetricLogger#METRIC_LOGGER}. */ @SdkInternalApi public class MetricUploader { private final CloudWatchAsyncClient cloudWatchClient; public MetricUploader(CloudWatchAsyncClient cloudWatchClient) { this.cloudWatchClient = cloudWatchClient; } /** * Upload the provided list of requests to CloudWatch, completing the returned future when the uploads complete. Note: This * will log a message if one of the provided requests fails. */ public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } private CompletableFuture<?>[] startCalls(List<PutMetricDataRequest> requests) { return requests.stream() .peek(this::logRequest) .map(cloudWatchClient::putMetricData) .toArray(CompletableFuture[]::new); } private void logRequest(PutMetricDataRequest putMetricDataRequest) { METRIC_LOGGER.trace(() -> "Sending request to CloudWatch: " + putMetricDataRequest); } public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } }
3,189
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/CloudWatchMetricLogger.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Logger; /** * A holder for {@link #METRIC_LOGGER}. */ @SdkInternalApi public class CloudWatchMetricLogger { /** * The logger via which all cloudwatch-metric-publisher logs are written. This allows customers to easily enable/disable logs * written from this module. */ public static final Logger METRIC_LOGGER = Logger.loggerFor("software.amazon.awssdk.metrics.publishers.cloudwatch"); private CloudWatchMetricLogger() { } }
3,190
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/task/AggregateMetricsTask.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.task; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.publishers.cloudwatch.CloudWatchMetricPublisher; import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.MetricCollectionAggregator; /** * A task that is executed on the {@link CloudWatchMetricPublisher}'s executor to add a {@link MetricCollection} to a * {@link MetricCollectionAggregator}. */ @SdkInternalApi public class AggregateMetricsTask implements Runnable { private final MetricCollectionAggregator collectionAggregator; private final MetricCollection metricCollection; public AggregateMetricsTask(MetricCollectionAggregator collectionAggregator, MetricCollection metricCollection) { this.collectionAggregator = collectionAggregator; this.metricCollection = metricCollection; } @Override public void run() { collectionAggregator.addCollection(metricCollection); } }
3,191
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/task/UploadMetricsTasks.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.task; import static software.amazon.awssdk.metrics.publishers.cloudwatch.internal.CloudWatchMetricLogger.METRIC_LOGGER; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.metrics.publishers.cloudwatch.CloudWatchMetricPublisher; import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.MetricUploader; import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.MetricCollectionAggregator; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest; import software.amazon.awssdk.utils.CompletableFutureUtils; /** * A task that is executed on the {@link CloudWatchMetricPublisher}'s executor to collect requests from a * {@link MetricCollectionAggregator} and write them to a {@link MetricUploader}. */ @SdkInternalApi public class UploadMetricsTasks implements Callable<CompletableFuture<?>> { private final MetricCollectionAggregator collectionAggregator; private final MetricUploader uploader; private int maximumRequestsPerFlush; public UploadMetricsTasks(MetricCollectionAggregator collectionAggregator, MetricUploader uploader, int maximumRequestsPerFlush) { this.collectionAggregator = collectionAggregator; this.uploader = uploader; this.maximumRequestsPerFlush = maximumRequestsPerFlush; } @Override public CompletableFuture<?> call() { try { List<PutMetricDataRequest> allRequests = collectionAggregator.getRequests(); List<PutMetricDataRequest> requests = allRequests; if (requests.size() > maximumRequestsPerFlush) { METRIC_LOGGER.warn(() -> "Maximum AWS SDK client-side metric call count exceeded: " + allRequests.size() + " > " + maximumRequestsPerFlush + ". Some metric requests will be dropped. This occurs " + "when the caller has configured too many metrics or too unique of dimensions without " + "an associated increase in the maximum-calls-per-upload configured on the publisher."); requests = requests.subList(0, maximumRequestsPerFlush); } return uploader.upload(requests); } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } } }
3,192
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/MetricValueNormalizer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi class MetricValueNormalizer { /** * Really small values (close to 0) result in CloudWatch failing with an "unsupported value" error. Make sure that we floor * those values to 0 to prevent that error. */ private static final double ZERO_THRESHOLD = 0.0001; private MetricValueNormalizer() { } /** * Normalizes a metric value so that it won't upset CloudWatch when it is uploaded. */ public static double normalize(double value) { if (value > ZERO_THRESHOLD) { return value; } if (value < -ZERO_THRESHOLD) { return value; } return 0; } }
3,193
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/MetricAggregatorKey.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.services.cloudwatch.model.Dimension; /** * A pairing of {@link SdkMetric} and {@link Dimension}s that can be used as a key in a map. This uniquely identifies a specific * {@link MetricAggregator}. */ @SdkInternalApi class MetricAggregatorKey { private final SdkMetric<?> metric; private final List<Dimension> dimensions; MetricAggregatorKey(SdkMetric<?> metric, List<Dimension> dimensions) { this.metric = metric; this.dimensions = dimensions; } public final SdkMetric<?> metric() { return this.metric; } public final List<Dimension> dimensions() { return this.dimensions; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MetricAggregatorKey that = (MetricAggregatorKey) o; if (!metric.equals(that.metric)) { return false; } return dimensions.equals(that.dimensions); } @Override public int hashCode() { int result = metric.hashCode(); result = 31 * result + dimensions.hashCode(); return result; } }
3,194
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/MetricAggregator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.metrics.publishers.cloudwatch.CloudWatchMetricPublisher; import software.amazon.awssdk.services.cloudwatch.model.Dimension; import software.amazon.awssdk.services.cloudwatch.model.MetricDatum; import software.amazon.awssdk.services.cloudwatch.model.StandardUnit; /** * Used by {@link MetricCollectionAggregator} to aggregate metrics in memory until they are ready to be added to a * {@link MetricDatum}. * * <p>This is either a {@link SummaryMetricAggregator} or a {@link DetailedMetricAggregator}, depending on the configured * {@link CloudWatchMetricPublisher.Builder#detailedMetrics(Collection)} setting. */ @SdkInternalApi interface MetricAggregator { /** * The metric that this aggregator is aggregating. For example, this may be aggregating {@link CoreMetric#API_CALL_DURATION} * metric values. There may be multiple aggregators for a single type of metric, when their {@link #dimensions()} differ. */ SdkMetric<?> metric(); /** * The dimensions associated with the metric values that this aggregator is aggregating. For example, this may be aggregating * "S3's putObject" metrics or "DynamoDb's listTables" metrics. The exact metric being aggregated is available via * {@link #metric()}. */ List<Dimension> dimensions(); /** * Get the unit of the {@link #metric()} when it is published to CloudWatch. */ StandardUnit unit(); /** * Add the provided metric value to this aggregator. */ void addMetricValue(double value); /** * Execute the provided consumer if this {@code MetricAggregator} is a {@link SummaryMetricAggregator}. */ default void ifSummary(Consumer<SummaryMetricAggregator> summaryConsumer) { if (this instanceof SummaryMetricAggregator) { summaryConsumer.accept((SummaryMetricAggregator) this); } } /** * Execute the provided consumer if this {@code MetricAggregator} is a {@link DetailedMetricAggregator}. */ default void ifDetailed(Consumer<DetailedMetricAggregator> detailsConsumer) { if (this instanceof DetailedMetricAggregator) { detailsConsumer.accept((DetailedMetricAggregator) this); } } }
3,195
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/SummaryMetricAggregator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.services.cloudwatch.model.Dimension; import software.amazon.awssdk.services.cloudwatch.model.MetricDatum; import software.amazon.awssdk.services.cloudwatch.model.StandardUnit; /** * An implementation of {@link MetricAggregator} that stores summary statistics for a given metric/dimension pair until the * summary can be added to a {@link MetricDatum}. */ @SdkInternalApi class SummaryMetricAggregator implements MetricAggregator { private final SdkMetric<?> metric; private final List<Dimension> dimensions; private final StandardUnit unit; private double min = Double.MAX_VALUE; private double max = Double.MIN_VALUE; private double sum = 0; private int count = 0; SummaryMetricAggregator(MetricAggregatorKey key, StandardUnit unit) { this.metric = key.metric(); this.dimensions = key.dimensions(); this.unit = unit; } @Override public SdkMetric<?> metric() { return metric; } @Override public List<Dimension> dimensions() { return dimensions; } @Override public void addMetricValue(double value) { min = Double.min(value, min); max = Double.max(value, max); sum += value; ++count; } @Override public StandardUnit unit() { return unit; } public double min() { return min; } public double max() { return max; } public double sum() { return sum; } public int count() { return count; } }
3,196
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/DetailedMetricAggregator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.services.cloudwatch.model.Dimension; import software.amazon.awssdk.services.cloudwatch.model.MetricDatum; import software.amazon.awssdk.services.cloudwatch.model.StandardUnit; /** * An implementation of {@link MetricAggregator} that stores all values and counts for a given metric/dimension pair * until they can be added to a {@link MetricDatum}. */ @SdkInternalApi class DetailedMetricAggregator implements MetricAggregator { private final SdkMetric<?> metric; private final List<Dimension> dimensions; private final StandardUnit unit; private final Map<Double, DetailedMetrics> metricDetails = new HashMap<>(); DetailedMetricAggregator(MetricAggregatorKey key, StandardUnit unit) { this.metric = key.metric(); this.dimensions = key.dimensions(); this.unit = unit; } @Override public SdkMetric<?> metric() { return metric; } @Override public List<Dimension> dimensions() { return dimensions; } @Override public void addMetricValue(double value) { metricDetails.computeIfAbsent(value, v -> new DetailedMetrics(value)).metricCount++; } @Override public StandardUnit unit() { return unit; } public Collection<DetailedMetrics> detailedMetrics() { return Collections.unmodifiableCollection(metricDetails.values()); } public static class DetailedMetrics { private final double metricValue; private int metricCount = 0; private DetailedMetrics(double metricValue) { this.metricValue = metricValue; } public double metricValue() { return metricValue; } public int metricCount() { return metricCount; } } }
3,197
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/MetricCollectionAggregator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.metrics.MetricCategory; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricLevel; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.DetailedMetricAggregator.DetailedMetrics; import software.amazon.awssdk.services.cloudwatch.model.MetricDatum; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest; import software.amazon.awssdk.services.cloudwatch.model.StatisticSet; /** * Aggregates {@link MetricCollection}s by: (1) the minute in which they occurred, and (2) the dimensions in the collection * associated with that metric. Allows retrieving the aggregated values as a list of {@link PutMetricDataRequest}s. * * <p>It would be too expensive to upload every {@code MetricCollection} as a unique {@code PutMetricDataRequest}, so this * class aggregates the data so that multiple {@code MetricCollection}s can be placed in the same {@code PutMetricDataRequest}. * * <p><b>Warning:</b> This class is *not* thread-safe. */ @SdkInternalApi @NotThreadSafe public class MetricCollectionAggregator { /** * The maximum number of {@link MetricDatum}s allowed in {@link PutMetricDataRequest#metricData()}. This limit is imposed by * CloudWatch. */ public static final int MAX_METRIC_DATA_PER_REQUEST = 20; /** * The maximum number of unique {@link MetricDatum#values()} allowed in a single {@link PutMetricDataRequest}. This limit is * not imposed directly by CloudWatch, but they do impose a 40KB limit for a single request. This value was determined by * trial-and-error to roughly equate to a 40KB limit when we are also at the {@link #MAX_METRIC_DATA_PER_REQUEST}. */ public static final int MAX_VALUES_PER_REQUEST = 300; /** * The API name to include in the user agent for all {@link PutMetricDataRequest}s generated by this aggregator. */ private static final ApiName API_NAME = ApiName.builder().name("hll").version("cw-mp").build(); /** * The {@link PutMetricDataRequest#namespace()} that should be used for all {@link PutMetricDataRequest}s returned from * {@link #getRequests()}. */ private final String namespace; /** * The {@link TimeBucketedMetrics} that actually performs the data aggregation whenever * {@link #addCollection(MetricCollection)} is called. */ private final TimeBucketedMetrics timeBucketedMetrics; public MetricCollectionAggregator(String namespace, Set<SdkMetric<String>> dimensions, Set<MetricCategory> metricCategories, MetricLevel metricLevel, Set<SdkMetric<?>> detailedMetrics) { this.namespace = namespace; this.timeBucketedMetrics = new TimeBucketedMetrics(dimensions, metricCategories, metricLevel, detailedMetrics); } /** * Add a collection to this aggregator. */ public void addCollection(MetricCollection collection) { timeBucketedMetrics.addMetrics(collection); } /** * Get all {@link PutMetricDataRequest}s that can be generated from the data that was added via * {@link #addCollection(MetricCollection)}. This method resets the state of this {@code MetricCollectionAggregator}. */ public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } private MetricDatum detailedMetricDatum(Instant timeBucket, DetailedMetricAggregator metric, int metricStartIndex, int maxElements) { List<Double> values = new ArrayList<>(); List<Double> counts = new ArrayList<>(); Stream<DetailedMetrics> boundedMetrics = metric.detailedMetrics() .stream() .skip(metricStartIndex) .limit(maxElements); boundedMetrics.forEach(detailedMetrics -> { values.add(MetricValueNormalizer.normalize(detailedMetrics.metricValue())); counts.add((double) detailedMetrics.metricCount()); }); return MetricDatum.builder() .timestamp(timeBucket) .metricName(metric.metric().name()) .dimensions(metric.dimensions()) .unit(metric.unit()) .values(values) .counts(counts) .build(); } private MetricDatum summaryMetricDatum(Instant timeBucket, SummaryMetricAggregator metric) { StatisticSet stats = StatisticSet.builder() .minimum(MetricValueNormalizer.normalize(metric.min())) .maximum(MetricValueNormalizer.normalize(metric.max())) .sum(MetricValueNormalizer.normalize(metric.sum())) .sampleCount((double) metric.count()) .build(); return MetricDatum.builder() .timestamp(timeBucket) .metricName(metric.metric().name()) .dimensions(metric.dimensions()) .unit(metric.unit()) .statisticValues(stats) .build(); } private PutMetricDataRequest newPutRequest(List<MetricDatum> metricData) { return PutMetricDataRequest.builder() .overrideConfiguration(r -> r.addApiName(API_NAME)) .namespace(namespace) .metricData(metricData) .build(); } private static class ValuesInRequestCounter { private int valuesInRequest; private void add(int i) { valuesInRequest += i; } private int get() { return valuesInRequest; } private void reset() { valuesInRequest = 0; } } }
3,198
0
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal
Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/TimeBucketedMetrics.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform; import static java.time.temporal.ChronoUnit.MINUTES; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.metrics.MetricCategory; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricLevel; import software.amazon.awssdk.metrics.MetricRecord; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.services.cloudwatch.model.Dimension; import software.amazon.awssdk.services.cloudwatch.model.StandardUnit; /** * "Buckets" metrics by the minute in which they were collected. This allows all metric data for a given 1-minute period to be * aggregated under a specific {@link MetricAggregator}. */ @SdkInternalApi class TimeBucketedMetrics { /** * A map from "the minute during which a metric value happened" to "the dimension and metric associated with the metric * values" to "the aggregator for the metric values that occurred within that minute and for that dimension/metric". */ private final Map<Instant, Map<MetricAggregatorKey, MetricAggregator>> timeBucketedMetrics = new HashMap<>(); /** * The dimensions that should be used for aggregating metrics that occur within a given minute. These are optional values. * The dimensions will be used if a {@link MetricCollection} includes them, but if it does not, it will be aggregated with * whatever dimensions (if any) are available. */ private final Set<SdkMetric<String>> dimensions; /** * The set of metrics for which {@link DetailedMetricAggregator}s should be used for aggregation. All other metrics will use * a {@link SummaryMetricAggregator}. */ private final Set<SdkMetric<?>> detailedMetrics; /** * The metric categories for which we should aggregate values. Any categories outside of this set will have their values * ignored/dropped. */ private final Set<MetricCategory> metricCategories; /** * The metric levels for which we should aggregate values. Any categories at a more "verbose" level than this one will have * their values ignored/dropped. */ private final MetricLevel metricLevel; /** * True, when the {@link #metricCategories} contains {@link MetricCategory#ALL}. */ private final boolean metricCategoriesContainsAll; TimeBucketedMetrics(Set<SdkMetric<String>> dimensions, Set<MetricCategory> metricCategories, MetricLevel metricLevel, Set<SdkMetric<?>> detailedMetrics) { this.dimensions = dimensions; this.detailedMetrics = detailedMetrics; this.metricCategories = metricCategories; this.metricLevel = metricLevel; this.metricCategoriesContainsAll = metricCategories.contains(MetricCategory.ALL); } /** * Add the provided collection to the proper bucket, based on the metric collection's time. */ public void addMetrics(MetricCollection metrics) { Instant bucket = getBucket(metrics); addMetricsToBucket(metrics, bucket); } /** * Reset this bucket, clearing all stored values. */ public void reset() { timeBucketedMetrics.clear(); } /** * Retrieve all values in this collection. The map key is the minute in which the metric values were collected, and the * map value are all of the metrics that were aggregated during that minute. */ public Map<Instant, Collection<MetricAggregator>> timeBucketedMetrics() { return timeBucketedMetrics.entrySet() .stream() .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().values())); } private Instant getBucket(MetricCollection metrics) { return metrics.creationTime().truncatedTo(MINUTES); } private void addMetricsToBucket(MetricCollection metrics, Instant bucketId) { aggregateMetrics(metrics, timeBucketedMetrics.computeIfAbsent(bucketId, i -> new HashMap<>())); } private void aggregateMetrics(MetricCollection metrics, Map<MetricAggregatorKey, MetricAggregator> bucket) { List<Dimension> dimensions = dimensions(metrics); extractAllMetrics(metrics).forEach(metricRecord -> { MetricAggregatorKey aggregatorKey = new MetricAggregatorKey(metricRecord.metric(), dimensions); valueFor(metricRecord).ifPresent(metricValue -> { bucket.computeIfAbsent(aggregatorKey, m -> newAggregator(aggregatorKey)) .addMetricValue(MetricValueNormalizer.normalize(metricValue)); }); }); } private List<Dimension> dimensions(MetricCollection metricCollection) { List<Dimension> result = new ArrayList<>(); for (MetricRecord<?> metricRecord : metricCollection) { if (dimensions.contains(metricRecord.metric())) { result.add(Dimension.builder() .name(metricRecord.metric().name()) .value((String) metricRecord.value()) .build()); } } // Sort the dimensions to make sure that the order in the input metric collection doesn't affect the result. // We use descending order just so that "ServiceName" is before "OperationName" when we use the default dimensions. result.sort(Comparator.comparing(Dimension::name).reversed()); return result; } private List<MetricRecord<?>> extractAllMetrics(MetricCollection metrics) { List<MetricRecord<?>> result = new ArrayList<>(); extractAllMetrics(metrics, result); return result; } private void extractAllMetrics(MetricCollection metrics, List<MetricRecord<?>> extractedMetrics) { for (MetricRecord<?> metric : metrics) { extractedMetrics.add(metric); } metrics.children().forEach(child -> extractAllMetrics(child, extractedMetrics)); } private MetricAggregator newAggregator(MetricAggregatorKey aggregatorKey) { SdkMetric<?> metric = aggregatorKey.metric(); StandardUnit metricUnit = unitFor(metric); if (detailedMetrics.contains(metric)) { return new DetailedMetricAggregator(aggregatorKey, metricUnit); } else { return new SummaryMetricAggregator(aggregatorKey, metricUnit); } } private StandardUnit unitFor(SdkMetric<?> metric) { Class<?> metricType = metric.valueClass(); if (Duration.class.isAssignableFrom(metricType)) { return StandardUnit.MILLISECONDS; } return StandardUnit.NONE; } private Optional<Double> valueFor(MetricRecord<?> metricRecord) { if (!shouldReport(metricRecord)) { return Optional.empty(); } Class<?> metricType = metricRecord.metric().valueClass(); if (Duration.class.isAssignableFrom(metricType)) { Duration durationMetricValue = (Duration) metricRecord.value(); long millis = durationMetricValue.toMillis(); return Optional.of((double) millis); } else if (Number.class.isAssignableFrom(metricType)) { Number numberMetricValue = (Number) metricRecord.value(); return Optional.of(numberMetricValue.doubleValue()); } else if (Boolean.class.isAssignableFrom(metricType)) { Boolean booleanMetricValue = (Boolean) metricRecord.value(); return Optional.of(booleanMetricValue ? 1.0 : 0.0); } return Optional.empty(); } private boolean shouldReport(MetricRecord<?> metricRecord) { return isSupportedCategory(metricRecord) && isSupportedLevel(metricRecord); } private boolean isSupportedCategory(MetricRecord<?> metricRecord) { return metricCategoriesContainsAll || metricRecord.metric() .categories() .stream() .anyMatch(metricCategories::contains); } private boolean isSupportedLevel(MetricRecord<?> metricRecord) { return metricLevel.includesLevel(metricRecord.metric().level()); } }
3,199