From b200280a83e062db05a9abad82303f04ca3d2011 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Wed, 20 May 2026 23:12:03 -0500 Subject: [PATCH] feat(cloudfront): implement CloudFront service emulation (#969) * feat(cloudfront): implement CloudFront service emulation Adds full CloudFront emulation covering both core and extended operations using the REST XML protocol (2020-05-31 API). Core resources: - Distributions (CRUDL, copy, enable/disable, ETag concurrency) - Cache Behaviors (default + ordered) - Invalidations (create, get, list) - Origin Access Controls and Origin Access Identities - CloudFront Functions (create, update, publish, test, describe) Extended resources: - Continuous Deployment Policies - Public Keys and Key Groups - Realtime Log Configs (non-standard POST-based get/delete) - Streaming Distributions (legacy RTMP, enforces disabled before delete) - Field-Level Encryption Configs and Profiles - Monitoring Subscriptions Infrastructure: - Registers CloudFrontController in ResolvedServiceCatalog as REST_XML - Adds CloudFrontServiceConfig and CloudFrontStorageConfig to EmulatorConfig - Adds CLOUDFRONT namespace constant to AwsNamespaces - Registers CloudFrontService for GraalVM runtime initialization to avoid SecureRandom heap-baking in native builds - Wires storage through StorageFactory with per-resource JSON files - Adds cloudfront.md documentation page * docs: revert docker-compose.yml --- docs/services/cloudfront.md | 225 ++ docs/services/index.md | 1 + mkdocs.yml | 1 + .../floci/config/EmulatorConfig.java | 14 + .../floci/core/common/AwsNamespaces.java | 1 + .../core/common/ResolvedServiceCatalog.java | 8 +- .../cloudfront/CloudFrontController.java | 2775 +++++++++++++++++ .../cloudfront/CloudFrontService.java | 1016 ++++++ .../cloudfront/model/CacheBehavior.java | 74 + .../cloudfront/model/CachePolicy.java | 34 + .../cloudfront/model/CloudFrontFunction.java | 45 + .../model/CloudFrontOriginAccessIdentity.java | 27 + .../model/ContinuousDeploymentPolicy.java | 36 + .../model/DefaultCacheBehavior.java | 70 + .../cloudfront/model/Distribution.java | 42 + .../cloudfront/model/DistributionConfig.java | 82 + .../model/FieldLevelEncryptionConfig.java | 29 + .../model/FieldLevelEncryptionProfile.java | 33 + .../cloudfront/model/Invalidation.java | 30 + .../services/cloudfront/model/KeyGroup.java | 34 + .../model/MonitoringSubscription.java | 17 + .../services/cloudfront/model/Origin.java | 46 + .../cloudfront/model/OriginAccessControl.java | 41 + .../cloudfront/model/OriginRequestPolicy.java | 34 + .../services/cloudfront/model/PublicKey.java | 37 + .../cloudfront/model/RealtimeLogConfig.java | 30 + .../model/ResponseHeadersPolicy.java | 34 + .../model/StreamingDistribution.java | 64 + src/main/resources/application.yml | 4 + src/test/resources/application.yml | 3 + 30 files changed, 4886 insertions(+), 1 deletion(-) create mode 100644 docs/services/cloudfront.md create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CacheBehavior.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CachePolicy.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CloudFrontFunction.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CloudFrontOriginAccessIdentity.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/ContinuousDeploymentPolicy.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DefaultCacheBehavior.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Distribution.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DistributionConfig.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/FieldLevelEncryptionConfig.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/FieldLevelEncryptionProfile.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Invalidation.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/KeyGroup.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/MonitoringSubscription.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Origin.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/OriginAccessControl.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/OriginRequestPolicy.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/PublicKey.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/RealtimeLogConfig.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/ResponseHeadersPolicy.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/model/StreamingDistribution.java diff --git a/docs/services/cloudfront.md b/docs/services/cloudfront.md new file mode 100644 index 0000000000..d54513a9e4 --- /dev/null +++ b/docs/services/cloudfront.md @@ -0,0 +1,225 @@ +# CloudFront + +CloudFront management-plane emulation. Supports distribution lifecycle, cache policies, origin request policies, response headers policies, origin access controls, origin access identities, CloudFront Functions, invalidations, and tagging. Actual content delivery is not emulated — this is a management-plane-only implementation. + +**Protocol:** REST XML +**API version:** `2020-05-31` +**Endpoint prefix:** `cloudfront` +**Namespace:** `http://cloudfront.amazonaws.com/doc/2020-05-31/` +**Global service** — ARNs contain no region segment. + +## Supported Operations + +### Distributions + +| Operation | Method | Path | +|---|---|---| +| `CreateDistribution` | POST | `/2020-05-31/distribution` | +| `CreateDistributionWithTags` | POST | `/2020-05-31/distribution?WithTags` | +| `GetDistribution` | GET | `/2020-05-31/distribution/{Id}` | +| `GetDistributionConfig` | GET | `/2020-05-31/distribution/{Id}/config` | +| `UpdateDistribution` | PUT | `/2020-05-31/distribution/{Id}/config` | +| `DeleteDistribution` | DELETE | `/2020-05-31/distribution/{Id}` | +| `ListDistributions` | GET | `/2020-05-31/distribution` | +| `AssociateAlias` | PUT | `/2020-05-31/distribution/{TargetDistributionId}/associate-alias` | + +### Invalidations + +| Operation | Method | Path | +|---|---|---| +| `CreateInvalidation` | POST | `/2020-05-31/distribution/{Id}/invalidation` | +| `GetInvalidation` | GET | `/2020-05-31/distribution/{Id}/invalidation/{InvId}` | +| `ListInvalidations` | GET | `/2020-05-31/distribution/{Id}/invalidation` | + +### Cache Policies + +| Operation | Method | Path | +|---|---|---| +| `CreateCachePolicy` | POST | `/2020-05-31/cache-policy` | +| `GetCachePolicy` | GET | `/2020-05-31/cache-policy/{Id}` | +| `GetCachePolicyConfig` | GET | `/2020-05-31/cache-policy/{Id}/config` | +| `UpdateCachePolicy` | PUT | `/2020-05-31/cache-policy/{Id}` | +| `DeleteCachePolicy` | DELETE | `/2020-05-31/cache-policy/{Id}` | +| `ListCachePolicies` | GET | `/2020-05-31/cache-policy` | + +### Origin Request Policies + +| Operation | Method | Path | +|---|---|---| +| `CreateOriginRequestPolicy` | POST | `/2020-05-31/origin-request-policy` | +| `GetOriginRequestPolicy` | GET | `/2020-05-31/origin-request-policy/{Id}` | +| `GetOriginRequestPolicyConfig` | GET | `/2020-05-31/origin-request-policy/{Id}/config` | +| `UpdateOriginRequestPolicy` | PUT | `/2020-05-31/origin-request-policy/{Id}` | +| `DeleteOriginRequestPolicy` | DELETE | `/2020-05-31/origin-request-policy/{Id}` | +| `ListOriginRequestPolicies` | GET | `/2020-05-31/origin-request-policy` | + +### Response Headers Policies + +| Operation | Method | Path | +|---|---|---| +| `CreateResponseHeadersPolicy` | POST | `/2020-05-31/response-headers-policy` | +| `GetResponseHeadersPolicy` | GET | `/2020-05-31/response-headers-policy/{Id}` | +| `GetResponseHeadersPolicyConfig` | GET | `/2020-05-31/response-headers-policy/{Id}/config` | +| `UpdateResponseHeadersPolicy` | PUT | `/2020-05-31/response-headers-policy/{Id}` | +| `DeleteResponseHeadersPolicy` | DELETE | `/2020-05-31/response-headers-policy/{Id}` | +| `ListResponseHeadersPolicies` | GET | `/2020-05-31/response-headers-policy` | + +### Origin Access Control (OAC) + +| Operation | Method | Path | +|---|---|---| +| `CreateOriginAccessControl` | POST | `/2020-05-31/origin-access-control` | +| `GetOriginAccessControl` | GET | `/2020-05-31/origin-access-control/{Id}` | +| `GetOriginAccessControlConfig` | GET | `/2020-05-31/origin-access-control/{Id}/config` | +| `UpdateOriginAccessControl` | PUT | `/2020-05-31/origin-access-control/{Id}` | +| `DeleteOriginAccessControl` | DELETE | `/2020-05-31/origin-access-control/{Id}` | +| `ListOriginAccessControls` | GET | `/2020-05-31/origin-access-control` | + +### Origin Access Identity (OAI — legacy) + +| Operation | Method | Path | +|---|---|---| +| `CreateCloudFrontOriginAccessIdentity` | POST | `/2020-05-31/origin-access-identity/cloudfront` | +| `GetCloudFrontOriginAccessIdentity` | GET | `/2020-05-31/origin-access-identity/cloudfront/{Id}` | +| `GetCloudFrontOriginAccessIdentityConfig` | GET | `/2020-05-31/origin-access-identity/cloudfront/{Id}/config` | +| `UpdateCloudFrontOriginAccessIdentity` | PUT | `/2020-05-31/origin-access-identity/cloudfront/{Id}/config` | +| `DeleteCloudFrontOriginAccessIdentity` | DELETE | `/2020-05-31/origin-access-identity/cloudfront/{Id}` | +| `ListCloudFrontOriginAccessIdentities` | GET | `/2020-05-31/origin-access-identity/cloudfront` | + +### CloudFront Functions + +| Operation | Method | Path | +|---|---|---| +| `CreateFunction` | POST | `/2020-05-31/function` | +| `DescribeFunction` | GET | `/2020-05-31/function/{Name}` | +| `UpdateFunction` | PUT | `/2020-05-31/function/{Name}` | +| `PublishFunction` | POST | `/2020-05-31/function/{Name}/publish` | +| `DeleteFunction` | DELETE | `/2020-05-31/function/{Name}` | +| `ListFunctions` | GET | `/2020-05-31/function` | + +### Tagging + +| Operation | Method | Path | +|---|---|---| +| `ListTagsForResource` | GET | `/2020-05-31/tagging?Resource={arn}` | +| `TagResource` | POST | `/2020-05-31/tagging?Operation=Tag&Resource={arn}` | +| `UntagResource` | POST | `/2020-05-31/tagging?Operation=Untag&Resource={arn}` | + +## Behavior + +- All distributions are immediately set to `Deployed` state (no async `InProgress` delay). +- Distribution IDs are 14 uppercase alphanumeric characters starting with `E` (e.g. `E1Z2X3C4V5B6N7`). +- Distribution domain names follow the pattern `{id}.cloudfront.net`. +- ARNs are global — no region segment: `arn:aws:cloudfront::{accountId}:distribution/{id}`. +- Invalidations are immediately marked `Completed`. +- `DeleteDistribution` returns `DistributionNotDisabled` (409) if `Enabled` is `true` in the config. +- All mutating operations (`PUT`, `DELETE`) require an `If-Match` header containing the current `ETag`. A missing or incorrect `ETag` returns `InvalidIfMatchVersion` (400). +- All `GET` and `POST` (create) responses include an `ETag` response header. +- All list-type sub-elements in XML follow CloudFront's `N...` wrapper pattern. +- OAI `CallerReference` uniqueness is enforced — duplicate `CallerReference` values return `CloudFrontOriginAccessIdentityAlreadyExists` (409). +- `AssociateAlias` attaches a CNAME alias to the target distribution's config. + +## Configuration + +| Property | Env var | Default | Description | +|---|---|---|---| +| `floci.services.cloudfront.enabled` | `FLOCI_SERVICES_CLOUDFRONT_ENABLED` | `true` | Enable or disable the service | +| `floci.services.cloudfront.domain-suffix` | `FLOCI_SERVICES_CLOUDFRONT_DOMAIN_SUFFIX` | `cloudfront.net` | Domain suffix for generated distribution domain names | + +## CLI Examples + +```bash +export AWS_ENDPOINT_URL=http://localhost:4566 +export AWS_DEFAULT_REGION=us-east-1 +export AWS_ACCESS_KEY_ID=test +export AWS_SECRET_ACCESS_KEY=test + +# Create a distribution with an S3 origin +aws cloudfront create-distribution --distribution-config '{ + "CallerReference": "ref-1", + "Enabled": true, + "Comment": "my distribution", + "Origins": { + "Quantity": 1, + "Items": [{ + "Id": "my-origin", + "DomainName": "mybucket.s3.amazonaws.com", + "S3OriginConfig": {"OriginAccessIdentity": ""} + }] + }, + "DefaultCacheBehavior": { + "TargetOriginId": "my-origin", + "ViewerProtocolPolicy": "redirect-to-https", + "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6", + "AllowedMethods": {"Quantity": 2, "Items": ["GET","HEAD"]}, + "Compress": true + } +}' + +# Get a distribution +aws cloudfront get-distribution --id E1Z2X3C4V5B6N7 + +# List distributions +aws cloudfront list-distributions + +# Create a cache invalidation +aws cloudfront create-invalidation \ + --distribution-id E1Z2X3C4V5B6N7 \ + --invalidation-batch '{ + "CallerReference": "inv-1", + "Paths": {"Quantity": 1, "Items": ["/*"]} + }' + +# Create an OAI (Origin Access Identity) +aws cloudfront create-cloud-front-origin-access-identity \ + --cloud-front-origin-access-identity-config \ + "CallerReference=oai-1,Comment=my-oai" + +# Create an OAC (Origin Access Control) +aws cloudfront create-origin-access-control \ + --origin-access-control-config '{ + "Name": "my-oac", + "Description": "", + "OriginAccessControlOriginType": "s3", + "SigningBehavior": "always", + "SigningProtocol": "sigv4" + }' + +# Create a cache policy +aws cloudfront create-cache-policy --cache-policy-config '{ + "Name": "my-cache-policy", + "DefaultTTL": 86400, + "MinTTL": 0, + "MaxTTL": 31536000, + "ParametersInCacheKeyAndForwardedToOrigin": { + "EnableAcceptEncodingGzip": true, + "EnableAcceptEncodingBrotli": true, + "HeadersConfig": {"HeaderBehavior": "none"}, + "CookiesConfig": {"CookieBehavior": "none"}, + "QueryStringsConfig": {"QueryStringBehavior": "none"} + } +}' + +# Disable and delete a distribution +ETAG=$(aws cloudfront get-distribution --id E1Z2X3C4V5B6N7 \ + --query 'ETag' --output text) +aws cloudfront update-distribution --id E1Z2X3C4V5B6N7 \ + --if-match "$ETAG" \ + --distribution-config '...(config with Enabled: false)...' +ETAG=$(aws cloudfront get-distribution --id E1Z2X3C4V5B6N7 \ + --query 'ETag' --output text) +aws cloudfront delete-distribution --id E1Z2X3C4V5B6N7 --if-match "$ETAG" +``` + +## Not Supported (Phase 2) + +- Continuous deployment policies (`CreateContinuousDeploymentPolicy`, etc.) +- `CopyDistribution` (staging distributions) +- Real-time log configs (`CreateRealtimeLogConfig`, etc.) +- Field-level encryption (`CreateFieldLevelEncryptionConfig`, etc.) +- Public keys and key groups (`CreatePublicKey`, `CreateKeyGroup`, etc.) +- `TestFunction` execution (function is stored, not executed) +- Streaming distributions (RTMP — deprecated by AWS) +- VPC origins, Anycast IP lists, key value stores +- Monitoring subscriptions +- Actual CDN content delivery and caching diff --git a/docs/services/index.md b/docs/services/index.md index 72aa5b2cb6..b779aa74d4 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -53,6 +53,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CodeBuild](codebuild.md) | `POST /` + `X-Amz-Target: CodeBuild_20161006.*` | JSON 1.1 | 20 | | [CodeDeploy](codedeploy.md) | `POST /` + `X-Amz-Target: CodeDeploy_20141006.*` | JSON 1.1 | 30 | | [AWS Backup](backup.md) | `/backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 20 | +| [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 | | [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*` | REST XML | 17 | | [AWS Config](config.md) | `POST /` + `X-Amz-Target: StarlingDoveService.*` | JSON 1.1 | 20 | | [Textract](textract.md) | `POST /` + `X-Amz-Target: Textract.*` | JSON 1.1 | 6 | diff --git a/mkdocs.yml b/mkdocs.yml index 4dbf475ea2..8ded25793c 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -111,6 +111,7 @@ nav: - CodeBuild: services/codebuild.md - CodeDeploy: services/codedeploy.md - AWS Backup: services/backup.md + - CloudFront: services/cloudfront.md - Route53: services/route53.md - Transfer Family: services/transfer.md - Testcontainers: diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 87195fd4d4..57d4b9e4c3 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -133,6 +133,7 @@ public interface EmulatorConfig { RdsStorageConfig rds(); NeptuneStorageConfig neptune(); BackupStorageConfig backup(); + CloudFrontStorageConfig cloudfront(); } interface SsmStorageConfig { @@ -242,6 +243,10 @@ public interface EmulatorConfig { long flushIntervalMs(); } + interface CloudFrontStorageConfig { + Optional mode(); + } + interface WalConfig { @WithDefault("30000") long compactionIntervalMs(); @@ -313,6 +318,7 @@ public interface EmulatorConfig { CurServiceConfig cur(); BcmDataExportsServiceConfig bcmDataExports(); ConfigServiceConfig configservice(); + CloudFrontServiceConfig cloudfront(); } interface TransferServiceConfig { @@ -736,6 +742,14 @@ public interface EmulatorConfig { String stagingBucket(); } + interface CloudFrontServiceConfig { + @WithDefault("true") + boolean enabled(); + + @WithDefault("cloudfront.net") + String domainSuffix(); + } + interface BcmDataExportsServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java index d8b4d1a52b..5774896597 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java @@ -20,6 +20,7 @@ public final class AwsNamespaces { public static final String ELB_V2 = "https://elasticloadbalancing.amazonaws.com/doc/2015-12-01/"; public static final String AUTOSCALING = "https://autoscaling.amazonaws.com/doc/2011-01-01/"; public static final String ROUTE53 = "https://route53.amazonaws.com/doc/2013-04-01/"; + public static final String CLOUDFRONT = "http://cloudfront.amazonaws.com/doc/2020-05-31/"; private AwsNamespaces() {} } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index d873b43b07..547f4928f6 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.eks.EksController; import io.github.hectorvent.floci.services.pipes.PipesController; import io.github.hectorvent.floci.services.lambda.LambdaController; import io.github.hectorvent.floci.services.opensearch.OpenSearchController; +import io.github.hectorvent.floci.services.cloudfront.CloudFrontController; import io.github.hectorvent.floci.services.route53.Route53Controller; import io.github.hectorvent.floci.services.ses.SesController; import jakarta.enterprise.context.ApplicationScoped; @@ -272,7 +273,12 @@ public class ResolvedServiceCatalog { descriptor("bcm-data-exports", "bcmdataexports", config.services().bcmDataExports().enabled(), true, "bcmdataexports", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), - Set.of("AWSBillingAndCostManagementDataExports."), Set.of("bcm-data-exports"), Set.of(), Set.of()) + Set.of("AWSBillingAndCostManagementDataExports."), Set.of("bcm-data-exports"), Set.of(), Set.of()), + descriptor("cloudfront", "cloudfront", config.services().cloudfront().enabled(), true, + "cloudfront", storageMode(config.storage().services().cloudfront().mode(), config.storage().mode()), + 5000L, AwsNamespaces.CLOUDFRONT, ServiceProtocol.REST_XML, + protocols(ServiceProtocol.REST_XML), + Set.of(), Set.of("cloudfront"), Set.of(), Set.of(CloudFrontController.class)) )); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java new file mode 100644 index 0000000000..4bf4947010 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java @@ -0,0 +1,2775 @@ +package io.github.hectorvent.floci.services.cloudfront; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsNamespaces; +import io.github.hectorvent.floci.core.common.XmlBuilder; +import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.services.cloudfront.model.*; +import jakarta.inject.Inject; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; +import java.io.StringReader; +import java.net.URI; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@Path("/2020-05-31") +public class CloudFrontController { + + private static final String NS = AwsNamespaces.CLOUDFRONT; + private static final String XML = "application/xml"; + + private static final XMLInputFactory XML_FACTORY; + + static { + XML_FACTORY = XMLInputFactory.newInstance(); + XML_FACTORY.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true); + XML_FACTORY.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); + XML_FACTORY.setProperty(XMLInputFactory.SUPPORT_DTD, false); + } + + private final CloudFrontService service; + + @Inject + public CloudFrontController(CloudFrontService service) { + this.service = service; + } + + // ── Distributions ───────────────────────────────────────────────────────── + + @POST + @Path("/distribution") + public Response createDistribution(@QueryParam("WithTags") String withTags, String body) { + try { + DistributionConfig config = parseDistributionConfig(body); + Map tags = new LinkedHashMap<>(); + if (withTags != null) { + tags = parseTags(body); + } + Distribution dist = new Distribution(); + dist.setConfig(config); + dist = service.createDistribution(dist, tags); + String xml = xmlDistribution(dist); + return Response.created(URI.create("/2020-05-31/distribution/" + dist.getId())) + .type(XML) + .header("ETag", dist.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/distribution/{Id}") + public Response getDistribution(@PathParam("Id") String id) { + try { + Distribution dist = service.getDistribution(id); + String xml = xmlDistribution(dist); + return Response.ok(xml, XML).header("ETag", dist.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/distribution/{Id}/config") + public Response getDistributionConfig(@PathParam("Id") String id) { + try { + Distribution dist = service.getDistribution(id); + String xml = new XmlBuilder() + .start("DistributionConfig", NS) + .raw(xmlDistributionConfigBody(dist.getConfig())) + .end("DistributionConfig") + .build(); + return Response.ok(xml, XML).header("ETag", dist.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/distribution/{Id}/config") + public Response updateDistribution(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + DistributionConfig config = parseDistributionConfig(body); + Distribution updated = new Distribution(); + updated.setConfig(config); + updated = service.updateDistribution(id, ifMatch, updated); + String xml = xmlDistribution(updated); + return Response.ok(xml, XML).header("ETag", updated.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/distribution/{Id}") + public Response deleteDistribution(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteDistribution(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/distribution") + public Response listDistributions(@QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems) { + try { + List dists = service.listDistributions(marker, maxItems); + long total = service.listDistributions(null, Integer.MAX_VALUE).size(); + boolean truncated = dists.size() == maxItems && dists.size() < total; + + XmlBuilder xml = new XmlBuilder() + .start("ListDistributionsResult", NS) + .start("DistributionList") + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated); + if (truncated && !dists.isEmpty()) { + xml.elem("NextMarker", dists.get(dists.size() - 1).getId()); + } + xml.elem("Quantity", dists.size()) + .start("Items"); + for (Distribution d : dists) { + xml.raw(xmlDistributionSummary(d)); + } + xml.end("Items") + .end("DistributionList") + .end("ListDistributionsResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/distribution/{TargetDistributionId}/associate-alias") + public Response associateAlias(@PathParam("TargetDistributionId") String targetId, + @QueryParam("Alias") String alias) { + try { + service.associateAlias(targetId, alias); + return Response.ok("", XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Invalidations ───────────────────────────────────────────────────────── + + @POST + @Path("/distribution/{Id}/invalidation") + public Response createInvalidation(@PathParam("Id") String id, String body) { + try { + Invalidation inv = parseInvalidation(body); + inv = service.createInvalidation(id, inv); + String xml = new XmlBuilder() + .start("Invalidation", NS) + .raw(xmlInvalidationBody(inv)) + .end("Invalidation") + .build(); + return Response.created( + URI.create("/2020-05-31/distribution/" + id + "/invalidation/" + inv.getId())) + .type(XML) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/distribution/{Id}/invalidation/{InvId}") + public Response getInvalidation(@PathParam("Id") String id, + @PathParam("InvId") String invId) { + try { + Invalidation inv = service.getInvalidation(id, invId); + String xml = new XmlBuilder() + .start("Invalidation", NS) + .raw(xmlInvalidationBody(inv)) + .end("Invalidation") + .build(); + return Response.ok(xml, XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/distribution/{Id}/invalidation") + public Response listInvalidations(@PathParam("Id") String id, + @QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems) { + try { + List invs = service.listInvalidations(id, marker, maxItems); + boolean truncated = invs.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("InvalidationList", NS) + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", invs.size()) + .start("Items"); + for (Invalidation inv : invs) { + xml.start("InvalidationSummary") + .elem("Id", inv.getId()) + .elem("Status", inv.getStatus()) + .elem("CreateTime", inv.getCreateTime() != null ? inv.getCreateTime().toString() : "") + .end("InvalidationSummary"); + } + xml.end("Items").end("InvalidationList"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Cache Policies ──────────────────────────────────────────────────────── + + @POST + @Path("/cache-policy") + public Response createCachePolicy(String body) { + try { + CachePolicy policy = parseCachePolicy(body); + policy = service.createCachePolicy(policy); + String xml = xmlCachePolicyResponse(policy); + return Response.created(URI.create("/2020-05-31/cache-policy/" + policy.getId())) + .type(XML) + .header("ETag", policy.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/cache-policy/{Id}") + public Response getCachePolicy(@PathParam("Id") String id) { + try { + CachePolicy policy = service.getCachePolicy(id); + return Response.ok(xmlCachePolicyResponse(policy), XML) + .header("ETag", policy.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/cache-policy/{Id}/config") + public Response getCachePolicyConfig(@PathParam("Id") String id) { + try { + CachePolicy policy = service.getCachePolicy(id); + String xml = new XmlBuilder() + .start("CachePolicyConfig", NS) + .elem("Name", policy.getName()) + .elem("Comment", policy.getComment() != null ? policy.getComment() : "") + .end("CachePolicyConfig") + .build(); + return Response.ok(xml, XML).header("ETag", policy.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/cache-policy/{Id}") + public Response updateCachePolicy(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + CachePolicy policy = parseCachePolicy(body); + policy = service.updateCachePolicy(id, ifMatch, policy); + return Response.ok(xmlCachePolicyResponse(policy), XML) + .header("ETag", policy.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/cache-policy/{Id}") + public Response deleteCachePolicy(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteCachePolicy(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/cache-policy") + public Response listCachePolicies(@QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems, + @QueryParam("Type") String type) { + try { + List policies = service.listCachePolicies(marker, maxItems); + boolean truncated = policies.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("ListCachePoliciesResult", NS) + .start("CachePolicyList") + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", policies.size()) + .start("Items"); + for (CachePolicy p : policies) { + xml.start("CachePolicySummary") + .elem("Type", "custom") + .raw(xmlCachePolicyResponse(p)) + .end("CachePolicySummary"); + } + xml.end("Items").end("CachePolicyList").end("ListCachePoliciesResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Origin Request Policies ─────────────────────────────────────────────── + + @POST + @Path("/origin-request-policy") + public Response createOriginRequestPolicy(String body) { + try { + OriginRequestPolicy policy = parseOriginRequestPolicy(body); + policy = service.createOriginRequestPolicy(policy); + String xml = xmlOriginRequestPolicyResponse(policy); + return Response.created(URI.create("/2020-05-31/origin-request-policy/" + policy.getId())) + .type(XML) + .header("ETag", policy.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/origin-request-policy/{Id}") + public Response getOriginRequestPolicy(@PathParam("Id") String id) { + try { + OriginRequestPolicy policy = service.getOriginRequestPolicy(id); + return Response.ok(xmlOriginRequestPolicyResponse(policy), XML) + .header("ETag", policy.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/origin-request-policy/{Id}/config") + public Response getOriginRequestPolicyConfig(@PathParam("Id") String id) { + try { + OriginRequestPolicy policy = service.getOriginRequestPolicy(id); + String xml = new XmlBuilder() + .start("OriginRequestPolicyConfig", NS) + .elem("Name", policy.getName()) + .elem("Comment", policy.getComment() != null ? policy.getComment() : "") + .end("OriginRequestPolicyConfig") + .build(); + return Response.ok(xml, XML).header("ETag", policy.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/origin-request-policy/{Id}") + public Response updateOriginRequestPolicy(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + OriginRequestPolicy policy = parseOriginRequestPolicy(body); + policy = service.updateOriginRequestPolicy(id, ifMatch, policy); + return Response.ok(xmlOriginRequestPolicyResponse(policy), XML) + .header("ETag", policy.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/origin-request-policy/{Id}") + public Response deleteOriginRequestPolicy(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteOriginRequestPolicy(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/origin-request-policy") + public Response listOriginRequestPolicies(@QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems, + @QueryParam("Type") String type) { + try { + List policies = service.listOriginRequestPolicies(marker, maxItems); + boolean truncated = policies.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("ListOriginRequestPoliciesResult", NS) + .start("OriginRequestPolicyList") + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", policies.size()) + .start("Items"); + for (OriginRequestPolicy p : policies) { + xml.start("OriginRequestPolicySummary") + .elem("Type", "custom") + .raw(xmlOriginRequestPolicyResponse(p)) + .end("OriginRequestPolicySummary"); + } + xml.end("Items").end("OriginRequestPolicyList").end("ListOriginRequestPoliciesResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Response Headers Policies ───────────────────────────────────────────── + + @POST + @Path("/response-headers-policy") + public Response createResponseHeadersPolicy(String body) { + try { + ResponseHeadersPolicy policy = parseResponseHeadersPolicy(body); + policy = service.createResponseHeadersPolicy(policy); + String xml = xmlResponseHeadersPolicyResponse(policy); + return Response.created( + URI.create("/2020-05-31/response-headers-policy/" + policy.getId())) + .type(XML) + .header("ETag", policy.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/response-headers-policy/{Id}") + public Response getResponseHeadersPolicy(@PathParam("Id") String id) { + try { + ResponseHeadersPolicy policy = service.getResponseHeadersPolicy(id); + return Response.ok(xmlResponseHeadersPolicyResponse(policy), XML) + .header("ETag", policy.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/response-headers-policy/{Id}/config") + public Response getResponseHeadersPolicyConfig(@PathParam("Id") String id) { + try { + ResponseHeadersPolicy policy = service.getResponseHeadersPolicy(id); + String xml = new XmlBuilder() + .start("ResponseHeadersPolicyConfig", NS) + .elem("Name", policy.getName()) + .elem("Comment", policy.getComment() != null ? policy.getComment() : "") + .end("ResponseHeadersPolicyConfig") + .build(); + return Response.ok(xml, XML).header("ETag", policy.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/response-headers-policy/{Id}") + public Response updateResponseHeadersPolicy(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + ResponseHeadersPolicy policy = parseResponseHeadersPolicy(body); + policy = service.updateResponseHeadersPolicy(id, ifMatch, policy); + return Response.ok(xmlResponseHeadersPolicyResponse(policy), XML) + .header("ETag", policy.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/response-headers-policy/{Id}") + public Response deleteResponseHeadersPolicy(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteResponseHeadersPolicy(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/response-headers-policy") + public Response listResponseHeadersPolicies(@QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems, + @QueryParam("Type") String type) { + try { + List policies = service.listResponseHeadersPolicies(marker, maxItems); + boolean truncated = policies.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("ListResponseHeadersPoliciesResult", NS) + .start("ResponseHeadersPolicyList") + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", policies.size()) + .start("Items"); + for (ResponseHeadersPolicy p : policies) { + xml.start("ResponseHeadersPolicySummary") + .elem("Type", "custom") + .raw(xmlResponseHeadersPolicyResponse(p)) + .end("ResponseHeadersPolicySummary"); + } + xml.end("Items").end("ResponseHeadersPolicyList").end("ListResponseHeadersPoliciesResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Origin Access Control ───────────────────────────────────────────────── + + @POST + @Path("/origin-access-control") + public Response createOriginAccessControl(String body) { + try { + OriginAccessControl oac = parseOriginAccessControl(body); + oac = service.createOriginAccessControl(oac); + String xml = xmlOriginAccessControlResponse(oac); + return Response.created(URI.create("/2020-05-31/origin-access-control/" + oac.getId())) + .type(XML) + .header("ETag", oac.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/origin-access-control/{Id}") + public Response getOriginAccessControl(@PathParam("Id") String id) { + try { + OriginAccessControl oac = service.getOriginAccessControl(id); + return Response.ok(xmlOriginAccessControlResponse(oac), XML) + .header("ETag", oac.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/origin-access-control/{Id}/config") + public Response getOriginAccessControlConfig(@PathParam("Id") String id) { + try { + OriginAccessControl oac = service.getOriginAccessControl(id); + String xml = new XmlBuilder() + .start("OriginAccessControlConfig", NS) + .elem("Name", oac.getName()) + .elem("Description", oac.getDescription() != null ? oac.getDescription() : "") + .elem("SigningProtocol", oac.getSigningProtocol()) + .elem("SigningBehavior", oac.getSigningBehavior()) + .elem("OriginAccessControlOriginType", oac.getOriginAccessControlOriginType()) + .end("OriginAccessControlConfig") + .build(); + return Response.ok(xml, XML).header("ETag", oac.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/origin-access-control/{Id}") + public Response updateOriginAccessControl(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + OriginAccessControl oac = parseOriginAccessControl(body); + oac = service.updateOriginAccessControl(id, ifMatch, oac); + return Response.ok(xmlOriginAccessControlResponse(oac), XML) + .header("ETag", oac.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/origin-access-control/{Id}") + public Response deleteOriginAccessControl(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteOriginAccessControl(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/origin-access-control") + public Response listOriginAccessControls(@QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems) { + try { + List oacs = service.listOriginAccessControls(marker, maxItems); + boolean truncated = oacs.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("ListOriginAccessControlsResult", NS) + .start("OriginAccessControlList") + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", oacs.size()) + .start("Items"); + for (OriginAccessControl o : oacs) { + xml.raw(xmlOriginAccessControlSummary(o)); + } + xml.end("Items").end("OriginAccessControlList").end("ListOriginAccessControlsResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Origin Access Identity ──────────────────────────────────────────────── + + @POST + @Path("/origin-access-identity/cloudfront") + public Response createCloudFrontOriginAccessIdentity(String body) { + try { + CloudFrontOriginAccessIdentity oai = parseOai(body); + oai = service.createCloudFrontOriginAccessIdentity(oai); + String xml = xmlOaiResponse(oai); + return Response.created( + URI.create("/2020-05-31/origin-access-identity/cloudfront/" + oai.getId())) + .type(XML) + .header("ETag", oai.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/origin-access-identity/cloudfront/{Id}") + public Response getCloudFrontOriginAccessIdentity(@PathParam("Id") String id) { + try { + CloudFrontOriginAccessIdentity oai = service.getCloudFrontOriginAccessIdentity(id); + return Response.ok(xmlOaiResponse(oai), XML).header("ETag", oai.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/origin-access-identity/cloudfront/{Id}/config") + public Response getCloudFrontOriginAccessIdentityConfig(@PathParam("Id") String id) { + try { + CloudFrontOriginAccessIdentity oai = service.getCloudFrontOriginAccessIdentity(id); + String xml = new XmlBuilder() + .start("CloudFrontOriginAccessIdentityConfig", NS) + .elem("CallerReference", oai.getCallerReference()) + .elem("Comment", oai.getComment() != null ? oai.getComment() : "") + .end("CloudFrontOriginAccessIdentityConfig") + .build(); + return Response.ok(xml, XML).header("ETag", oai.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/origin-access-identity/cloudfront/{Id}/config") + public Response updateCloudFrontOriginAccessIdentity(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + CloudFrontOriginAccessIdentity oai = parseOai(body); + oai = service.updateCloudFrontOriginAccessIdentity(id, ifMatch, oai); + return Response.ok(xmlOaiResponse(oai), XML).header("ETag", oai.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/origin-access-identity/cloudfront/{Id}") + public Response deleteCloudFrontOriginAccessIdentity(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteCloudFrontOriginAccessIdentity(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/origin-access-identity/cloudfront") + public Response listCloudFrontOriginAccessIdentities( + @QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems) { + try { + List oais = + service.listCloudFrontOriginAccessIdentities(marker, maxItems); + boolean truncated = oais.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("ListCloudFrontOriginAccessIdentitiesResult", NS) + .start("CloudFrontOriginAccessIdentityList") + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", oais.size()) + .start("Items"); + for (CloudFrontOriginAccessIdentity o : oais) { + xml.start("CloudFrontOriginAccessIdentitySummary") + .elem("Id", o.getId()) + .elem("S3CanonicalUserId", o.getS3CanonicalUserId()) + .elem("Comment", o.getComment() != null ? o.getComment() : "") + .end("CloudFrontOriginAccessIdentitySummary"); + } + xml.end("Items").end("CloudFrontOriginAccessIdentityList") + .end("ListCloudFrontOriginAccessIdentitiesResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── CloudFront Functions ────────────────────────────────────────────────── + + @POST + @Path("/function") + public Response createFunction(String body) { + try { + CloudFrontFunction fn = parseFunction(body); + fn = service.createFunction(fn); + String xml = xmlFunctionResponse(fn); + return Response.created(URI.create("/2020-05-31/function/" + fn.getName())) + .type(XML) + .header("ETag", fn.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/function/{Name}") + public Response describeFunction(@PathParam("Name") String name, + @QueryParam("Stage") String stage) { + try { + CloudFrontFunction fn = service.describeFunction(name, stage); + return Response.ok(xmlFunctionResponse(fn), XML).header("ETag", fn.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/function/{Name}") + public Response updateFunction(@PathParam("Name") String name, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + CloudFrontFunction fn = parseFunction(body); + fn = service.updateFunction(name, ifMatch, fn); + return Response.ok(xmlFunctionResponse(fn), XML).header("ETag", fn.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @POST + @Path("/function/{Name}/publish") + public Response publishFunction(@PathParam("Name") String name, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + CloudFrontFunction fn = service.publishFunction(name, ifMatch); + return Response.ok(xmlFunctionResponse(fn), XML).header("ETag", fn.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/function/{Name}") + public Response deleteFunction(@PathParam("Name") String name, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteFunction(name, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/function") + public Response listFunctions(@QueryParam("Stage") String stage, + @QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems) { + try { + List fns = service.listFunctions(stage); + XmlBuilder xml = new XmlBuilder() + .start("ListFunctionsResult", NS) + .start("FunctionList") + .elem("MaxItems", maxItems) + .elem("Quantity", fns.size()) + .start("Items"); + for (CloudFrontFunction fn : fns) { + xml.start("FunctionSummary") + .elem("Name", fn.getName()) + .elem("Status", fn.getStatus()) + .start("FunctionConfig") + .elem("Comment", fn.getComment() != null ? fn.getComment() : "") + .elem("Runtime", fn.getRuntime() != null ? fn.getRuntime() : "cloudfront-js-2.0") + .end("FunctionConfig") + .start("FunctionMetadata") + .elem("FunctionARN", "arn:aws:cloudfront::" + service.getAccountId() + + ":function/" + fn.getName()) + .elem("Stage", fn.getStage()) + .elem("CreatedTime", fn.getCreatedTime() != null ? fn.getCreatedTime().toString() : "") + .elem("LastModifiedTime", + fn.getLastModifiedTime() != null ? fn.getLastModifiedTime().toString() : "") + .end("FunctionMetadata") + .end("FunctionSummary"); + } + xml.end("Items").end("FunctionList").end("ListFunctionsResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Tagging ─────────────────────────────────────────────────────────────── + + @GET + @Path("/tagging") + public Response listTagsForResource(@QueryParam("Resource") String resource) { + try { + Map tags = service.listTagsForResource(resource); + XmlBuilder xml = new XmlBuilder() + .start("ListTagsForResourceResult", NS) + .start("Tags") + .start("Items"); + for (Map.Entry entry : tags.entrySet()) { + xml.start("Tag") + .elem("Key", entry.getKey()) + .elem("Value", entry.getValue()) + .end("Tag"); + } + xml.end("Items").end("Tags").end("ListTagsForResourceResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @POST + @Path("/tagging") + public Response tagging(@QueryParam("Operation") String operation, + @QueryParam("Resource") String resource, + String body) { + try { + if ("Tag".equals(operation)) { + Map tags = parseTags(body); + service.tagResource(resource, tags); + } else if ("Untag".equals(operation)) { + List keys = XmlParser.extractAll(body, "Key"); + service.untagResource(resource, keys); + } else { + throw new AwsException("InvalidArgument", "Unknown tagging operation.", 400); + } + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Continuous Deployment Policies ─────────────────────────────────────── + + @POST + @Path("/continuous-deployment-policy") + public Response createContinuousDeploymentPolicy(String body) { + try { + ContinuousDeploymentPolicy policy = parseContinuousDeploymentPolicy(body); + policy = service.createContinuousDeploymentPolicy(policy); + String xml = xmlContinuousDeploymentPolicyResponse(policy); + return Response.created(URI.create("/2020-05-31/continuous-deployment-policy/" + policy.getId())) + .type(XML) + .header("ETag", policy.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/continuous-deployment-policy/{Id}") + public Response getContinuousDeploymentPolicy(@PathParam("Id") String id) { + try { + ContinuousDeploymentPolicy policy = service.getContinuousDeploymentPolicy(id); + return Response.ok(xmlContinuousDeploymentPolicyResponse(policy), XML) + .header("ETag", policy.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/continuous-deployment-policy/{Id}") + public Response updateContinuousDeploymentPolicy(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + ContinuousDeploymentPolicy policy = parseContinuousDeploymentPolicy(body); + policy = service.updateContinuousDeploymentPolicy(id, ifMatch, policy); + return Response.ok(xmlContinuousDeploymentPolicyResponse(policy), XML) + .header("ETag", policy.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/continuous-deployment-policy/{Id}") + public Response deleteContinuousDeploymentPolicy(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteContinuousDeploymentPolicy(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/continuous-deployment-policy") + public Response listContinuousDeploymentPolicies(@QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems) { + try { + List policies = + service.listContinuousDeploymentPolicies(marker, maxItems); + boolean truncated = policies.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("ListContinuousDeploymentPoliciesResult", NS) + .start("ContinuousDeploymentPolicyList") + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", policies.size()) + .start("Items"); + for (ContinuousDeploymentPolicy p : policies) { + xml.start("ContinuousDeploymentPolicySummary") + .elem("Type", "custom") + .raw(xmlContinuousDeploymentPolicyResponse(p)) + .end("ContinuousDeploymentPolicySummary"); + } + xml.end("Items").end("ContinuousDeploymentPolicyList") + .end("ListContinuousDeploymentPoliciesResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── CopyDistribution ────────────────────────────────────────────────────── + + @POST + @Path("/distribution/{PrimaryDistributionId}/copy") + public Response copyDistribution(@PathParam("PrimaryDistributionId") String primaryId, + String body) { + try { + String callerReference = XmlParser.extractFirst(body, "CallerReference", null); + Map tags = parseTags(body); + Distribution dist = service.copyDistribution(primaryId, callerReference, tags); + String xml = xmlDistribution(dist); + return Response.created(URI.create("/2020-05-31/distribution/" + dist.getId())) + .type(XML) + .header("ETag", dist.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Public Keys ─────────────────────────────────────────────────────────── + + @POST + @Path("/public-key") + public Response createPublicKey(String body) { + try { + PublicKey key = parsePublicKey(body); + key = service.createPublicKey(key); + String xml = xmlPublicKeyResponse(key); + return Response.created(URI.create("/2020-05-31/public-key/" + key.getId())) + .type(XML) + .header("ETag", key.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/public-key/{Id}") + public Response getPublicKey(@PathParam("Id") String id) { + try { + PublicKey key = service.getPublicKey(id); + return Response.ok(xmlPublicKeyResponse(key), XML).header("ETag", key.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/public-key/{Id}/config") + public Response getPublicKeyConfig(@PathParam("Id") String id) { + try { + PublicKey key = service.getPublicKey(id); + String xml = new XmlBuilder() + .start("PublicKeyConfig", NS) + .elem("CallerReference", key.getCallerReference() != null ? key.getCallerReference() : "") + .elem("Name", key.getName() != null ? key.getName() : "") + .elem("EncodedKey", key.getEncodedKey() != null ? key.getEncodedKey() : "") + .elem("Comment", key.getComment() != null ? key.getComment() : "") + .end("PublicKeyConfig") + .build(); + return Response.ok(xml, XML).header("ETag", key.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/public-key/{Id}/config") + public Response updatePublicKey(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + PublicKey key = parsePublicKey(body); + key = service.updatePublicKey(id, ifMatch, key); + return Response.ok(xmlPublicKeyResponse(key), XML).header("ETag", key.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/public-key/{Id}") + public Response deletePublicKey(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deletePublicKey(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/public-key") + public Response listPublicKeys(@QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems) { + try { + List keys = service.listPublicKeys(marker, maxItems); + boolean truncated = keys.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("ListPublicKeysResult", NS) + .start("PublicKeyList") + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", keys.size()) + .start("Items"); + for (PublicKey k : keys) { + xml.raw(xmlPublicKeySummary(k)); + } + xml.end("Items").end("PublicKeyList").end("ListPublicKeysResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Key Groups ──────────────────────────────────────────────────────────── + + @POST + @Path("/key-group") + public Response createKeyGroup(String body) { + try { + KeyGroup group = parseKeyGroup(body); + group = service.createKeyGroup(group); + String xml = xmlKeyGroupResponse(group); + return Response.created(URI.create("/2020-05-31/key-group/" + group.getId())) + .type(XML) + .header("ETag", group.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/key-group/{Id}") + public Response getKeyGroup(@PathParam("Id") String id) { + try { + KeyGroup group = service.getKeyGroup(id); + return Response.ok(xmlKeyGroupResponse(group), XML).header("ETag", group.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/key-group/{Id}/config") + public Response getKeyGroupConfig(@PathParam("Id") String id) { + try { + KeyGroup group = service.getKeyGroup(id); + List items = group.getItems() != null ? group.getItems() : List.of(); + String xml = new XmlBuilder() + .start("KeyGroupConfig", NS) + .elem("Name", group.getName() != null ? group.getName() : "") + .elem("Comment", group.getComment() != null ? group.getComment() : "") + .raw(xmlQuantityItems("Items", "PublicKey", items.size(), + items.stream().map(k -> "" + XmlBuilder.escape(k) + "").toList())) + .end("KeyGroupConfig") + .build(); + return Response.ok(xml, XML).header("ETag", group.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/key-group/{Id}") + public Response updateKeyGroup(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + KeyGroup group = parseKeyGroup(body); + group = service.updateKeyGroup(id, ifMatch, group); + return Response.ok(xmlKeyGroupResponse(group), XML).header("ETag", group.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/key-group/{Id}") + public Response deleteKeyGroup(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteKeyGroup(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/key-group") + public Response listKeyGroups(@QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems) { + try { + List groups = service.listKeyGroups(marker, maxItems); + boolean truncated = groups.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("ListKeyGroupsResult", NS) + .start("KeyGroupList") + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", groups.size()) + .start("Items"); + for (KeyGroup g : groups) { + xml.start("KeyGroupSummary").raw(xmlKeyGroupResponse(g)).end("KeyGroupSummary"); + } + xml.end("Items").end("KeyGroupList").end("ListKeyGroupsResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Realtime Log Configs ────────────────────────────────────────────────── + + @POST + @Path("/realtime-log-config") + public Response createRealtimeLogConfig(String body) { + try { + RealtimeLogConfig cfg = parseRealtimeLogConfig(body); + cfg = service.createRealtimeLogConfig(cfg); + String xml = new XmlBuilder() + .start("CreateRealtimeLogConfigResult", NS) + .raw(xmlRealtimeLogConfigBody(cfg)) + .end("CreateRealtimeLogConfigResult") + .build(); + return Response.created(URI.create("/2020-05-31/realtime-log-config")) + .type(XML) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @POST + @Path("/get-realtime-log-config") + public Response getRealtimeLogConfig(String body) { + try { + String name = XmlParser.extractFirst(body, "Name", null); + String arn = XmlParser.extractFirst(body, "ARN", null); + RealtimeLogConfig cfg = service.getRealtimeLogConfig(name != null ? name : arn); + String xml = new XmlBuilder() + .start("GetRealtimeLogConfigResult", NS) + .raw(xmlRealtimeLogConfigBody(cfg)) + .end("GetRealtimeLogConfigResult") + .build(); + return Response.ok(xml, XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/realtime-log-config") + public Response updateRealtimeLogConfig(String body) { + try { + RealtimeLogConfig cfg = parseRealtimeLogConfig(body); + cfg = service.updateRealtimeLogConfig(cfg); + String xml = new XmlBuilder() + .start("UpdateRealtimeLogConfigResult", NS) + .raw(xmlRealtimeLogConfigBody(cfg)) + .end("UpdateRealtimeLogConfigResult") + .build(); + return Response.ok(xml, XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @POST + @Path("/delete-realtime-log-config") + public Response deleteRealtimeLogConfig(String body) { + try { + String name = XmlParser.extractFirst(body, "Name", null); + String arn = XmlParser.extractFirst(body, "ARN", null); + service.deleteRealtimeLogConfig(name != null ? name : arn); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/realtime-log-config") + public Response listRealtimeLogConfigs(@QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems) { + try { + List configs = service.listRealtimeLogConfigs(marker, maxItems); + boolean truncated = configs.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("ListRealtimeLogConfigsResult", NS) + .start("RealtimeLogConfigs") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", configs.size()) + .start("Items"); + for (RealtimeLogConfig c : configs) { + xml.raw(xmlRealtimeLogConfigBody(c)); + } + xml.end("Items").end("RealtimeLogConfigs").end("ListRealtimeLogConfigsResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Streaming Distributions ─────────────────────────────────────────────── + + @POST + @Path("/streaming-distribution") + public Response createStreamingDistribution(String body) { + try { + StreamingDistribution sd = parseStreamingDistribution(body); + sd = service.createStreamingDistribution(sd); + String xml = xmlStreamingDistributionResponse(sd); + return Response.created(URI.create("/2020-05-31/streaming-distribution/" + sd.getId())) + .type(XML) + .header("ETag", sd.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/streaming-distribution/{Id}") + public Response getStreamingDistribution(@PathParam("Id") String id) { + try { + StreamingDistribution sd = service.getStreamingDistribution(id); + return Response.ok(xmlStreamingDistributionResponse(sd), XML) + .header("ETag", sd.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/streaming-distribution/{Id}/config") + public Response getStreamingDistributionConfig(@PathParam("Id") String id) { + try { + StreamingDistribution sd = service.getStreamingDistribution(id); + String xml = xmlStreamingDistributionConfigBody(sd); + return Response.ok(xml, XML).header("ETag", sd.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/streaming-distribution/{Id}/config") + public Response updateStreamingDistribution(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + StreamingDistribution sd = parseStreamingDistribution(body); + sd = service.updateStreamingDistribution(id, ifMatch, sd); + return Response.ok(xmlStreamingDistributionResponse(sd), XML) + .header("ETag", sd.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/streaming-distribution/{Id}") + public Response deleteStreamingDistribution(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteStreamingDistribution(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Field-Level Encryption Configs ──────────────────────────────────────── + + @POST + @Path("/field-level-encryption") + public Response createFieldLevelEncryptionConfig(String body) { + try { + FieldLevelEncryptionConfig cfg = parseFieldLevelEncryptionConfig(body); + cfg = service.createFieldLevelEncryptionConfig(cfg); + String xml = xmlFieldLevelEncryptionConfigResponse(cfg); + return Response.created(URI.create("/2020-05-31/field-level-encryption/" + cfg.getId())) + .type(XML) + .header("ETag", cfg.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/field-level-encryption/{Id}/config") + public Response getFieldLevelEncryptionConfig(@PathParam("Id") String id) { + try { + FieldLevelEncryptionConfig cfg = service.getFieldLevelEncryptionConfig(id); + return Response.ok(xmlFieldLevelEncryptionConfigResponse(cfg), XML) + .header("ETag", cfg.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/field-level-encryption/{Id}/config") + public Response updateFieldLevelEncryptionConfig(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + FieldLevelEncryptionConfig cfg = parseFieldLevelEncryptionConfig(body); + cfg = service.updateFieldLevelEncryptionConfig(id, ifMatch, cfg); + return Response.ok(xmlFieldLevelEncryptionConfigResponse(cfg), XML) + .header("ETag", cfg.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/field-level-encryption/{Id}") + public Response deleteFieldLevelEncryptionConfig(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteFieldLevelEncryptionConfig(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/field-level-encryption") + public Response listFieldLevelEncryptionConfigs(@QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems) { + try { + List configs = + service.listFieldLevelEncryptionConfigs(marker, maxItems); + boolean truncated = configs.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("ListFieldLevelEncryptionConfigsResult", NS) + .start("FieldLevelEncryptionList") + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", configs.size()) + .start("Items"); + for (FieldLevelEncryptionConfig c : configs) { + xml.raw(xmlFieldLevelEncryptionConfigResponse(c)); + } + xml.end("Items").end("FieldLevelEncryptionList").end("ListFieldLevelEncryptionConfigsResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Field-Level Encryption Profiles ────────────────────────────────────── + + @POST + @Path("/field-level-encryption-profile") + public Response createFieldLevelEncryptionProfile(String body) { + try { + FieldLevelEncryptionProfile profile = parseFieldLevelEncryptionProfile(body); + profile = service.createFieldLevelEncryptionProfile(profile); + String xml = xmlFieldLevelEncryptionProfileResponse(profile); + return Response.created( + URI.create("/2020-05-31/field-level-encryption-profile/" + profile.getId())) + .type(XML) + .header("ETag", profile.getEtag()) + .entity(xml) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/field-level-encryption-profile/{Id}") + public Response getFieldLevelEncryptionProfile(@PathParam("Id") String id) { + try { + FieldLevelEncryptionProfile profile = service.getFieldLevelEncryptionProfile(id); + return Response.ok(xmlFieldLevelEncryptionProfileResponse(profile), XML) + .header("ETag", profile.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/field-level-encryption-profile/{Id}/config") + public Response updateFieldLevelEncryptionProfile(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + FieldLevelEncryptionProfile profile = parseFieldLevelEncryptionProfile(body); + profile = service.updateFieldLevelEncryptionProfile(id, ifMatch, profile); + return Response.ok(xmlFieldLevelEncryptionProfileResponse(profile), XML) + .header("ETag", profile.getEtag()).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/field-level-encryption-profile/{Id}") + public Response deleteFieldLevelEncryptionProfile(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + if (ifMatch == null || ifMatch.isEmpty()) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + service.deleteFieldLevelEncryptionProfile(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/field-level-encryption-profile") + public Response listFieldLevelEncryptionProfiles(@QueryParam("Marker") String marker, + @QueryParam("MaxItems") @DefaultValue("100") int maxItems) { + try { + List profiles = + service.listFieldLevelEncryptionProfiles(marker, maxItems); + boolean truncated = profiles.size() == maxItems; + + XmlBuilder xml = new XmlBuilder() + .start("ListFieldLevelEncryptionProfilesResult", NS) + .start("FieldLevelEncryptionProfileList") + .elem("Marker", marker != null ? marker : "") + .elem("MaxItems", maxItems) + .elem("IsTruncated", truncated) + .elem("Quantity", profiles.size()) + .start("Items"); + for (FieldLevelEncryptionProfile p : profiles) { + xml.raw(xmlFieldLevelEncryptionProfileResponse(p)); + } + xml.end("Items").end("FieldLevelEncryptionProfileList") + .end("ListFieldLevelEncryptionProfilesResult"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── Monitoring Subscriptions ────────────────────────────────────────────── + + @POST + @Path("/distributions/{DistributionId}/monitoring-subscription") + public Response createMonitoringSubscription(@PathParam("DistributionId") String distributionId, + String body) { + try { + MonitoringSubscription sub = parseMonitoringSubscription(body); + sub = service.createMonitoringSubscription(distributionId, sub); + String xml = xmlMonitoringSubscriptionResponse(sub); + return Response.ok(xml, XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/distributions/{DistributionId}/monitoring-subscription") + public Response getMonitoringSubscription(@PathParam("DistributionId") String distributionId) { + try { + MonitoringSubscription sub = service.getMonitoringSubscription(distributionId); + return Response.ok(xmlMonitoringSubscriptionResponse(sub), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/distributions/{DistributionId}/monitoring-subscription") + public Response deleteMonitoringSubscription(@PathParam("DistributionId") String distributionId) { + try { + service.deleteMonitoringSubscription(distributionId); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + // ── XML builders ────────────────────────────────────────────────────────── + + private String xmlDistribution(Distribution dist) { + return new XmlBuilder() + .start("Distribution", NS) + .elem("Id", dist.getId()) + .elem("ARN", dist.getArn()) + .elem("Status", dist.getStatus()) + .elem("DomainName", dist.getDomainName()) + .elem("LastModifiedTime", + dist.getLastModifiedTime() != null ? dist.getLastModifiedTime().toString() : "") + .start("DistributionConfig") + .raw(xmlDistributionConfigBody(dist.getConfig())) + .end("DistributionConfig") + .end("Distribution") + .build(); + } + + private String xmlDistributionConfigBody(DistributionConfig cfg) { + if (cfg == null) { + return ""; + } + XmlBuilder xml = new XmlBuilder() + .elem("CallerReference", cfg.getCallerReference() != null ? cfg.getCallerReference() : "") + .elem("Enabled", cfg.isEnabled()) + .elem("Comment", cfg.getComment() != null ? cfg.getComment() : "") + .elem("DefaultRootObject", cfg.getDefaultRootObject() != null ? cfg.getDefaultRootObject() : "") + .elem("HttpVersion", cfg.getHttpVersion() != null ? cfg.getHttpVersion() : "http2") + .elem("PriceClass", cfg.getPriceClass() != null ? cfg.getPriceClass() : "PriceClass_All") + .elem("IsIPV6Enabled", cfg.isIPV6Enabled()) + .elem("WebAclId", cfg.getWebAclId() != null ? cfg.getWebAclId() : ""); + + List origins = cfg.getOrigins(); + xml.raw(xmlQuantityItems("Origins", "Origin", origins != null ? origins.size() : 0, + origins != null ? origins.stream().map(this::xmlOrigin).toList() : List.of())); + + if (cfg.getDefaultCacheBehavior() != null) { + xml.raw(xmlDefaultCacheBehavior(cfg.getDefaultCacheBehavior())); + } + + List cacheBehaviors = cfg.getCacheBehaviors(); + int cbCount = cacheBehaviors != null ? cacheBehaviors.size() : 0; + xml.start("CacheBehaviors").elem("Quantity", cbCount); + if (cbCount > 0) { + xml.start("Items"); + for (CacheBehavior cb : cacheBehaviors) { + xml.raw(xmlCacheBehavior(cb)); + } + xml.end("Items"); + } + xml.end("CacheBehaviors"); + + xml.start("CustomErrorResponses").elem("Quantity", 0).end("CustomErrorResponses"); + + List aliases = cfg.getAliases(); + int aliasCount = aliases != null ? aliases.size() : 0; + xml.start("Aliases").elem("Quantity", aliasCount); + if (aliasCount > 0) { + xml.start("Items"); + for (String a : aliases) { + xml.elem("CNAME", a); + } + xml.end("Items"); + } + xml.end("Aliases"); + + xml.raw(xmlViewerCertificate(cfg.getViewerCertificate())); + + return xml.build(); + } + + private String xmlOrigin(Origin o) { + XmlBuilder xml = new XmlBuilder() + .start("Origin") + .elem("Id", o.getId()) + .elem("DomainName", o.getDomainName()) + .elem("OriginPath", o.getOriginPath() != null ? o.getOriginPath() : "") + .elem("ConnectionAttempts", o.getConnectionAttempts()) + .elem("ConnectionTimeout", o.getConnectionTimeout()); + + if (o.getOriginAccessControlId() != null && !o.getOriginAccessControlId().isEmpty()) { + xml.elem("OriginAccessControlId", o.getOriginAccessControlId()); + } + + Map s3Config = o.getS3OriginConfig(); + if (s3Config != null) { + xml.start("S3OriginConfig") + .elem("OriginAccessIdentity", s3Config.getOrDefault("OriginAccessIdentity", "")) + .end("S3OriginConfig"); + } else if (o.getCustomOriginConfig() == null) { + xml.start("S3OriginConfig").elem("OriginAccessIdentity", "").end("S3OriginConfig"); + } + + if (o.getCustomOriginConfig() != null) { + Map coc = o.getCustomOriginConfig(); + xml.start("CustomOriginConfig") + .elem("HTTPPort", coc.getOrDefault("HTTPPort", "80").toString()) + .elem("HTTPSPort", coc.getOrDefault("HTTPSPort", "443").toString()) + .elem("OriginProtocolPolicy", + coc.getOrDefault("OriginProtocolPolicy", "https-only").toString()) + .end("CustomOriginConfig"); + } + + xml.end("Origin"); + return xml.build(); + } + + private String xmlDefaultCacheBehavior(DefaultCacheBehavior dcb) { + XmlBuilder xml = new XmlBuilder() + .start("DefaultCacheBehavior") + .elem("TargetOriginId", dcb.getTargetOriginId()) + .elem("ViewerProtocolPolicy", + dcb.getViewerProtocolPolicy() != null ? dcb.getViewerProtocolPolicy() : "redirect-to-https") + .elem("CachePolicyId", dcb.getCachePolicyId()) + .elem("OriginRequestPolicyId", dcb.getOriginRequestPolicyId()) + .elem("ResponseHeadersPolicyId", dcb.getResponseHeadersPolicyId()) + .elem("Compress", dcb.isCompress()); + + List allowed = dcb.getAllowedMethods(); + if (allowed == null || allowed.isEmpty()) { + allowed = List.of("GET", "HEAD"); + } + xml.raw(xmlQuantityItems("AllowedMethods", "Method", allowed.size(), + allowed.stream().map(m -> "" + XmlBuilder.escape(m) + "").toList())); + + xml.start("FunctionAssociations").elem("Quantity", 0).end("FunctionAssociations"); + xml.start("LambdaFunctionAssociations").elem("Quantity", 0).end("LambdaFunctionAssociations"); + + xml.end("DefaultCacheBehavior"); + return xml.build(); + } + + private String xmlCacheBehavior(CacheBehavior cb) { + XmlBuilder xml = new XmlBuilder() + .start("CacheBehavior") + .elem("PathPattern", cb.getPathPattern()) + .elem("TargetOriginId", cb.getTargetOriginId()) + .elem("ViewerProtocolPolicy", + cb.getViewerProtocolPolicy() != null ? cb.getViewerProtocolPolicy() : "redirect-to-https") + .elem("CachePolicyId", cb.getCachePolicyId()) + .elem("OriginRequestPolicyId", cb.getOriginRequestPolicyId()) + .elem("ResponseHeadersPolicyId", cb.getResponseHeadersPolicyId()) + .elem("Compress", cb.isCompress()); + + List allowed = cb.getAllowedMethods(); + if (allowed == null || allowed.isEmpty()) { + allowed = List.of("GET", "HEAD"); + } + xml.raw(xmlQuantityItems("AllowedMethods", "Method", allowed.size(), + allowed.stream().map(m -> "" + XmlBuilder.escape(m) + "").toList())); + + xml.start("FunctionAssociations").elem("Quantity", 0).end("FunctionAssociations"); + xml.start("LambdaFunctionAssociations").elem("Quantity", 0).end("LambdaFunctionAssociations"); + + xml.end("CacheBehavior"); + return xml.build(); + } + + private String xmlViewerCertificate(Map vc) { + XmlBuilder xml = new XmlBuilder().start("ViewerCertificate"); + if (vc != null && !vc.isEmpty()) { + for (Map.Entry entry : vc.entrySet()) { + xml.elem(entry.getKey(), entry.getValue()); + } + } else { + xml.elem("CloudFrontDefaultCertificate", "true") + .elem("MinimumProtocolVersion", "TLSv1.2_2021"); + } + xml.end("ViewerCertificate"); + return xml.build(); + } + + private String xmlDistributionSummary(Distribution d) { + XmlBuilder xml = new XmlBuilder() + .start("DistributionSummary") + .elem("Id", d.getId()) + .elem("ARN", d.getArn()) + .elem("Status", d.getStatus()) + .elem("DomainName", d.getDomainName()) + .elem("LastModifiedTime", + d.getLastModifiedTime() != null ? d.getLastModifiedTime().toString() : "") + .elem("Comment", d.getConfig() != null && d.getConfig().getComment() != null + ? d.getConfig().getComment() : "") + .elem("Enabled", d.getConfig() != null && d.getConfig().isEnabled()) + .elem("HttpVersion", d.getConfig() != null && d.getConfig().getHttpVersion() != null + ? d.getConfig().getHttpVersion() : "http2") + .elem("PriceClass", d.getConfig() != null && d.getConfig().getPriceClass() != null + ? d.getConfig().getPriceClass() : "PriceClass_All") + .elem("IsIPV6Enabled", d.getConfig() != null && d.getConfig().isIPV6Enabled()) + .elem("WebAclId", ""); + + DistributionConfig cfg = d.getConfig(); + List origins = cfg != null ? cfg.getOrigins() : null; + xml.raw(xmlQuantityItems("Origins", "Origin", + origins != null ? origins.size() : 0, + origins != null ? origins.stream().map(o -> + "" + XmlBuilder.escape(o.getId()) + "" + + XmlBuilder.escape(o.getDomainName()) + "").toList() + : List.of())); + + List aliases = cfg != null ? cfg.getAliases() : null; + int aliasCount = aliases != null ? aliases.size() : 0; + xml.start("Aliases").elem("Quantity", aliasCount); + if (aliasCount > 0) { + xml.start("Items"); + for (String a : aliases) { + xml.elem("CNAME", a); + } + xml.end("Items"); + } + xml.end("Aliases"); + + xml.raw(xmlViewerCertificate(cfg != null ? cfg.getViewerCertificate() : null)); + + xml.end("DistributionSummary"); + return xml.build(); + } + + private String xmlInvalidationBody(Invalidation inv) { + XmlBuilder xml = new XmlBuilder() + .elem("Id", inv.getId()) + .elem("Status", inv.getStatus()) + .elem("CreateTime", inv.getCreateTime() != null ? inv.getCreateTime().toString() : "") + .start("InvalidationBatch"); + List paths = inv.getPaths(); + int pathCount = paths != null ? paths.size() : 0; + xml.start("Paths").elem("Quantity", pathCount); + if (pathCount > 0) { + xml.start("Items"); + for (String p : paths) { + xml.elem("Path", p); + } + xml.end("Items"); + } + xml.end("Paths") + .elem("CallerReference", inv.getCallerReference() != null ? inv.getCallerReference() : "") + .end("InvalidationBatch"); + return xml.build(); + } + + private String xmlCachePolicyResponse(CachePolicy policy) { + return new XmlBuilder() + .start("CachePolicy") + .elem("Id", policy.getId()) + .elem("LastModifiedTime", + policy.getLastModifiedTime() != null ? policy.getLastModifiedTime().toString() : "") + .start("CachePolicyConfig") + .elem("Name", policy.getName()) + .elem("Comment", policy.getComment() != null ? policy.getComment() : "") + .end("CachePolicyConfig") + .end("CachePolicy") + .build(); + } + + private String xmlOriginRequestPolicyResponse(OriginRequestPolicy policy) { + return new XmlBuilder() + .start("OriginRequestPolicy") + .elem("Id", policy.getId()) + .elem("LastModifiedTime", + policy.getLastModifiedTime() != null ? policy.getLastModifiedTime().toString() : "") + .start("OriginRequestPolicyConfig") + .elem("Name", policy.getName()) + .elem("Comment", policy.getComment() != null ? policy.getComment() : "") + .end("OriginRequestPolicyConfig") + .end("OriginRequestPolicy") + .build(); + } + + private String xmlResponseHeadersPolicyResponse(ResponseHeadersPolicy policy) { + return new XmlBuilder() + .start("ResponseHeadersPolicy") + .elem("Id", policy.getId()) + .elem("LastModifiedTime", + policy.getLastModifiedTime() != null ? policy.getLastModifiedTime().toString() : "") + .start("ResponseHeadersPolicyConfig") + .elem("Name", policy.getName()) + .elem("Comment", policy.getComment() != null ? policy.getComment() : "") + .end("ResponseHeadersPolicyConfig") + .end("ResponseHeadersPolicy") + .build(); + } + + private String xmlOriginAccessControlResponse(OriginAccessControl oac) { + return new XmlBuilder() + .start("OriginAccessControl") + .elem("Id", oac.getId()) + .start("OriginAccessControlConfig") + .elem("Name", oac.getName()) + .elem("Description", oac.getDescription() != null ? oac.getDescription() : "") + .elem("SigningProtocol", oac.getSigningProtocol()) + .elem("SigningBehavior", oac.getSigningBehavior()) + .elem("OriginAccessControlOriginType", oac.getOriginAccessControlOriginType()) + .end("OriginAccessControlConfig") + .end("OriginAccessControl") + .build(); + } + + private String xmlOriginAccessControlSummary(OriginAccessControl oac) { + return new XmlBuilder() + .start("OriginAccessControlSummary") + .elem("Id", oac.getId()) + .elem("Name", oac.getName()) + .elem("Description", oac.getDescription() != null ? oac.getDescription() : "") + .elem("SigningProtocol", oac.getSigningProtocol()) + .elem("SigningBehavior", oac.getSigningBehavior()) + .elem("OriginAccessControlOriginType", oac.getOriginAccessControlOriginType()) + .elem("LastModifiedTime", + oac.getLastModifiedTime() != null ? oac.getLastModifiedTime().toString() : "") + .end("OriginAccessControlSummary") + .build(); + } + + private String xmlOaiResponse(CloudFrontOriginAccessIdentity oai) { + return new XmlBuilder() + .start("CloudFrontOriginAccessIdentity") + .elem("Id", oai.getId()) + .elem("S3CanonicalUserId", oai.getS3CanonicalUserId()) + .start("CloudFrontOriginAccessIdentityConfig") + .elem("CallerReference", oai.getCallerReference()) + .elem("Comment", oai.getComment() != null ? oai.getComment() : "") + .end("CloudFrontOriginAccessIdentityConfig") + .end("CloudFrontOriginAccessIdentity") + .build(); + } + + private String xmlFunctionResponse(CloudFrontFunction fn) { + return new XmlBuilder() + .start("FunctionSummary") + .elem("Name", fn.getName()) + .elem("Status", fn.getStatus()) + .start("FunctionConfig") + .elem("Comment", fn.getComment() != null ? fn.getComment() : "") + .elem("Runtime", fn.getRuntime() != null ? fn.getRuntime() : "cloudfront-js-2.0") + .end("FunctionConfig") + .start("FunctionMetadata") + .elem("FunctionARN", + "arn:aws:cloudfront::" + service.getAccountId() + ":function/" + fn.getName()) + .elem("Stage", fn.getStage()) + .elem("CreatedTime", fn.getCreatedTime() != null ? fn.getCreatedTime().toString() : "") + .elem("LastModifiedTime", + fn.getLastModifiedTime() != null ? fn.getLastModifiedTime().toString() : "") + .end("FunctionMetadata") + .end("FunctionSummary") + .build(); + } + + private String xmlQuantityItems(String wrapper, String itemTag, int count, List items) { + XmlBuilder xml = new XmlBuilder().start(wrapper).elem("Quantity", count); + if (count > 0 && items != null && !items.isEmpty()) { + xml.start("Items"); + for (String item : items) { + xml.raw(item); + } + xml.end("Items"); + } + xml.end(wrapper); + return xml.build(); + } + + private Response xmlErrorResponse(AwsException e) { + String xml = new XmlBuilder() + .start("ErrorResponse", NS) + .start("Error") + .elem("Type", "Client") + .elem("Code", e.getErrorCode()) + .elem("Message", e.getMessage()) + .end("Error") + .elem("RequestId", "00000000-0000-0000-0000-000000000000") + .end("ErrorResponse") + .build(); + return Response.status(e.getHttpStatus()).type(XML).entity(xml).build(); + } + + // ── Request parsers ─────────────────────────────────────────────────────── + + private DistributionConfig parseDistributionConfig(String body) { + DistributionConfig cfg = new DistributionConfig(); + cfg.setCallerReference(XmlParser.extractFirst(body, "CallerReference", null)); + cfg.setEnabled("true".equalsIgnoreCase(XmlParser.extractFirst(body, "Enabled", "true"))); + cfg.setComment(XmlParser.extractFirst(body, "Comment", "")); + cfg.setDefaultRootObject(XmlParser.extractFirst(body, "DefaultRootObject", "")); + cfg.setHttpVersion(XmlParser.extractFirst(body, "HttpVersion", "http2")); + cfg.setPriceClass(XmlParser.extractFirst(body, "PriceClass", "PriceClass_All")); + cfg.setIPV6Enabled("true".equalsIgnoreCase(XmlParser.extractFirst(body, "IsIPV6Enabled", "true"))); + cfg.setWebAclId(XmlParser.extractFirst(body, "WebAclId", null)); + cfg.setContinuousDeploymentPolicyId(XmlParser.extractFirst(body, "ContinuousDeploymentPolicyId", null)); + cfg.setStaging("true".equalsIgnoreCase(XmlParser.extractFirst(body, "Staging", "false"))); + + cfg.setOrigins(parseOrigins(body)); + cfg.setDefaultCacheBehavior(parseDefaultCacheBehavior(body)); + cfg.setCacheBehaviors(parseCacheBehaviors(body)); + cfg.setAliases(parseAliases(body)); + cfg.setViewerCertificate(parseViewerCertificate(body)); + + return cfg; + } + + private List parseOrigins(String body) { + List result = new ArrayList<>(); + if (body == null || body.isEmpty()) { + return result; + } + try { + XMLStreamReader r = XML_FACTORY.createXMLStreamReader(new StringReader(body)); + boolean inOrigins = false; + boolean inOrigin = false; + boolean inS3OriginConfig = false; + boolean inCustomOriginConfig = false; + Origin current = null; + Map s3Config = null; + Map customConfig = null; + + while (r.hasNext()) { + int event = r.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + String local = r.getLocalName(); + switch (local) { + case "Origins" -> inOrigins = true; + case "Origin" -> { + if (inOrigins) { + inOrigin = true; + current = new Origin(); + } + } + case "S3OriginConfig" -> { + if (inOrigin) { + inS3OriginConfig = true; + s3Config = new LinkedHashMap<>(); + } + } + case "CustomOriginConfig" -> { + if (inOrigin) { + inCustomOriginConfig = true; + customConfig = new LinkedHashMap<>(); + } + } + case "Id" -> { + if (inOrigin && !inS3OriginConfig && !inCustomOriginConfig && current != null) { + current.setId(r.getElementText()); + } + } + case "DomainName" -> { + if (inOrigin && !inS3OriginConfig && !inCustomOriginConfig && current != null) { + current.setDomainName(r.getElementText()); + } + } + case "OriginPath" -> { + if (inOrigin && !inS3OriginConfig && !inCustomOriginConfig && current != null) { + current.setOriginPath(r.getElementText()); + } + } + case "OriginAccessControlId" -> { + if (inOrigin && !inS3OriginConfig && !inCustomOriginConfig && current != null) { + current.setOriginAccessControlId(r.getElementText()); + } + } + case "ConnectionAttempts" -> { + if (inOrigin && !inS3OriginConfig && !inCustomOriginConfig && current != null) { + try { + current.setConnectionAttempts(Integer.parseInt(r.getElementText())); + } catch (NumberFormatException ignored) { + } + } + } + case "ConnectionTimeout" -> { + if (inOrigin && !inS3OriginConfig && !inCustomOriginConfig && current != null) { + try { + current.setConnectionTimeout(Integer.parseInt(r.getElementText())); + } catch (NumberFormatException ignored) { + } + } + } + case "OriginAccessIdentity" -> { + if (inS3OriginConfig && s3Config != null) { + s3Config.put("OriginAccessIdentity", r.getElementText()); + } + } + case "HTTPPort" -> { + if (inCustomOriginConfig && customConfig != null) { + customConfig.put("HTTPPort", r.getElementText()); + } + } + case "HTTPSPort" -> { + if (inCustomOriginConfig && customConfig != null) { + customConfig.put("HTTPSPort", r.getElementText()); + } + } + case "OriginProtocolPolicy" -> { + if (inCustomOriginConfig && customConfig != null) { + customConfig.put("OriginProtocolPolicy", r.getElementText()); + } + } + default -> { + } + } + } else if (event == XMLStreamConstants.END_ELEMENT) { + switch (r.getLocalName()) { + case "S3OriginConfig" -> { + if (inS3OriginConfig && current != null) { + current.setS3OriginConfig(s3Config); + } + inS3OriginConfig = false; + s3Config = null; + } + case "CustomOriginConfig" -> { + if (inCustomOriginConfig && current != null) { + current.setCustomOriginConfig(customConfig); + } + inCustomOriginConfig = false; + customConfig = null; + } + case "Origin" -> { + if (inOrigin && current != null) { + result.add(current); + } + inOrigin = false; + current = null; + } + case "Origins" -> inOrigins = false; + default -> { + } + } + } + } + r.close(); + } catch (Exception ignored) { + } + return result; + } + + private DefaultCacheBehavior parseDefaultCacheBehavior(String body) { + DefaultCacheBehavior dcb = new DefaultCacheBehavior(); + if (body == null || body.isEmpty()) { + return dcb; + } + try { + XMLStreamReader r = XML_FACTORY.createXMLStreamReader(new StringReader(body)); + boolean inDcb = false; + boolean inAllowedMethods = false; + List allowedMethods = new ArrayList<>(); + + while (r.hasNext()) { + int event = r.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + String local = r.getLocalName(); + switch (local) { + case "DefaultCacheBehavior" -> inDcb = true; + case "AllowedMethods" -> { + if (inDcb) inAllowedMethods = true; + } + case "TargetOriginId" -> { + if (inDcb) dcb.setTargetOriginId(r.getElementText()); + } + case "ViewerProtocolPolicy" -> { + if (inDcb) dcb.setViewerProtocolPolicy(r.getElementText()); + } + case "CachePolicyId" -> { + if (inDcb) dcb.setCachePolicyId(r.getElementText()); + } + case "OriginRequestPolicyId" -> { + if (inDcb) dcb.setOriginRequestPolicyId(r.getElementText()); + } + case "ResponseHeadersPolicyId" -> { + if (inDcb) dcb.setResponseHeadersPolicyId(r.getElementText()); + } + case "FieldLevelEncryptionId" -> { + if (inDcb) dcb.setFieldLevelEncryptionId(r.getElementText()); + } + case "RealtimeLogConfigArn" -> { + if (inDcb) dcb.setRealtimeLogConfigArn(r.getElementText()); + } + case "Compress" -> { + if (inDcb) dcb.setCompress("true".equalsIgnoreCase(r.getElementText())); + } + case "Method" -> { + if (inAllowedMethods) allowedMethods.add(r.getElementText()); + } + default -> { + } + } + } else if (event == XMLStreamConstants.END_ELEMENT) { + switch (r.getLocalName()) { + case "AllowedMethods" -> inAllowedMethods = false; + case "DefaultCacheBehavior" -> inDcb = false; + default -> { + } + } + } + } + r.close(); + if (!allowedMethods.isEmpty()) { + dcb.setAllowedMethods(allowedMethods); + } + } catch (Exception ignored) { + } + return dcb; + } + + private List parseCacheBehaviors(String body) { + List result = new ArrayList<>(); + if (body == null || body.isEmpty()) { + return result; + } + try { + XMLStreamReader r = XML_FACTORY.createXMLStreamReader(new StringReader(body)); + boolean inCacheBehaviors = false; + boolean inCacheBehavior = false; + boolean inAllowedMethods = false; + CacheBehavior current = null; + List allowedMethods = new ArrayList<>(); + + while (r.hasNext()) { + int event = r.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + String local = r.getLocalName(); + switch (local) { + case "CacheBehaviors" -> inCacheBehaviors = true; + case "CacheBehavior" -> { + if (inCacheBehaviors) { + inCacheBehavior = true; + current = new CacheBehavior(); + allowedMethods = new ArrayList<>(); + } + } + case "AllowedMethods" -> { + if (inCacheBehavior) inAllowedMethods = true; + } + case "PathPattern" -> { + if (inCacheBehavior && current != null) current.setPathPattern(r.getElementText()); + } + case "TargetOriginId" -> { + if (inCacheBehavior && current != null) current.setTargetOriginId(r.getElementText()); + } + case "ViewerProtocolPolicy" -> { + if (inCacheBehavior && current != null) current.setViewerProtocolPolicy(r.getElementText()); + } + case "CachePolicyId" -> { + if (inCacheBehavior && current != null) current.setCachePolicyId(r.getElementText()); + } + case "OriginRequestPolicyId" -> { + if (inCacheBehavior && current != null) + current.setOriginRequestPolicyId(r.getElementText()); + } + case "ResponseHeadersPolicyId" -> { + if (inCacheBehavior && current != null) + current.setResponseHeadersPolicyId(r.getElementText()); + } + case "Compress" -> { + if (inCacheBehavior && current != null) { + current.setCompress("true".equalsIgnoreCase(r.getElementText())); + } + } + case "Method" -> { + if (inAllowedMethods) allowedMethods.add(r.getElementText()); + } + default -> { + } + } + } else if (event == XMLStreamConstants.END_ELEMENT) { + switch (r.getLocalName()) { + case "AllowedMethods" -> inAllowedMethods = false; + case "CacheBehavior" -> { + if (inCacheBehavior && current != null) { + if (!allowedMethods.isEmpty()) { + current.setAllowedMethods(allowedMethods); + } + result.add(current); + } + inCacheBehavior = false; + current = null; + } + case "CacheBehaviors" -> inCacheBehaviors = false; + default -> { + } + } + } + } + r.close(); + } catch (Exception ignored) { + } + return result; + } + + private List parseAliases(String body) { + List result = new ArrayList<>(); + if (body == null || body.isEmpty()) { + return result; + } + try { + XMLStreamReader r = XML_FACTORY.createXMLStreamReader(new StringReader(body)); + boolean inAliases = false; + while (r.hasNext()) { + int event = r.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + String local = r.getLocalName(); + if ("Aliases".equals(local)) { + inAliases = true; + } else if (inAliases && "CNAME".equals(local)) { + result.add(r.getElementText()); + } + } else if (event == XMLStreamConstants.END_ELEMENT) { + if ("Aliases".equals(r.getLocalName())) { + inAliases = false; + } + } + } + r.close(); + } catch (Exception ignored) { + } + return result; + } + + private Map parseViewerCertificate(String body) { + Map result = new LinkedHashMap<>(); + if (body == null || body.isEmpty()) { + return result; + } + try { + XMLStreamReader r = XML_FACTORY.createXMLStreamReader(new StringReader(body)); + boolean inVc = false; + while (r.hasNext()) { + int event = r.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + String local = r.getLocalName(); + if ("ViewerCertificate".equals(local)) { + inVc = true; + } else if (inVc) { + String text = r.getElementText(); + result.put(local, text); + } + } else if (event == XMLStreamConstants.END_ELEMENT) { + if ("ViewerCertificate".equals(r.getLocalName())) { + inVc = false; + } + } + } + r.close(); + } catch (Exception ignored) { + } + return result; + } + + private Invalidation parseInvalidation(String body) { + Invalidation inv = new Invalidation(); + inv.setCallerReference(XmlParser.extractFirst(body, "CallerReference", null)); + inv.setPaths(XmlParser.extractAll(body, "Path")); + return inv; + } + + private CachePolicy parseCachePolicy(String body) { + CachePolicy policy = new CachePolicy(); + policy.setName(XmlParser.extractFirst(body, "Name", null)); + policy.setComment(XmlParser.extractFirst(body, "Comment", null)); + return policy; + } + + private OriginRequestPolicy parseOriginRequestPolicy(String body) { + OriginRequestPolicy policy = new OriginRequestPolicy(); + policy.setName(XmlParser.extractFirst(body, "Name", null)); + policy.setComment(XmlParser.extractFirst(body, "Comment", null)); + return policy; + } + + private ResponseHeadersPolicy parseResponseHeadersPolicy(String body) { + ResponseHeadersPolicy policy = new ResponseHeadersPolicy(); + policy.setName(XmlParser.extractFirst(body, "Name", null)); + policy.setComment(XmlParser.extractFirst(body, "Comment", null)); + return policy; + } + + private OriginAccessControl parseOriginAccessControl(String body) { + OriginAccessControl oac = new OriginAccessControl(); + oac.setName(XmlParser.extractFirst(body, "Name", null)); + oac.setDescription(XmlParser.extractFirst(body, "Description", null)); + oac.setSigningProtocol(XmlParser.extractFirst(body, "SigningProtocol", "sigv4")); + oac.setSigningBehavior(XmlParser.extractFirst(body, "SigningBehavior", "always")); + oac.setOriginAccessControlOriginType(XmlParser.extractFirst(body, "OriginAccessControlOriginType", "s3")); + return oac; + } + + private CloudFrontOriginAccessIdentity parseOai(String body) { + CloudFrontOriginAccessIdentity oai = new CloudFrontOriginAccessIdentity(); + oai.setCallerReference(XmlParser.extractFirst(body, "CallerReference", null)); + oai.setComment(XmlParser.extractFirst(body, "Comment", null)); + return oai; + } + + private CloudFrontFunction parseFunction(String body) { + CloudFrontFunction fn = new CloudFrontFunction(); + fn.setName(XmlParser.extractFirst(body, "Name", null)); + fn.setComment(XmlParser.extractFirst(body, "Comment", null)); + fn.setRuntime(XmlParser.extractFirst(body, "Runtime", "cloudfront-js-2.0")); + fn.setFunctionCode(XmlParser.extractFirst(body, "FunctionCode", null)); + return fn; + } + + // ── Phase 2 XML builders ────────────────────────────────────────────────── + + private String xmlContinuousDeploymentPolicyResponse(ContinuousDeploymentPolicy policy) { + XmlBuilder xml = new XmlBuilder() + .start("ContinuousDeploymentPolicy") + .elem("Id", policy.getId()) + .elem("LastModifiedTime", + policy.getLastModifiedTime() != null ? policy.getLastModifiedTime().toString() : "") + .start("ContinuousDeploymentPolicyConfig") + .elem("Enabled", policy.isEnabled()); + List dns = policy.getStagingDistributionDnsNames(); + int dnsCount = dns != null ? dns.size() : 0; + xml.start("StagingDistributionDnsNames").elem("Quantity", dnsCount); + if (dnsCount > 0) { + xml.start("Items"); + for (String d : dns) { + xml.elem("DnsName", d); + } + xml.end("Items"); + } + xml.end("StagingDistributionDnsNames") + .end("ContinuousDeploymentPolicyConfig") + .end("ContinuousDeploymentPolicy"); + return xml.build(); + } + + private String xmlPublicKeyResponse(PublicKey key) { + return new XmlBuilder() + .start("PublicKey") + .elem("Id", key.getId()) + .elem("CreatedTime", key.getCreatedTime() != null ? key.getCreatedTime().toString() : "") + .start("PublicKeyConfig") + .elem("CallerReference", key.getCallerReference() != null ? key.getCallerReference() : "") + .elem("Name", key.getName() != null ? key.getName() : "") + .elem("EncodedKey", key.getEncodedKey() != null ? key.getEncodedKey() : "") + .elem("Comment", key.getComment() != null ? key.getComment() : "") + .end("PublicKeyConfig") + .end("PublicKey") + .build(); + } + + private String xmlPublicKeySummary(PublicKey key) { + return new XmlBuilder() + .start("PublicKeySummary") + .elem("Id", key.getId()) + .elem("Name", key.getName() != null ? key.getName() : "") + .elem("CreatedTime", key.getCreatedTime() != null ? key.getCreatedTime().toString() : "") + .elem("EncodedKey", key.getEncodedKey() != null ? key.getEncodedKey() : "") + .elem("Comment", key.getComment() != null ? key.getComment() : "") + .end("PublicKeySummary") + .build(); + } + + private String xmlKeyGroupResponse(KeyGroup group) { + List items = group.getItems() != null ? group.getItems() : List.of(); + XmlBuilder xml = new XmlBuilder() + .start("KeyGroup") + .elem("Id", group.getId()) + .elem("LastModifiedTime", + group.getLastModifiedTime() != null ? group.getLastModifiedTime().toString() : "") + .start("KeyGroupConfig") + .elem("Name", group.getName() != null ? group.getName() : "") + .elem("Comment", group.getComment() != null ? group.getComment() : "") + .raw(xmlQuantityItems("Items", "PublicKey", items.size(), + items.stream().map(k -> "" + XmlBuilder.escape(k) + "").toList())) + .end("KeyGroupConfig") + .end("KeyGroup"); + return xml.build(); + } + + private String xmlRealtimeLogConfigBody(RealtimeLogConfig cfg) { + List fields = cfg.getFields() != null ? cfg.getFields() : List.of(); + XmlBuilder xml = new XmlBuilder() + .start("RealtimeLogConfig") + .elem("ARN", cfg.getArn() != null ? cfg.getArn() : "") + .elem("Name", cfg.getName() != null ? cfg.getName() : "") + .elem("SamplingRate", cfg.getSamplingRate()) + .start("Fields") + .elem("Quantity", fields.size()); + if (!fields.isEmpty()) { + xml.start("Items"); + for (String f : fields) { + xml.elem("Field", f); + } + xml.end("Items"); + } + xml.end("Fields"); + xml.start("EndPoints").elem("Quantity", 0).end("EndPoints"); + xml.end("RealtimeLogConfig"); + return xml.build(); + } + + private String xmlStreamingDistributionResponse(StreamingDistribution sd) { + return new XmlBuilder() + .start("StreamingDistribution", NS) + .elem("Id", sd.getId()) + .elem("ARN", sd.getArn() != null ? sd.getArn() : "") + .elem("Status", sd.getStatus()) + .elem("DomainName", sd.getDomainName() != null ? sd.getDomainName() : "") + .elem("LastModifiedTime", + sd.getLastModifiedTime() != null ? sd.getLastModifiedTime().toString() : "") + .start("ActiveTrustedSigners") + .elem("Enabled", false) + .elem("Quantity", 0) + .end("ActiveTrustedSigners") + .raw(xmlStreamingDistributionConfigBody(sd)) + .end("StreamingDistribution") + .build(); + } + + private String xmlStreamingDistributionConfigBody(StreamingDistribution sd) { + List aliases = sd.getAliases() != null ? sd.getAliases() : List.of(); + XmlBuilder xml = new XmlBuilder() + .start("StreamingDistributionConfig") + .elem("CallerReference", sd.getCallerReference() != null ? sd.getCallerReference() : "") + .elem("Comment", sd.getComment() != null ? sd.getComment() : "") + .elem("Enabled", sd.isEnabled()) + .elem("PriceClass", sd.getPriceClass() != null ? sd.getPriceClass() : "PriceClass_All") + .start("S3Origin") + .elem("DomainName", sd.getS3Bucket() != null ? sd.getS3Bucket() : "") + .elem("OriginAccessIdentity", + sd.getS3OriginAccessIdentity() != null ? sd.getS3OriginAccessIdentity() : "") + .end("S3Origin") + .start("Aliases").elem("Quantity", aliases.size()); + if (!aliases.isEmpty()) { + xml.start("Items"); + for (String a : aliases) { + xml.elem("CNAME", a); + } + xml.end("Items"); + } + xml.end("Aliases") + .start("TrustedSigners").elem("Enabled", false).elem("Quantity", 0).end("TrustedSigners") + .end("StreamingDistributionConfig"); + return xml.build(); + } + + private String xmlFieldLevelEncryptionConfigResponse(FieldLevelEncryptionConfig cfg) { + return new XmlBuilder() + .start("FieldLevelEncryption") + .elem("Id", cfg.getId()) + .elem("LastModifiedTime", + cfg.getLastModifiedTime() != null ? cfg.getLastModifiedTime().toString() : "") + .start("FieldLevelEncryptionConfig") + .elem("CallerReference", cfg.getCallerReference() != null ? cfg.getCallerReference() : "") + .elem("Comment", cfg.getComment() != null ? cfg.getComment() : "") + .end("FieldLevelEncryptionConfig") + .end("FieldLevelEncryption") + .build(); + } + + private String xmlFieldLevelEncryptionProfileResponse(FieldLevelEncryptionProfile profile) { + return new XmlBuilder() + .start("FieldLevelEncryptionProfile") + .elem("Id", profile.getId()) + .elem("LastModifiedTime", + profile.getLastModifiedTime() != null ? profile.getLastModifiedTime().toString() : "") + .start("FieldLevelEncryptionProfileConfig") + .elem("Name", profile.getName() != null ? profile.getName() : "") + .elem("CallerReference", + profile.getCallerReference() != null ? profile.getCallerReference() : "") + .elem("Comment", profile.getComment() != null ? profile.getComment() : "") + .start("EncryptionEntities").elem("Quantity", 0).end("EncryptionEntities") + .end("FieldLevelEncryptionProfileConfig") + .end("FieldLevelEncryptionProfile") + .build(); + } + + private String xmlMonitoringSubscriptionResponse(MonitoringSubscription sub) { + return new XmlBuilder() + .start("MonitoringSubscription", NS) + .start("RealtimeMetricsSubscriptionConfig") + .elem("RealtimeMetricsSubscriptionStatus", + sub.getRealtimeMetricsSubscriptionStatus() != null + ? sub.getRealtimeMetricsSubscriptionStatus() : "Disabled") + .end("RealtimeMetricsSubscriptionConfig") + .end("MonitoringSubscription") + .build(); + } + + // ── Phase 2 request parsers ─────────────────────────────────────────────── + + private ContinuousDeploymentPolicy parseContinuousDeploymentPolicy(String body) { + ContinuousDeploymentPolicy policy = new ContinuousDeploymentPolicy(); + policy.setEnabled("true".equalsIgnoreCase(XmlParser.extractFirst(body, "Enabled", "false"))); + policy.setStagingDistributionDnsNames(XmlParser.extractAll(body, "DnsName")); + return policy; + } + + private PublicKey parsePublicKey(String body) { + PublicKey key = new PublicKey(); + key.setCallerReference(XmlParser.extractFirst(body, "CallerReference", null)); + key.setName(XmlParser.extractFirst(body, "Name", null)); + key.setEncodedKey(XmlParser.extractFirst(body, "EncodedKey", null)); + key.setComment(XmlParser.extractFirst(body, "Comment", null)); + return key; + } + + private KeyGroup parseKeyGroup(String body) { + KeyGroup group = new KeyGroup(); + group.setName(XmlParser.extractFirst(body, "Name", null)); + group.setComment(XmlParser.extractFirst(body, "Comment", null)); + group.setItems(XmlParser.extractAll(body, "PublicKey")); + return group; + } + + private RealtimeLogConfig parseRealtimeLogConfig(String body) { + RealtimeLogConfig cfg = new RealtimeLogConfig(); + cfg.setName(XmlParser.extractFirst(body, "Name", null)); + String sr = XmlParser.extractFirst(body, "SamplingRate", "100"); + try { + cfg.setSamplingRate(Long.parseLong(sr)); + } catch (NumberFormatException ignored) { + cfg.setSamplingRate(100); + } + cfg.setFields(XmlParser.extractAll(body, "Field")); + return cfg; + } + + private StreamingDistribution parseStreamingDistribution(String body) { + StreamingDistribution sd = new StreamingDistribution(); + sd.setCallerReference(XmlParser.extractFirst(body, "CallerReference", null)); + sd.setEnabled("true".equalsIgnoreCase(XmlParser.extractFirst(body, "Enabled", "false"))); + sd.setComment(XmlParser.extractFirst(body, "Comment", "")); + sd.setPriceClass(XmlParser.extractFirst(body, "PriceClass", "PriceClass_All")); + sd.setS3Bucket(XmlParser.extractFirst(body, "DomainName", null)); + sd.setS3OriginAccessIdentity(XmlParser.extractFirst(body, "OriginAccessIdentity", "")); + sd.setAliases(XmlParser.extractAll(body, "CNAME")); + return sd; + } + + private FieldLevelEncryptionConfig parseFieldLevelEncryptionConfig(String body) { + FieldLevelEncryptionConfig cfg = new FieldLevelEncryptionConfig(); + cfg.setCallerReference(XmlParser.extractFirst(body, "CallerReference", null)); + cfg.setComment(XmlParser.extractFirst(body, "Comment", null)); + return cfg; + } + + private FieldLevelEncryptionProfile parseFieldLevelEncryptionProfile(String body) { + FieldLevelEncryptionProfile profile = new FieldLevelEncryptionProfile(); + profile.setName(XmlParser.extractFirst(body, "Name", null)); + profile.setCallerReference(XmlParser.extractFirst(body, "CallerReference", null)); + profile.setComment(XmlParser.extractFirst(body, "Comment", null)); + return profile; + } + + private MonitoringSubscription parseMonitoringSubscription(String body) { + MonitoringSubscription sub = new MonitoringSubscription(); + sub.setRealtimeMetricsSubscriptionStatus( + XmlParser.extractFirst(body, "RealtimeMetricsSubscriptionStatus", "Enabled")); + return sub; + } + + private Map parseTags(String body) { + Map tags = new LinkedHashMap<>(); + List> groups = XmlParser.extractGroups(body, "Tag"); + for (Map group : groups) { + String key = group.get("Key"); + if (key != null) { + tags.put(key, group.getOrDefault("Value", "")); + } + } + return tags; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java new file mode 100644 index 0000000000..1bd97c6d28 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java @@ -0,0 +1,1016 @@ +package io.github.hectorvent.floci.services.cloudfront; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.cloudfront.model.CachePolicy; +import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontFunction; +import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontOriginAccessIdentity; +import io.github.hectorvent.floci.services.cloudfront.model.ContinuousDeploymentPolicy; +import io.github.hectorvent.floci.services.cloudfront.model.Distribution; +import io.github.hectorvent.floci.services.cloudfront.model.FieldLevelEncryptionConfig; +import io.github.hectorvent.floci.services.cloudfront.model.FieldLevelEncryptionProfile; +import io.github.hectorvent.floci.services.cloudfront.model.Invalidation; +import io.github.hectorvent.floci.services.cloudfront.model.KeyGroup; +import io.github.hectorvent.floci.services.cloudfront.model.MonitoringSubscription; +import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl; +import io.github.hectorvent.floci.services.cloudfront.model.OriginRequestPolicy; +import io.github.hectorvent.floci.services.cloudfront.model.PublicKey; +import io.github.hectorvent.floci.services.cloudfront.model.RealtimeLogConfig; +import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolicy; +import io.github.hectorvent.floci.services.cloudfront.model.StreamingDistribution; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.security.SecureRandom; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; + +@ApplicationScoped +public class CloudFrontService { + + private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + private static final SecureRandom RANDOM = new SecureRandom(); + + private final StorageBackend distStore; + private final StorageBackend> invalidationStore; + private final StorageBackend cachePolicyStore; + private final StorageBackend orpStore; + private final StorageBackend rhpStore; + private final StorageBackend oacStore; + private final StorageBackend oaiStore; + private final StorageBackend functionStore; + private final StorageBackend> tagStore; + private final StorageBackend cdpStore; + private final StorageBackend publicKeyStore; + private final StorageBackend keyGroupStore; + private final StorageBackend realtimeLogConfigStore; + private final StorageBackend streamingDistStore; + private final StorageBackend fleConfigStore; + private final StorageBackend fleProfileStore; + private final StorageBackend monitoringStore; + private final String accountId; + + @Inject + public CloudFrontService(StorageFactory factory, EmulatorConfig config) { + this.distStore = factory.create("cloudfront", "cloudfront-distributions.json", + new TypeReference>() {}); + this.invalidationStore = factory.create("cloudfront", "cloudfront-invalidations.json", + new TypeReference>>() {}); + this.cachePolicyStore = factory.create("cloudfront", "cloudfront-cache-policies.json", + new TypeReference>() {}); + this.orpStore = factory.create("cloudfront", "cloudfront-origin-request-policies.json", + new TypeReference>() {}); + this.rhpStore = factory.create("cloudfront", "cloudfront-response-headers-policies.json", + new TypeReference>() {}); + this.oacStore = factory.create("cloudfront", "cloudfront-oac.json", + new TypeReference>() {}); + this.oaiStore = factory.create("cloudfront", "cloudfront-oai.json", + new TypeReference>() {}); + this.functionStore = factory.create("cloudfront", "cloudfront-functions.json", + new TypeReference>() {}); + this.tagStore = factory.create("cloudfront", "cloudfront-tags.json", + new TypeReference>>() {}); + this.cdpStore = factory.create("cloudfront", "cloudfront-continuous-deployment-policies.json", + new TypeReference>() {}); + this.publicKeyStore = factory.create("cloudfront", "cloudfront-public-keys.json", + new TypeReference>() {}); + this.keyGroupStore = factory.create("cloudfront", "cloudfront-key-groups.json", + new TypeReference>() {}); + this.realtimeLogConfigStore = factory.create("cloudfront", "cloudfront-realtime-log-configs.json", + new TypeReference>() {}); + this.streamingDistStore = factory.create("cloudfront", "cloudfront-streaming-distributions.json", + new TypeReference>() {}); + this.fleConfigStore = factory.create("cloudfront", "cloudfront-fle-configs.json", + new TypeReference>() {}); + this.fleProfileStore = factory.create("cloudfront", "cloudfront-fle-profiles.json", + new TypeReference>() {}); + this.monitoringStore = factory.create("cloudfront", "cloudfront-monitoring-subscriptions.json", + new TypeReference>() {}); + this.accountId = config.defaultAccountId(); + } + + // ── Distributions ───────────────────────────────────────────────────────── + + public synchronized Distribution createDistribution(Distribution dist, Map tags) { + String id = generateDistributionId(); + dist.setId(id); + dist.setArn("arn:aws:cloudfront::" + accountId + ":distribution/" + id); + dist.setDomainName(id + ".cloudfront.net"); + dist.setStatus("Deployed"); + dist.setLastModifiedTime(Instant.now()); + dist.setEtag(UUID.randomUUID().toString()); + if (tags != null && !tags.isEmpty()) { + dist.setTags(tags); + tagStore.put("distribution/" + id, tags); + } + distStore.put(id, dist); + return dist; + } + + public Distribution getDistribution(String id) { + return distStore.get(id).orElseThrow(() -> + new AwsException("NoSuchDistribution", "The specified distribution does not exist.", 404)); + } + + public synchronized Distribution updateDistribution(String id, String ifMatch, Distribution updated) { + Distribution existing = getDistribution(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setArn(existing.getArn()); + updated.setDomainName(existing.getDomainName()); + updated.setStatus("Deployed"); + updated.setLastModifiedTime(Instant.now()); + updated.setEtag(UUID.randomUUID().toString()); + updated.setTags(existing.getTags()); + distStore.put(id, updated); + return updated; + } + + public synchronized void deleteDistribution(String id, String ifMatch) { + Distribution existing = getDistribution(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + if (existing.getConfig() != null && existing.getConfig().isEnabled()) { + throw new AwsException("DistributionNotDisabled", + "The distribution you are trying to delete has not been disabled.", 409); + } + distStore.delete(id); + invalidationStore.delete(id); + tagStore.delete("distribution/" + id); + } + + public List listDistributions(String marker, int maxItems) { + List all = new ArrayList<>(distStore.scan(k -> true)); + all.sort((a, b) -> a.getId().compareTo(b.getId())); + if (marker != null && !marker.isEmpty()) { + int idx = 0; + for (int i = 0; i < all.size(); i++) { + if (all.get(i).getId().equals(marker)) { + idx = i + 1; + break; + } + } + all = all.subList(idx, all.size()); + } + if (maxItems > 0 && all.size() > maxItems) { + return all.subList(0, maxItems); + } + return all; + } + + public synchronized void associateAlias(String targetDistributionId, String alias) { + Distribution dist = getDistribution(targetDistributionId); + List aliases = dist.getConfig() != null ? dist.getConfig().getAliases() : null; + if (aliases == null) { + aliases = new ArrayList<>(); + } else { + aliases = new ArrayList<>(aliases); + } + if (!aliases.contains(alias)) { + aliases.add(alias); + } + if (dist.getConfig() != null) { + dist.getConfig().setAliases(aliases); + } + dist.setEtag(UUID.randomUUID().toString()); + distStore.put(targetDistributionId, dist); + } + + // ── Invalidations ───────────────────────────────────────────────────────── + + public synchronized Invalidation createInvalidation(String distributionId, Invalidation inv) { + getDistribution(distributionId); + inv.setId(generateInvalidationId()); + inv.setStatus("Completed"); + inv.setCreateTime(Instant.now()); + List list = new ArrayList<>( + invalidationStore.get(distributionId).orElse(new ArrayList<>())); + list.add(inv); + invalidationStore.put(distributionId, list); + return inv; + } + + public Invalidation getInvalidation(String distributionId, String invId) { + getDistribution(distributionId); + List list = invalidationStore.get(distributionId).orElse(List.of()); + return list.stream() + .filter(i -> i.getId().equals(invId)) + .findFirst() + .orElseThrow(() -> new AwsException("NoSuchInvalidation", + "The specified invalidation does not exist.", 404)); + } + + public List listInvalidations(String distributionId, String marker, int maxItems) { + getDistribution(distributionId); + List all = new ArrayList<>( + invalidationStore.get(distributionId).orElse(List.of())); + if (marker != null && !marker.isEmpty()) { + int idx = 0; + for (int i = 0; i < all.size(); i++) { + if (all.get(i).getId().equals(marker)) { + idx = i + 1; + break; + } + } + all = all.subList(idx, all.size()); + } + if (maxItems > 0 && all.size() > maxItems) { + return all.subList(0, maxItems); + } + return all; + } + + // ── Cache Policies ──────────────────────────────────────────────────────── + + public synchronized CachePolicy createCachePolicy(CachePolicy policy) { + policy.setId(UUID.randomUUID().toString()); + policy.setEtag(UUID.randomUUID().toString()); + policy.setLastModifiedTime(Instant.now()); + cachePolicyStore.put(policy.getId(), policy); + return policy; + } + + public CachePolicy getCachePolicy(String id) { + return cachePolicyStore.get(id).orElseThrow(() -> + new AwsException("NoSuchCachePolicy", "The specified cache policy does not exist.", 404)); + } + + public synchronized CachePolicy updateCachePolicy(String id, String ifMatch, CachePolicy updated) { + CachePolicy existing = getCachePolicy(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setEtag(UUID.randomUUID().toString()); + updated.setLastModifiedTime(Instant.now()); + cachePolicyStore.put(id, updated); + return updated; + } + + public synchronized void deleteCachePolicy(String id, String ifMatch) { + CachePolicy existing = getCachePolicy(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + cachePolicyStore.delete(id); + } + + public List listCachePolicies(String marker, int maxItems) { + List all = new ArrayList<>(cachePolicyStore.scan(k -> true)); + all.sort((a, b) -> a.getName() != null && b.getName() != null + ? a.getName().compareTo(b.getName()) : a.getId().compareTo(b.getId())); + if (marker != null && !marker.isEmpty()) { + int idx = 0; + for (int i = 0; i < all.size(); i++) { + if (all.get(i).getId().equals(marker)) { + idx = i + 1; + break; + } + } + all = all.subList(idx, all.size()); + } + if (maxItems > 0 && all.size() > maxItems) { + return all.subList(0, maxItems); + } + return all; + } + + // ── Origin Request Policies ─────────────────────────────────────────────── + + public synchronized OriginRequestPolicy createOriginRequestPolicy(OriginRequestPolicy policy) { + policy.setId(UUID.randomUUID().toString()); + policy.setEtag(UUID.randomUUID().toString()); + policy.setLastModifiedTime(Instant.now()); + orpStore.put(policy.getId(), policy); + return policy; + } + + public OriginRequestPolicy getOriginRequestPolicy(String id) { + return orpStore.get(id).orElseThrow(() -> + new AwsException("NoSuchOriginRequestPolicy", + "The specified origin request policy does not exist.", 404)); + } + + public synchronized OriginRequestPolicy updateOriginRequestPolicy(String id, String ifMatch, + OriginRequestPolicy updated) { + OriginRequestPolicy existing = getOriginRequestPolicy(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setEtag(UUID.randomUUID().toString()); + updated.setLastModifiedTime(Instant.now()); + orpStore.put(id, updated); + return updated; + } + + public synchronized void deleteOriginRequestPolicy(String id, String ifMatch) { + OriginRequestPolicy existing = getOriginRequestPolicy(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + orpStore.delete(id); + } + + public List listOriginRequestPolicies(String marker, int maxItems) { + List all = new ArrayList<>(orpStore.scan(k -> true)); + all.sort((a, b) -> a.getName() != null && b.getName() != null + ? a.getName().compareTo(b.getName()) : a.getId().compareTo(b.getId())); + if (marker != null && !marker.isEmpty()) { + int idx = 0; + for (int i = 0; i < all.size(); i++) { + if (all.get(i).getId().equals(marker)) { + idx = i + 1; + break; + } + } + all = all.subList(idx, all.size()); + } + if (maxItems > 0 && all.size() > maxItems) { + return all.subList(0, maxItems); + } + return all; + } + + // ── Response Headers Policies ───────────────────────────────────────────── + + public synchronized ResponseHeadersPolicy createResponseHeadersPolicy(ResponseHeadersPolicy policy) { + policy.setId(UUID.randomUUID().toString()); + policy.setEtag(UUID.randomUUID().toString()); + policy.setLastModifiedTime(Instant.now()); + rhpStore.put(policy.getId(), policy); + return policy; + } + + public ResponseHeadersPolicy getResponseHeadersPolicy(String id) { + return rhpStore.get(id).orElseThrow(() -> + new AwsException("NoSuchResponseHeadersPolicy", + "The specified response headers policy does not exist.", 404)); + } + + public synchronized ResponseHeadersPolicy updateResponseHeadersPolicy(String id, String ifMatch, + ResponseHeadersPolicy updated) { + ResponseHeadersPolicy existing = getResponseHeadersPolicy(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setEtag(UUID.randomUUID().toString()); + updated.setLastModifiedTime(Instant.now()); + rhpStore.put(id, updated); + return updated; + } + + public synchronized void deleteResponseHeadersPolicy(String id, String ifMatch) { + ResponseHeadersPolicy existing = getResponseHeadersPolicy(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + rhpStore.delete(id); + } + + public List listResponseHeadersPolicies(String marker, int maxItems) { + List all = new ArrayList<>(rhpStore.scan(k -> true)); + all.sort((a, b) -> a.getName() != null && b.getName() != null + ? a.getName().compareTo(b.getName()) : a.getId().compareTo(b.getId())); + if (marker != null && !marker.isEmpty()) { + int idx = 0; + for (int i = 0; i < all.size(); i++) { + if (all.get(i).getId().equals(marker)) { + idx = i + 1; + break; + } + } + all = all.subList(idx, all.size()); + } + if (maxItems > 0 && all.size() > maxItems) { + return all.subList(0, maxItems); + } + return all; + } + + // ── Origin Access Control ───────────────────────────────────────────────── + + public synchronized OriginAccessControl createOriginAccessControl(OriginAccessControl oac) { + oac.setId(UUID.randomUUID().toString()); + oac.setEtag(UUID.randomUUID().toString()); + oac.setLastModifiedTime(Instant.now()); + oacStore.put(oac.getId(), oac); + return oac; + } + + public OriginAccessControl getOriginAccessControl(String id) { + return oacStore.get(id).orElseThrow(() -> + new AwsException("NoSuchOriginAccessControl", + "The specified origin access control does not exist.", 404)); + } + + public synchronized OriginAccessControl updateOriginAccessControl(String id, String ifMatch, + OriginAccessControl updated) { + OriginAccessControl existing = getOriginAccessControl(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setEtag(UUID.randomUUID().toString()); + updated.setLastModifiedTime(Instant.now()); + oacStore.put(id, updated); + return updated; + } + + public synchronized void deleteOriginAccessControl(String id, String ifMatch) { + OriginAccessControl existing = getOriginAccessControl(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + oacStore.delete(id); + } + + public List listOriginAccessControls(String marker, int maxItems) { + List all = new ArrayList<>(oacStore.scan(k -> true)); + all.sort((a, b) -> a.getName() != null && b.getName() != null + ? a.getName().compareTo(b.getName()) : a.getId().compareTo(b.getId())); + if (marker != null && !marker.isEmpty()) { + int idx = 0; + for (int i = 0; i < all.size(); i++) { + if (all.get(i).getId().equals(marker)) { + idx = i + 1; + break; + } + } + all = all.subList(idx, all.size()); + } + if (maxItems > 0 && all.size() > maxItems) { + return all.subList(0, maxItems); + } + return all; + } + + // ── Origin Access Identity (OAI) ────────────────────────────────────────── + + public synchronized CloudFrontOriginAccessIdentity createCloudFrontOriginAccessIdentity( + CloudFrontOriginAccessIdentity oai) { + for (CloudFrontOriginAccessIdentity existing : oaiStore.scan(k -> true)) { + if (oai.getCallerReference() != null + && oai.getCallerReference().equals(existing.getCallerReference())) { + throw new AwsException("CloudFrontOriginAccessIdentityAlreadyExists", + "An origin access identity with the caller reference already exists.", 409); + } + } + oai.setId(generateDistributionId()); + oai.setS3CanonicalUserId(UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "")); + oai.setEtag(UUID.randomUUID().toString()); + oaiStore.put(oai.getId(), oai); + return oai; + } + + public CloudFrontOriginAccessIdentity getCloudFrontOriginAccessIdentity(String id) { + return oaiStore.get(id).orElseThrow(() -> + new AwsException("NoSuchCloudFrontOriginAccessIdentity", + "The specified origin access identity does not exist.", 404)); + } + + public synchronized CloudFrontOriginAccessIdentity updateCloudFrontOriginAccessIdentity( + String id, String ifMatch, CloudFrontOriginAccessIdentity updated) { + CloudFrontOriginAccessIdentity existing = getCloudFrontOriginAccessIdentity(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setS3CanonicalUserId(existing.getS3CanonicalUserId()); + updated.setEtag(UUID.randomUUID().toString()); + oaiStore.put(id, updated); + return updated; + } + + public synchronized void deleteCloudFrontOriginAccessIdentity(String id, String ifMatch) { + CloudFrontOriginAccessIdentity existing = getCloudFrontOriginAccessIdentity(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + oaiStore.delete(id); + } + + public List listCloudFrontOriginAccessIdentities( + String marker, int maxItems) { + List all = new ArrayList<>(oaiStore.scan(k -> true)); + if (marker != null && !marker.isEmpty()) { + int idx = 0; + for (int i = 0; i < all.size(); i++) { + if (all.get(i).getId().equals(marker)) { + idx = i + 1; + break; + } + } + all = all.subList(idx, all.size()); + } + if (maxItems > 0 && all.size() > maxItems) { + return all.subList(0, maxItems); + } + return all; + } + + // ── CloudFront Functions ────────────────────────────────────────────────── + + public synchronized CloudFrontFunction createFunction(CloudFrontFunction fn) { + fn.setStage("DEVELOPMENT"); + fn.setStatus("UNPUBLISHED"); + fn.setEtag(UUID.randomUUID().toString()); + fn.setCreatedTime(Instant.now()); + fn.setLastModifiedTime(Instant.now()); + functionStore.put(fn.getName(), fn); + return fn; + } + + public CloudFrontFunction describeFunction(String name, String stage) { + CloudFrontFunction fn = functionStore.get(name).orElseThrow(() -> + new AwsException("NoSuchFunctionExists", + "The specified function does not exist.", 404)); + if (stage != null && !stage.isEmpty() && !fn.getStage().equals(stage)) { + throw new AwsException("NoSuchFunctionExists", + "The specified function does not exist.", 404); + } + return fn; + } + + public synchronized CloudFrontFunction updateFunction(String name, String ifMatch, + CloudFrontFunction updated) { + CloudFrontFunction existing = describeFunction(name, null); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setName(name); + updated.setStage(existing.getStage()); + updated.setStatus(existing.getStatus()); + updated.setEtag(UUID.randomUUID().toString()); + updated.setCreatedTime(existing.getCreatedTime()); + updated.setLastModifiedTime(Instant.now()); + functionStore.put(name, updated); + return updated; + } + + public synchronized CloudFrontFunction publishFunction(String name, String ifMatch) { + CloudFrontFunction fn = describeFunction(name, null); + if (!fn.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + fn.setStage("LIVE"); + fn.setStatus("DEPLOYED"); + fn.setEtag(UUID.randomUUID().toString()); + fn.setLastModifiedTime(Instant.now()); + functionStore.put(name, fn); + return fn; + } + + public synchronized void deleteFunction(String name, String ifMatch) { + CloudFrontFunction existing = describeFunction(name, null); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + functionStore.delete(name); + } + + public List listFunctions(String stage) { + List all = new ArrayList<>(functionStore.scan(k -> true)); + if (stage != null && !stage.isEmpty()) { + all = all.stream().filter(f -> stage.equals(f.getStage())).toList(); + all = new ArrayList<>(all); + } + all.sort((a, b) -> a.getName().compareTo(b.getName())); + return all; + } + + // ── Tags ────────────────────────────────────────────────────────────────── + + public Map listTagsForResource(String arn) { + return tagStore.get(arn).orElse(new LinkedHashMap<>()); + } + + public synchronized void tagResource(String arn, Map tags) { + Map existing = new LinkedHashMap<>(tagStore.get(arn).orElse(new LinkedHashMap<>())); + existing.putAll(tags); + tagStore.put(arn, existing); + } + + public synchronized void untagResource(String arn, List tagKeys) { + Map existing = new LinkedHashMap<>(tagStore.get(arn).orElse(new LinkedHashMap<>())); + tagKeys.forEach(existing::remove); + tagStore.put(arn, existing); + } + + // ── Continuous Deployment Policies ─────────────────────────────────────── + + public synchronized ContinuousDeploymentPolicy createContinuousDeploymentPolicy( + ContinuousDeploymentPolicy policy) { + policy.setId(UUID.randomUUID().toString()); + policy.setLastModifiedTime(Instant.now()); + policy.setEtag(UUID.randomUUID().toString()); + cdpStore.put(policy.getId(), policy); + return policy; + } + + public ContinuousDeploymentPolicy getContinuousDeploymentPolicy(String id) { + return cdpStore.get(id).orElseThrow(() -> + new AwsException("NoSuchContinuousDeploymentPolicy", + "The specified continuous deployment policy does not exist.", 404)); + } + + public synchronized ContinuousDeploymentPolicy updateContinuousDeploymentPolicy( + String id, String ifMatch, ContinuousDeploymentPolicy updated) { + ContinuousDeploymentPolicy existing = getContinuousDeploymentPolicy(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setLastModifiedTime(Instant.now()); + updated.setEtag(UUID.randomUUID().toString()); + cdpStore.put(id, updated); + return updated; + } + + public synchronized void deleteContinuousDeploymentPolicy(String id, String ifMatch) { + ContinuousDeploymentPolicy existing = getContinuousDeploymentPolicy(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + cdpStore.delete(id); + } + + public List listContinuousDeploymentPolicies(String marker, int maxItems) { + List all = new ArrayList<>(cdpStore.scan(k -> true)); + all.sort((a, b) -> a.getId().compareTo(b.getId())); + return paginate(all, marker, maxItems, ContinuousDeploymentPolicy::getId); + } + + // ── CopyDistribution ────────────────────────────────────────────────────── + + public synchronized Distribution copyDistribution(String primaryDistributionId, String callerReference, + Map tags) { + Distribution primary = getDistribution(primaryDistributionId); + Distribution copy = new Distribution(); + copy.setConfig(primary.getConfig()); + if (copy.getConfig() != null) { + copy.getConfig().setCallerReference(callerReference); + copy.getConfig().setStaging(true); + } + return createDistribution(copy, tags); + } + + // ── Public Keys ─────────────────────────────────────────────────────────── + + public synchronized PublicKey createPublicKey(PublicKey key) { + key.setId(UUID.randomUUID().toString()); + key.setCreatedTime(Instant.now()); + key.setEtag(UUID.randomUUID().toString()); + publicKeyStore.put(key.getId(), key); + return key; + } + + public PublicKey getPublicKey(String id) { + return publicKeyStore.get(id).orElseThrow(() -> + new AwsException("NoSuchPublicKey", "The specified public key does not exist.", 404)); + } + + public synchronized PublicKey updatePublicKey(String id, String ifMatch, PublicKey updated) { + PublicKey existing = getPublicKey(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setCreatedTime(existing.getCreatedTime()); + updated.setEtag(UUID.randomUUID().toString()); + publicKeyStore.put(id, updated); + return updated; + } + + public synchronized void deletePublicKey(String id, String ifMatch) { + PublicKey existing = getPublicKey(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + publicKeyStore.delete(id); + } + + public List listPublicKeys(String marker, int maxItems) { + List all = new ArrayList<>(publicKeyStore.scan(k -> true)); + all.sort((a, b) -> a.getId().compareTo(b.getId())); + return paginate(all, marker, maxItems, PublicKey::getId); + } + + // ── Key Groups ──────────────────────────────────────────────────────────── + + public synchronized KeyGroup createKeyGroup(KeyGroup group) { + group.setId(UUID.randomUUID().toString()); + group.setLastModifiedTime(Instant.now()); + group.setEtag(UUID.randomUUID().toString()); + keyGroupStore.put(group.getId(), group); + return group; + } + + public KeyGroup getKeyGroup(String id) { + return keyGroupStore.get(id).orElseThrow(() -> + new AwsException("NoSuchResource", "The specified key group does not exist.", 404)); + } + + public synchronized KeyGroup updateKeyGroup(String id, String ifMatch, KeyGroup updated) { + KeyGroup existing = getKeyGroup(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setLastModifiedTime(Instant.now()); + updated.setEtag(UUID.randomUUID().toString()); + keyGroupStore.put(id, updated); + return updated; + } + + public synchronized void deleteKeyGroup(String id, String ifMatch) { + KeyGroup existing = getKeyGroup(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + keyGroupStore.delete(id); + } + + public List listKeyGroups(String marker, int maxItems) { + List all = new ArrayList<>(keyGroupStore.scan(k -> true)); + all.sort((a, b) -> a.getId().compareTo(b.getId())); + return paginate(all, marker, maxItems, KeyGroup::getId); + } + + // ── Realtime Log Configs ────────────────────────────────────────────────── + + public synchronized RealtimeLogConfig createRealtimeLogConfig(RealtimeLogConfig cfg) { + String arn = "arn:aws:cloudfront::" + accountId + ":realtime-log-config/" + cfg.getName(); + cfg.setArn(arn); + realtimeLogConfigStore.put(cfg.getName(), cfg); + return cfg; + } + + public RealtimeLogConfig getRealtimeLogConfig(String nameOrArn) { + if (nameOrArn != null && nameOrArn.startsWith("arn:")) { + String name = nameOrArn.substring(nameOrArn.lastIndexOf('/') + 1); + return realtimeLogConfigStore.get(name).orElseThrow(() -> + new AwsException("NoSuchRealtimeLogConfig", + "The specified realtime log configuration does not exist.", 404)); + } + return realtimeLogConfigStore.get(nameOrArn).orElseThrow(() -> + new AwsException("NoSuchRealtimeLogConfig", + "The specified realtime log configuration does not exist.", 404)); + } + + public synchronized RealtimeLogConfig updateRealtimeLogConfig(RealtimeLogConfig updated) { + getRealtimeLogConfig(updated.getName()); + String arn = "arn:aws:cloudfront::" + accountId + ":realtime-log-config/" + updated.getName(); + updated.setArn(arn); + realtimeLogConfigStore.put(updated.getName(), updated); + return updated; + } + + public synchronized void deleteRealtimeLogConfig(String nameOrArn) { + RealtimeLogConfig existing = getRealtimeLogConfig(nameOrArn); + String name = existing.getName(); + realtimeLogConfigStore.delete(name); + } + + public List listRealtimeLogConfigs(String marker, int maxItems) { + List all = new ArrayList<>(realtimeLogConfigStore.scan(k -> true)); + all.sort((a, b) -> a.getName().compareTo(b.getName())); + return paginate(all, marker, maxItems, RealtimeLogConfig::getName); + } + + // ── Streaming Distributions ─────────────────────────────────────────────── + + public synchronized StreamingDistribution createStreamingDistribution(StreamingDistribution sd) { + String id = generateDistributionId(); + sd.setId(id); + sd.setArn("arn:aws:cloudfront::" + accountId + ":streaming-distribution/" + id); + sd.setDomainName(id + ".cloudfront.net"); + sd.setStatus("Deployed"); + sd.setLastModifiedTime(Instant.now()); + sd.setEtag(UUID.randomUUID().toString()); + streamingDistStore.put(id, sd); + return sd; + } + + public StreamingDistribution getStreamingDistribution(String id) { + return streamingDistStore.get(id).orElseThrow(() -> + new AwsException("NoSuchStreamingDistribution", + "The specified streaming distribution does not exist.", 404)); + } + + public synchronized StreamingDistribution updateStreamingDistribution(String id, String ifMatch, + StreamingDistribution updated) { + StreamingDistribution existing = getStreamingDistribution(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setArn(existing.getArn()); + updated.setDomainName(existing.getDomainName()); + updated.setStatus("Deployed"); + updated.setLastModifiedTime(Instant.now()); + updated.setEtag(UUID.randomUUID().toString()); + streamingDistStore.put(id, updated); + return updated; + } + + public synchronized void deleteStreamingDistribution(String id, String ifMatch) { + StreamingDistribution existing = getStreamingDistribution(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + if (existing.isEnabled()) { + throw new AwsException("StreamingDistributionNotDisabled", + "The streaming distribution you are trying to delete has not been disabled.", 409); + } + streamingDistStore.delete(id); + } + + // ── Field-Level Encryption Configs ──────────────────────────────────────── + + public synchronized FieldLevelEncryptionConfig createFieldLevelEncryptionConfig( + FieldLevelEncryptionConfig cfg) { + cfg.setId(UUID.randomUUID().toString()); + cfg.setLastModifiedTime(Instant.now()); + cfg.setEtag(UUID.randomUUID().toString()); + fleConfigStore.put(cfg.getId(), cfg); + return cfg; + } + + public FieldLevelEncryptionConfig getFieldLevelEncryptionConfig(String id) { + return fleConfigStore.get(id).orElseThrow(() -> + new AwsException("NoSuchFieldLevelEncryptionConfig", + "The specified field-level encryption configuration does not exist.", 404)); + } + + public synchronized FieldLevelEncryptionConfig updateFieldLevelEncryptionConfig( + String id, String ifMatch, FieldLevelEncryptionConfig updated) { + FieldLevelEncryptionConfig existing = getFieldLevelEncryptionConfig(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setLastModifiedTime(Instant.now()); + updated.setEtag(UUID.randomUUID().toString()); + fleConfigStore.put(id, updated); + return updated; + } + + public synchronized void deleteFieldLevelEncryptionConfig(String id, String ifMatch) { + FieldLevelEncryptionConfig existing = getFieldLevelEncryptionConfig(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + fleConfigStore.delete(id); + } + + public List listFieldLevelEncryptionConfigs(String marker, int maxItems) { + List all = new ArrayList<>(fleConfigStore.scan(k -> true)); + all.sort((a, b) -> a.getId().compareTo(b.getId())); + return paginate(all, marker, maxItems, FieldLevelEncryptionConfig::getId); + } + + // ── Field-Level Encryption Profiles ────────────────────────────────────── + + public synchronized FieldLevelEncryptionProfile createFieldLevelEncryptionProfile( + FieldLevelEncryptionProfile profile) { + profile.setId(UUID.randomUUID().toString()); + profile.setLastModifiedTime(Instant.now()); + profile.setEtag(UUID.randomUUID().toString()); + fleProfileStore.put(profile.getId(), profile); + return profile; + } + + public FieldLevelEncryptionProfile getFieldLevelEncryptionProfile(String id) { + return fleProfileStore.get(id).orElseThrow(() -> + new AwsException("NoSuchFieldLevelEncryptionProfile", + "The specified field-level encryption profile does not exist.", 404)); + } + + public synchronized FieldLevelEncryptionProfile updateFieldLevelEncryptionProfile( + String id, String ifMatch, FieldLevelEncryptionProfile updated) { + FieldLevelEncryptionProfile existing = getFieldLevelEncryptionProfile(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + updated.setId(id); + updated.setLastModifiedTime(Instant.now()); + updated.setEtag(UUID.randomUUID().toString()); + fleProfileStore.put(id, updated); + return updated; + } + + public synchronized void deleteFieldLevelEncryptionProfile(String id, String ifMatch) { + FieldLevelEncryptionProfile existing = getFieldLevelEncryptionProfile(id); + if (!existing.getEtag().equals(ifMatch)) { + throw new AwsException("InvalidIfMatchVersion", + "The If-Match version is missing or not valid for the resource.", 400); + } + fleProfileStore.delete(id); + } + + public List listFieldLevelEncryptionProfiles(String marker, int maxItems) { + List all = new ArrayList<>(fleProfileStore.scan(k -> true)); + all.sort((a, b) -> a.getId().compareTo(b.getId())); + return paginate(all, marker, maxItems, FieldLevelEncryptionProfile::getId); + } + + // ── Monitoring Subscriptions ────────────────────────────────────────────── + + public synchronized MonitoringSubscription createMonitoringSubscription( + String distributionId, MonitoringSubscription subscription) { + getDistribution(distributionId); + subscription.setDistributionId(distributionId); + monitoringStore.put(distributionId, subscription); + return subscription; + } + + public MonitoringSubscription getMonitoringSubscription(String distributionId) { + return monitoringStore.get(distributionId).orElseThrow(() -> + new AwsException("NoSuchMonitoringSubscription", + "A monitoring subscription does not exist for the specified distribution.", 404)); + } + + public synchronized void deleteMonitoringSubscription(String distributionId) { + getMonitoringSubscription(distributionId); + monitoringStore.delete(distributionId); + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + + public String getAccountId() { + return accountId; + } + + private static String generateDistributionId() { + StringBuilder sb = new StringBuilder("E"); + for (int i = 0; i < 13; i++) { + sb.append(CHARS.charAt(RANDOM.nextInt(CHARS.length()))); + } + return sb.toString(); + } + + private static String generateInvalidationId() { + StringBuilder sb = new StringBuilder("I"); + for (int i = 0; i < 13; i++) { + sb.append(CHARS.charAt(RANDOM.nextInt(CHARS.length()))); + } + return sb.toString(); + } + + private List paginate(List all, String marker, int maxItems, + Function keyFn) { + if (marker != null && !marker.isEmpty()) { + int idx = 0; + for (int i = 0; i < all.size(); i++) { + if (marker.equals(keyFn.apply(all.get(i)))) { + idx = i + 1; + break; + } + } + all = all.subList(idx, all.size()); + } + if (maxItems > 0 && all.size() > maxItems) { + return all.subList(0, maxItems); + } + return all; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CacheBehavior.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CacheBehavior.java new file mode 100644 index 0000000000..0f8b84363b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CacheBehavior.java @@ -0,0 +1,74 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.util.List; +import java.util.Map; + +public class CacheBehavior { + + private String pathPattern; + private String targetOriginId; + private String viewerProtocolPolicy = "redirect-to-https"; + private List allowedMethods; + private List cachedMethods; + private String cachePolicyId; + private String originRequestPolicyId; + private String responseHeadersPolicyId; + private String fieldLevelEncryptionId; + private String realtimeLogConfigArn; + private List> functionAssociations; + private List> lambdaFunctionAssociations; + private boolean compress; + private long defaultTTL; + private long minTTL; + private long maxTTL; + + public CacheBehavior() {} + + public String getPathPattern() { return pathPattern; } + public void setPathPattern(String pathPattern) { this.pathPattern = pathPattern; } + + public String getTargetOriginId() { return targetOriginId; } + public void setTargetOriginId(String targetOriginId) { this.targetOriginId = targetOriginId; } + + public String getViewerProtocolPolicy() { return viewerProtocolPolicy; } + public void setViewerProtocolPolicy(String viewerProtocolPolicy) { this.viewerProtocolPolicy = viewerProtocolPolicy; } + + public List getAllowedMethods() { return allowedMethods; } + public void setAllowedMethods(List allowedMethods) { this.allowedMethods = allowedMethods; } + + public List getCachedMethods() { return cachedMethods; } + public void setCachedMethods(List cachedMethods) { this.cachedMethods = cachedMethods; } + + public String getCachePolicyId() { return cachePolicyId; } + public void setCachePolicyId(String cachePolicyId) { this.cachePolicyId = cachePolicyId; } + + public String getOriginRequestPolicyId() { return originRequestPolicyId; } + public void setOriginRequestPolicyId(String originRequestPolicyId) { this.originRequestPolicyId = originRequestPolicyId; } + + public String getResponseHeadersPolicyId() { return responseHeadersPolicyId; } + public void setResponseHeadersPolicyId(String responseHeadersPolicyId) { this.responseHeadersPolicyId = responseHeadersPolicyId; } + + public String getFieldLevelEncryptionId() { return fieldLevelEncryptionId; } + public void setFieldLevelEncryptionId(String fieldLevelEncryptionId) { this.fieldLevelEncryptionId = fieldLevelEncryptionId; } + + public String getRealtimeLogConfigArn() { return realtimeLogConfigArn; } + public void setRealtimeLogConfigArn(String realtimeLogConfigArn) { this.realtimeLogConfigArn = realtimeLogConfigArn; } + + public List> getFunctionAssociations() { return functionAssociations; } + public void setFunctionAssociations(List> functionAssociations) { this.functionAssociations = functionAssociations; } + + public List> getLambdaFunctionAssociations() { return lambdaFunctionAssociations; } + public void setLambdaFunctionAssociations(List> lambdaFunctionAssociations) { this.lambdaFunctionAssociations = lambdaFunctionAssociations; } + + public boolean isCompress() { return compress; } + public void setCompress(boolean compress) { this.compress = compress; } + + public long getDefaultTTL() { return defaultTTL; } + public void setDefaultTTL(long defaultTTL) { this.defaultTTL = defaultTTL; } + + public long getMinTTL() { return minTTL; } + public void setMinTTL(long minTTL) { this.minTTL = minTTL; } + + public long getMaxTTL() { return maxTTL; } + public void setMaxTTL(long maxTTL) { this.maxTTL = maxTTL; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CachePolicy.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CachePolicy.java new file mode 100644 index 0000000000..0d783654b9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CachePolicy.java @@ -0,0 +1,34 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; +import java.util.Map; + +public class CachePolicy { + + private String id; + private String name; + private String comment; + private String etag; + private Instant lastModifiedTime; + private Map config; + + public CachePolicy() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getComment() { return comment; } + public void setComment(String comment) { this.comment = comment; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + + public Map getConfig() { return config; } + public void setConfig(Map config) { this.config = config; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CloudFrontFunction.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CloudFrontFunction.java new file mode 100644 index 0000000000..eeaf2336a8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CloudFrontFunction.java @@ -0,0 +1,45 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; + +public class CloudFrontFunction { + + private String name; + private String stage; + private String status; + private String functionCode; + private String runtime; + private String comment; + private String etag; + private Instant createdTime; + private Instant lastModifiedTime; + + public CloudFrontFunction() {} + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getStage() { return stage; } + public void setStage(String stage) { this.stage = stage; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public String getFunctionCode() { return functionCode; } + public void setFunctionCode(String functionCode) { this.functionCode = functionCode; } + + public String getRuntime() { return runtime; } + public void setRuntime(String runtime) { this.runtime = runtime; } + + public String getComment() { return comment; } + public void setComment(String comment) { this.comment = comment; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public Instant getCreatedTime() { return createdTime; } + public void setCreatedTime(Instant createdTime) { this.createdTime = createdTime; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CloudFrontOriginAccessIdentity.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CloudFrontOriginAccessIdentity.java new file mode 100644 index 0000000000..c3f04c88f9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CloudFrontOriginAccessIdentity.java @@ -0,0 +1,27 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +public class CloudFrontOriginAccessIdentity { + + private String id; + private String s3CanonicalUserId; + private String callerReference; + private String comment; + private String etag; + + public CloudFrontOriginAccessIdentity() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getS3CanonicalUserId() { return s3CanonicalUserId; } + public void setS3CanonicalUserId(String s3CanonicalUserId) { this.s3CanonicalUserId = s3CanonicalUserId; } + + public String getCallerReference() { return callerReference; } + public void setCallerReference(String callerReference) { this.callerReference = callerReference; } + + public String getComment() { return comment; } + public void setComment(String comment) { this.comment = comment; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/ContinuousDeploymentPolicy.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/ContinuousDeploymentPolicy.java new file mode 100644 index 0000000000..f8351d69e0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/ContinuousDeploymentPolicy.java @@ -0,0 +1,36 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; +import java.util.List; + +public class ContinuousDeploymentPolicy { + + private String id; + private Instant lastModifiedTime; + private String etag; + private boolean enabled; + private List stagingDistributionDnsNames; + private String trafficConfig; + + public ContinuousDeploymentPolicy() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public boolean isEnabled() { return enabled; } + public void setEnabled(boolean enabled) { this.enabled = enabled; } + + public List getStagingDistributionDnsNames() { return stagingDistributionDnsNames; } + public void setStagingDistributionDnsNames(List stagingDistributionDnsNames) { + this.stagingDistributionDnsNames = stagingDistributionDnsNames; + } + + public String getTrafficConfig() { return trafficConfig; } + public void setTrafficConfig(String trafficConfig) { this.trafficConfig = trafficConfig; } +} \ No newline at end of file diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DefaultCacheBehavior.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DefaultCacheBehavior.java new file mode 100644 index 0000000000..9cb9528107 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DefaultCacheBehavior.java @@ -0,0 +1,70 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.util.List; +import java.util.Map; + +public class DefaultCacheBehavior { + + private String targetOriginId; + private String viewerProtocolPolicy = "redirect-to-https"; + private List allowedMethods; + private List cachedMethods; + private String cachePolicyId; + private String originRequestPolicyId; + private String responseHeadersPolicyId; + private String fieldLevelEncryptionId; + private String realtimeLogConfigArn; + private List> functionAssociations; + private List> lambdaFunctionAssociations; + private boolean compress; + private long defaultTTL; + private long minTTL; + private long maxTTL; + + public DefaultCacheBehavior() {} + + public String getTargetOriginId() { return targetOriginId; } + public void setTargetOriginId(String targetOriginId) { this.targetOriginId = targetOriginId; } + + public String getViewerProtocolPolicy() { return viewerProtocolPolicy; } + public void setViewerProtocolPolicy(String viewerProtocolPolicy) { this.viewerProtocolPolicy = viewerProtocolPolicy; } + + public List getAllowedMethods() { return allowedMethods; } + public void setAllowedMethods(List allowedMethods) { this.allowedMethods = allowedMethods; } + + public List getCachedMethods() { return cachedMethods; } + public void setCachedMethods(List cachedMethods) { this.cachedMethods = cachedMethods; } + + public String getCachePolicyId() { return cachePolicyId; } + public void setCachePolicyId(String cachePolicyId) { this.cachePolicyId = cachePolicyId; } + + public String getOriginRequestPolicyId() { return originRequestPolicyId; } + public void setOriginRequestPolicyId(String originRequestPolicyId) { this.originRequestPolicyId = originRequestPolicyId; } + + public String getResponseHeadersPolicyId() { return responseHeadersPolicyId; } + public void setResponseHeadersPolicyId(String responseHeadersPolicyId) { this.responseHeadersPolicyId = responseHeadersPolicyId; } + + public String getFieldLevelEncryptionId() { return fieldLevelEncryptionId; } + public void setFieldLevelEncryptionId(String fieldLevelEncryptionId) { this.fieldLevelEncryptionId = fieldLevelEncryptionId; } + + public String getRealtimeLogConfigArn() { return realtimeLogConfigArn; } + public void setRealtimeLogConfigArn(String realtimeLogConfigArn) { this.realtimeLogConfigArn = realtimeLogConfigArn; } + + public List> getFunctionAssociations() { return functionAssociations; } + public void setFunctionAssociations(List> functionAssociations) { this.functionAssociations = functionAssociations; } + + public List> getLambdaFunctionAssociations() { return lambdaFunctionAssociations; } + public void setLambdaFunctionAssociations(List> lambdaFunctionAssociations) { this.lambdaFunctionAssociations = lambdaFunctionAssociations; } + + public boolean isCompress() { return compress; } + public void setCompress(boolean compress) { this.compress = compress; } + + public long getDefaultTTL() { return defaultTTL; } + public void setDefaultTTL(long defaultTTL) { this.defaultTTL = defaultTTL; } + + public long getMinTTL() { return minTTL; } + public void setMinTTL(long minTTL) { this.minTTL = minTTL; } + + public long getMaxTTL() { return maxTTL; } + public void setMaxTTL(long maxTTL) { this.maxTTL = maxTTL; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Distribution.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Distribution.java new file mode 100644 index 0000000000..eb51ad3db5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Distribution.java @@ -0,0 +1,42 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; +import java.util.Map; + +public class Distribution { + + private String id; + private String arn; + private String domainName; + private String status; + private Instant lastModifiedTime; + private String etag; + private Map tags; + private DistributionConfig config; + + public Distribution() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + + public String getDomainName() { return domainName; } + public void setDomainName(String domainName) { this.domainName = domainName; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } + + public DistributionConfig getConfig() { return config; } + public void setConfig(DistributionConfig config) { this.config = config; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DistributionConfig.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DistributionConfig.java new file mode 100644 index 0000000000..9225c11dbc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DistributionConfig.java @@ -0,0 +1,82 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.util.List; +import java.util.Map; + +public class DistributionConfig { + + private String callerReference; + private boolean enabled; + private String comment; + private String defaultRootObject; + private List origins; + private DefaultCacheBehavior defaultCacheBehavior; + private List cacheBehaviors; + private List aliases; + private Map viewerCertificate; + private Map geoRestriction; + private String httpVersion = "http2"; + private String priceClass = "PriceClass_All"; + private boolean isIPV6Enabled = true; + private String webAclId; + private List> customErrorResponses; + private Map logging; + private String continuousDeploymentPolicyId; + private boolean staging; + + public DistributionConfig() {} + + public String getCallerReference() { return callerReference; } + public void setCallerReference(String callerReference) { this.callerReference = callerReference; } + + public boolean isEnabled() { return enabled; } + public void setEnabled(boolean enabled) { this.enabled = enabled; } + + public String getComment() { return comment; } + public void setComment(String comment) { this.comment = comment; } + + public String getDefaultRootObject() { return defaultRootObject; } + public void setDefaultRootObject(String defaultRootObject) { this.defaultRootObject = defaultRootObject; } + + public List getOrigins() { return origins; } + public void setOrigins(List origins) { this.origins = origins; } + + public DefaultCacheBehavior getDefaultCacheBehavior() { return defaultCacheBehavior; } + public void setDefaultCacheBehavior(DefaultCacheBehavior defaultCacheBehavior) { this.defaultCacheBehavior = defaultCacheBehavior; } + + public List getCacheBehaviors() { return cacheBehaviors; } + public void setCacheBehaviors(List cacheBehaviors) { this.cacheBehaviors = cacheBehaviors; } + + public List getAliases() { return aliases; } + public void setAliases(List aliases) { this.aliases = aliases; } + + public Map getViewerCertificate() { return viewerCertificate; } + public void setViewerCertificate(Map viewerCertificate) { this.viewerCertificate = viewerCertificate; } + + public Map getGeoRestriction() { return geoRestriction; } + public void setGeoRestriction(Map geoRestriction) { this.geoRestriction = geoRestriction; } + + public String getHttpVersion() { return httpVersion; } + public void setHttpVersion(String httpVersion) { this.httpVersion = httpVersion; } + + public String getPriceClass() { return priceClass; } + public void setPriceClass(String priceClass) { this.priceClass = priceClass; } + + public boolean isIPV6Enabled() { return isIPV6Enabled; } + public void setIPV6Enabled(boolean IPV6Enabled) { this.isIPV6Enabled = IPV6Enabled; } + + public String getWebAclId() { return webAclId; } + public void setWebAclId(String webAclId) { this.webAclId = webAclId; } + + public List> getCustomErrorResponses() { return customErrorResponses; } + public void setCustomErrorResponses(List> customErrorResponses) { this.customErrorResponses = customErrorResponses; } + + public Map getLogging() { return logging; } + public void setLogging(Map logging) { this.logging = logging; } + + public String getContinuousDeploymentPolicyId() { return continuousDeploymentPolicyId; } + public void setContinuousDeploymentPolicyId(String continuousDeploymentPolicyId) { this.continuousDeploymentPolicyId = continuousDeploymentPolicyId; } + + public boolean isStaging() { return staging; } + public void setStaging(boolean staging) { this.staging = staging; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/FieldLevelEncryptionConfig.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/FieldLevelEncryptionConfig.java new file mode 100644 index 0000000000..cce56b46dc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/FieldLevelEncryptionConfig.java @@ -0,0 +1,29 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; + +public class FieldLevelEncryptionConfig { + + private String id; + private Instant lastModifiedTime; + private String etag; + private String callerReference; + private String comment; + + public FieldLevelEncryptionConfig() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public String getCallerReference() { return callerReference; } + public void setCallerReference(String callerReference) { this.callerReference = callerReference; } + + public String getComment() { return comment; } + public void setComment(String comment) { this.comment = comment; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/FieldLevelEncryptionProfile.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/FieldLevelEncryptionProfile.java new file mode 100644 index 0000000000..c96b7dfc16 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/FieldLevelEncryptionProfile.java @@ -0,0 +1,33 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; + +public class FieldLevelEncryptionProfile { + + private String id; + private Instant lastModifiedTime; + private String etag; + private String name; + private String callerReference; + private String comment; + + public FieldLevelEncryptionProfile() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getCallerReference() { return callerReference; } + public void setCallerReference(String callerReference) { this.callerReference = callerReference; } + + public String getComment() { return comment; } + public void setComment(String comment) { this.comment = comment; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Invalidation.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Invalidation.java new file mode 100644 index 0000000000..59e03fc2b6 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Invalidation.java @@ -0,0 +1,30 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; +import java.util.List; + +public class Invalidation { + + private String id; + private String status; + private Instant createTime; + private List paths; + private String callerReference; + + public Invalidation() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public Instant getCreateTime() { return createTime; } + public void setCreateTime(Instant createTime) { this.createTime = createTime; } + + public List getPaths() { return paths; } + public void setPaths(List paths) { this.paths = paths; } + + public String getCallerReference() { return callerReference; } + public void setCallerReference(String callerReference) { this.callerReference = callerReference; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/KeyGroup.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/KeyGroup.java new file mode 100644 index 0000000000..a14c386947 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/KeyGroup.java @@ -0,0 +1,34 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; +import java.util.List; + +public class KeyGroup { + + private String id; + private Instant lastModifiedTime; + private String etag; + private String name; + private String comment; + private List items; + + public KeyGroup() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getComment() { return comment; } + public void setComment(String comment) { this.comment = comment; } + + public List getItems() { return items; } + public void setItems(List items) { this.items = items; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/MonitoringSubscription.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/MonitoringSubscription.java new file mode 100644 index 0000000000..1ac840e1c4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/MonitoringSubscription.java @@ -0,0 +1,17 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +public class MonitoringSubscription { + + private String distributionId; + private String realtimeMetricsSubscriptionStatus; + + public MonitoringSubscription() {} + + public String getDistributionId() { return distributionId; } + public void setDistributionId(String distributionId) { this.distributionId = distributionId; } + + public String getRealtimeMetricsSubscriptionStatus() { return realtimeMetricsSubscriptionStatus; } + public void setRealtimeMetricsSubscriptionStatus(String realtimeMetricsSubscriptionStatus) { + this.realtimeMetricsSubscriptionStatus = realtimeMetricsSubscriptionStatus; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Origin.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Origin.java new file mode 100644 index 0000000000..945d16f1c1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/Origin.java @@ -0,0 +1,46 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.util.List; +import java.util.Map; + +public class Origin { + + private String id; + private String domainName; + private String originPath; + private String originAccessControlId; + private Map s3OriginConfig; + private Map customOriginConfig; + private int connectionAttempts = 3; + private int connectionTimeout = 10; + private List> customHeaders; + + public Origin() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getDomainName() { return domainName; } + public void setDomainName(String domainName) { this.domainName = domainName; } + + public String getOriginPath() { return originPath; } + public void setOriginPath(String originPath) { this.originPath = originPath; } + + public String getOriginAccessControlId() { return originAccessControlId; } + public void setOriginAccessControlId(String originAccessControlId) { this.originAccessControlId = originAccessControlId; } + + public Map getS3OriginConfig() { return s3OriginConfig; } + public void setS3OriginConfig(Map s3OriginConfig) { this.s3OriginConfig = s3OriginConfig; } + + public Map getCustomOriginConfig() { return customOriginConfig; } + public void setCustomOriginConfig(Map customOriginConfig) { this.customOriginConfig = customOriginConfig; } + + public int getConnectionAttempts() { return connectionAttempts; } + public void setConnectionAttempts(int connectionAttempts) { this.connectionAttempts = connectionAttempts; } + + public int getConnectionTimeout() { return connectionTimeout; } + public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } + + public List> getCustomHeaders() { return customHeaders; } + public void setCustomHeaders(List> customHeaders) { this.customHeaders = customHeaders; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/OriginAccessControl.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/OriginAccessControl.java new file mode 100644 index 0000000000..c39d0c25cf --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/OriginAccessControl.java @@ -0,0 +1,41 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; + +public class OriginAccessControl { + + private String id; + private String name; + private String description; + private String etag; + private Instant lastModifiedTime; + private String signingBehavior; + private String signingProtocol; + private String originAccessControlOriginType; + + public OriginAccessControl() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + + public String getSigningBehavior() { return signingBehavior; } + public void setSigningBehavior(String signingBehavior) { this.signingBehavior = signingBehavior; } + + public String getSigningProtocol() { return signingProtocol; } + public void setSigningProtocol(String signingProtocol) { this.signingProtocol = signingProtocol; } + + public String getOriginAccessControlOriginType() { return originAccessControlOriginType; } + public void setOriginAccessControlOriginType(String originAccessControlOriginType) { this.originAccessControlOriginType = originAccessControlOriginType; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/OriginRequestPolicy.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/OriginRequestPolicy.java new file mode 100644 index 0000000000..4c35f08177 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/OriginRequestPolicy.java @@ -0,0 +1,34 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; +import java.util.Map; + +public class OriginRequestPolicy { + + private String id; + private String name; + private String comment; + private String etag; + private Instant lastModifiedTime; + private Map config; + + public OriginRequestPolicy() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getComment() { return comment; } + public void setComment(String comment) { this.comment = comment; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + + public Map getConfig() { return config; } + public void setConfig(Map config) { this.config = config; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/PublicKey.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/PublicKey.java new file mode 100644 index 0000000000..c2737dab22 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/PublicKey.java @@ -0,0 +1,37 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; + +public class PublicKey { + + private String id; + private Instant createdTime; + private String etag; + private String callerReference; + private String name; + private String encodedKey; + private String comment; + + public PublicKey() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public Instant getCreatedTime() { return createdTime; } + public void setCreatedTime(Instant createdTime) { this.createdTime = createdTime; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public String getCallerReference() { return callerReference; } + public void setCallerReference(String callerReference) { this.callerReference = callerReference; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getEncodedKey() { return encodedKey; } + public void setEncodedKey(String encodedKey) { this.encodedKey = encodedKey; } + + public String getComment() { return comment; } + public void setComment(String comment) { this.comment = comment; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/RealtimeLogConfig.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/RealtimeLogConfig.java new file mode 100644 index 0000000000..cfb6433214 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/RealtimeLogConfig.java @@ -0,0 +1,30 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.util.List; +import java.util.Map; + +public class RealtimeLogConfig { + + private String arn; + private String name; + private long samplingRate; + private List fields; + private List> endPoints; + + public RealtimeLogConfig() {} + + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public long getSamplingRate() { return samplingRate; } + public void setSamplingRate(long samplingRate) { this.samplingRate = samplingRate; } + + public List getFields() { return fields; } + public void setFields(List fields) { this.fields = fields; } + + public List> getEndPoints() { return endPoints; } + public void setEndPoints(List> endPoints) { this.endPoints = endPoints; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/ResponseHeadersPolicy.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/ResponseHeadersPolicy.java new file mode 100644 index 0000000000..fa31e298e1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/ResponseHeadersPolicy.java @@ -0,0 +1,34 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; +import java.util.Map; + +public class ResponseHeadersPolicy { + + private String id; + private String name; + private String comment; + private String etag; + private Instant lastModifiedTime; + private Map config; + + public ResponseHeadersPolicy() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getComment() { return comment; } + public void setComment(String comment) { this.comment = comment; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + + public Map getConfig() { return config; } + public void setConfig(Map config) { this.config = config; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/StreamingDistribution.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/StreamingDistribution.java new file mode 100644 index 0000000000..dc91e68a92 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/StreamingDistribution.java @@ -0,0 +1,64 @@ +package io.github.hectorvent.floci.services.cloudfront.model; + +import java.time.Instant; +import java.util.List; + +public class StreamingDistribution { + + private String id; + private String arn; + private String status; + private Instant lastModifiedTime; + private String domainName; + private String etag; + private String callerReference; + private boolean enabled; + private String comment; + private String s3Bucket; + private String s3OriginAccessIdentity; + private List aliases; + private String priceClass; + + public StreamingDistribution() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + + public String getDomainName() { return domainName; } + public void setDomainName(String domainName) { this.domainName = domainName; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } + + public String getCallerReference() { return callerReference; } + public void setCallerReference(String callerReference) { this.callerReference = callerReference; } + + public boolean isEnabled() { return enabled; } + public void setEnabled(boolean enabled) { this.enabled = enabled; } + + public String getComment() { return comment; } + public void setComment(String comment) { this.comment = comment; } + + public String getS3Bucket() { return s3Bucket; } + public void setS3Bucket(String s3Bucket) { this.s3Bucket = s3Bucket; } + + public String getS3OriginAccessIdentity() { return s3OriginAccessIdentity; } + public void setS3OriginAccessIdentity(String s3OriginAccessIdentity) { + this.s3OriginAccessIdentity = s3OriginAccessIdentity; + } + + public List getAliases() { return aliases; } + public void setAliases(List aliases) { this.aliases = aliases; } + + public String getPriceClass() { return priceClass; } + public void setPriceClass(String priceClass) { this.priceClass = priceClass; } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 873efbcfb5..6b1f018cd2 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -43,6 +43,7 @@ quarkus: - --initialize-at-run-time=io.github.hectorvent.floci.services.ses.SesService - --initialize-at-run-time=io.github.hectorvent.floci.services.route53.Route53Service - --initialize-at-run-time=io.github.hectorvent.floci.services.kms.KmsService + - --initialize-at-run-time=io.github.hectorvent.floci.services.cloudfront.CloudFrontService floci: @@ -83,6 +84,7 @@ floci: rds: # Override storage mode for RDS (memory = no Docker volumes; hybrid/persistent = named volume per instance) # mode: memory + cloudfront: dns: # Extra hostname suffixes resolved to Floci's container IP by the embedded DNS server. @@ -284,3 +286,5 @@ floci: bcm-data-exports: enabled: true emit-mode: synchronous + cloudfront: + enabled: true diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index b6beb79bf7..57fbda68ab 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -34,6 +34,7 @@ floci: flush-interval-ms: 60000 opensearch: flush-interval-ms: 60000 + cloudfront: auth: validate-signatures: false @@ -192,3 +193,5 @@ floci: bcm-data-exports: enabled: true emit-mode: off + cloudfront: + enabled: true