Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#14648] feat(server): Add Domain REST APIs (#14649)

Jerry Shao95a1caa81f1b
diff --git a/common/src/main/java/org/apache/gravitino/dto/domain/DomainBackingTagDTO.java b/common/src/main/java/org/apache/gravitino/dto/domain/DomainBackingTagDTO.java
new file mode 100644
index 0000000000..1345032a9d
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/domain/DomainBackingTagDTO.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.domain;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import javax.annotation.Nullable;
+import lombok.Getter;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.tag.TagValue;
+
+/** A backing tag name and optional exact assignment value. */
+@Getter
+public class DomainBackingTagDTO {
+
+ @JsonProperty("name")
+ private final String name;
+
+ @JsonProperty("value")
+ @Nullable
+ private final String value;
+
+ /** Creates a backing tag for Jackson deserialization. */
+ public DomainBackingTagDTO() {
+ this(null, null);
+ }
+
+ /**
+ * Creates a backing tag representation.
+ *
+ * @param name The tag name.
+ * @param value The optional value; null matches any assignment.
+ */
+ public DomainBackingTagDTO(String name, @Nullable String value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ /** Validates the name and optional value. */
+ public void validate() {
+ Preconditions.checkArgument(StringUtils.isNotBlank(name), "backingTag.name must not be blank");
+ Preconditions.checkArgument(
+ value == null || StringUtils.isNotBlank(value), "backingTag.value must not be blank");
+ Preconditions.checkArgument(
+ value == null || value.length() <= 256, "backingTag.value must not exceed 256 characters");
+ }
+
+ /**
+ * @return The corresponding tag value.
+ */
+ public TagValue tagValue() {
+ validate();
+ return value == null ? TagValue.noValue(name) : TagValue.of(name, value);
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/domain/DomainDTO.java b/common/src/main/java/org/apache/gravitino/dto/domain/DomainDTO.java
new file mode 100644
index 0000000000..1ec7503a70
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/domain/DomainDTO.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.domain;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.collect.ImmutableMap;
+import java.util.Arrays;
+import java.util.Map;
+import javax.annotation.Nullable;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.domain.DomainRelation;
+import org.apache.gravitino.dto.AuditDTO;
+import org.apache.gravitino.tag.TagValue;
+
+/**
+ * A domain snapshot; relations are present only in a metadata object's domain lookup. Jackson uses
+ * the private no-argument constructor to deserialize a snapshot.
+ */
+@Getter
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class DomainDTO {
+
+ @JsonProperty("name")
+ private String name;
+
+ @JsonProperty("comment")
+ @Nullable
+ private String comment;
+
+ @JsonProperty("properties")
+ private Map<String, String> properties;
+
+ @JsonProperty("status")
+ private Domain.Status status;
+
+ @JsonProperty("parent")
+ @Nullable
+ private String parent;
+
+ @JsonProperty("backingTag")
+ @Nullable
+ private DomainBackingTagDTO backingTag;
+
+ @JsonProperty("audit")
+ private AuditDTO audit;
+
+ @JsonProperty("relations")
+ @JsonInclude(JsonInclude.Include.NON_EMPTY)
+ private DomainRelationDTO[] relations = new DomainRelationDTO[0];
+
+ /**
+ * Creates a domain response snapshot.
+ *
+ * @param name The domain name.
+ * @param comment The optional comment.
+ * @param properties The properties.
+ * @param status The status.
+ * @param parent The optional parent name.
+ * @param backingTag The optional backing tag.
+ * @param audit The audit information.
+ * @param relations The object's relations to this domain.
+ */
+ public DomainDTO(
+ String name,
+ @Nullable String comment,
+ Map<String, String> properties,
+ Domain.Status status,
+ @Nullable String parent,
+ @Nullable TagValue backingTag,
+ AuditDTO audit,
+ DomainRelation[] relations) {
+ this.name = name;
+ this.comment = comment;
+ this.properties = ImmutableMap.copyOf(properties);
+ this.status = status;
+ this.parent = parent;
+ this.backingTag =
+ backingTag == null
+ ? null
+ : new DomainBackingTagDTO(backingTag.name(), backingTag.value().orElse(null));
+ this.audit = audit;
+ this.relations =
+ Arrays.stream(relations).map(DomainRelationDTO::from).toArray(DomainRelationDTO[]::new);
+ }
+
+ /**
+ * @return All applicable relations.
+ */
+ public DomainRelationDTO[] getRelations() {
+ return relations == null ? new DomainRelationDTO[0] : relations.clone();
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/domain/DomainMemberDTO.java b/common/src/main/java/org/apache/gravitino/dto/domain/DomainMemberDTO.java
new file mode 100644
index 0000000000..fc03802f63
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/domain/DomainMemberDTO.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.domain;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.Arrays;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import org.apache.gravitino.domain.DomainMember;
+import org.apache.gravitino.dto.tag.MetadataObjectDTO;
+import org.apache.gravitino.dto.util.DTOConverters;
+
+/** A recorded leaf member and all its relations to the queried domain. */
+@Getter
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class DomainMemberDTO {
+
+ @JsonProperty("object")
+ private MetadataObjectDTO object;
+
+ @JsonProperty("relations")
+ private DomainRelationDTO[] relations;
+
+ /**
+ * Copies a member into its wire representation.
+ *
+ * @param member The member.
+ * @return The member DTO.
+ */
+ public static DomainMemberDTO from(DomainMember member) {
+ DomainMemberDTO dto = new DomainMemberDTO();
+ dto.object = DTOConverters.toDTO(member.object());
+ dto.relations =
+ Arrays.stream(member.relations())
+ .map(DomainRelationDTO::from)
+ .toArray(DomainRelationDTO[]::new);
+ return dto;
+ }
+
+ /**
+ * @return All applicable relations.
+ */
+ public DomainRelationDTO[] getRelations() {
+ return relations == null ? new DomainRelationDTO[0] : relations.clone();
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/domain/DomainRelationDTO.java b/common/src/main/java/org/apache/gravitino/dto/domain/DomainRelationDTO.java
new file mode 100644
index 0000000000..2f13a0dfa2
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/domain/DomainRelationDTO.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.domain;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import javax.annotation.Nullable;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import org.apache.gravitino.domain.DomainRelation;
+import org.apache.gravitino.dto.tag.MetadataObjectDTO;
+import org.apache.gravitino.dto.util.DTOConverters;
+
+/** Describes one relation between a metadata object and a domain. */
+@Getter
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class DomainRelationDTO {
+
+ @JsonProperty("relation")
+ private DomainRelation.Type relation;
+
+ @JsonProperty("source")
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ @Nullable
+ private MetadataObjectDTO source;
+
+ /**
+ * Copies a relation into its wire representation.
+ *
+ * @param relation The relation.
+ * @return The relation DTO.
+ */
+ public static DomainRelationDTO from(DomainRelation relation) {
+ DomainRelationDTO dto = new DomainRelationDTO();
+ dto.relation = relation.type();
+ dto.source = relation.source().map(DTOConverters::toDTO).orElse(null);
+ return dto;
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/DomainBackingTagSetRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/DomainBackingTagSetRequest.java
new file mode 100644
index 0000000000..05f4a9ccf9
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/DomainBackingTagSetRequest.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonSetter;
+import com.google.common.base.Preconditions;
+import javax.annotation.Nullable;
+import lombok.AccessLevel;
+import lombok.Getter;
+import org.apache.gravitino.dto.domain.DomainBackingTagDTO;
+import org.apache.gravitino.rest.RESTRequest;
+
+/** A request to set a domain's backingTag. */
+@Getter
+public class DomainBackingTagSetRequest implements RESTRequest {
+
+ @JsonProperty("backingTag")
+ @Nullable
+ @JsonInclude(JsonInclude.Include.ALWAYS)
+ private DomainBackingTagDTO backingTag;
+
+ @JsonIgnore
+ @Getter(AccessLevel.NONE)
+ private boolean backingTagSpecified;
+
+ /** Creates a request for Jackson deserialization. */
+ public DomainBackingTagSetRequest() {
+ // Jackson invokes the setter only when the backingTag field is present.
+ }
+
+ /**
+ * Creates a set request.
+ *
+ * @param backingTag The new backingTag. Null removes the backing tag.
+ */
+ public DomainBackingTagSetRequest(@Nullable DomainBackingTagDTO backingTag) {
+ setBackingTag(backingTag);
+ }
+
+ /**
+ * Records an explicitly supplied binding, including null to remove it.
+ *
+ * @param backingTag The binding, or null to remove the current binding.
+ */
+ @JsonSetter("backingTag")
+ public void setBackingTag(@Nullable DomainBackingTagDTO backingTag) {
+ this.backingTag = backingTag;
+ this.backingTagSpecified = true;
+ }
+
+ /** Validates the requested value. */
+ @Override
+ public void validate() {
+ Preconditions.checkArgument(
+ backingTagSpecified,
+ "backingTag must be explicitly provided; use null to remove the binding");
+ if (backingTag != null) {
+ backingTag.validate();
+ }
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/DomainCreateRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/DomainCreateRequest.java
new file mode 100644
index 0000000000..d9acd58af6
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/DomainCreateRequest.java
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import java.util.Map;
+import javax.annotation.Nullable;
+import lombok.Getter;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.dto.domain.DomainBackingTagDTO;
+import org.apache.gravitino.rest.RESTRequest;
+
+/** Creates a draft domain, optionally under a parent, with an explicit backing tag. */
+@Getter
+public class DomainCreateRequest implements RESTRequest {
+
+ @JsonProperty("name")
+ private final String name;
+
+ @JsonProperty("comment")
+ @Nullable
+ private final String comment;
+
+ @JsonProperty("properties")
+ @Nullable
+ private final Map<String, String> properties;
+
+ @JsonProperty("parent")
+ @Nullable
+ private final String parent;
+
+ @JsonProperty("backingTag")
+ private final BackingTag backingTag;
+
+ /** Creates a request for Jackson deserialization. */
+ public DomainCreateRequest() {
+ this(null, null, null, null, null);
+ }
+
+ /**
+ * Creates a domain creation request.
+ *
+ * @param name The new domain name.
+ * @param comment The optional comment.
+ * @param properties The optional properties.
+ * @param parent The optional parent domain name.
+ * @param backingTag The explicit backing tag.
+ */
+ public DomainCreateRequest(
+ String name,
+ @Nullable String comment,
+ @Nullable Map<String, String> properties,
+ @Nullable String parent,
+ BackingTag backingTag) {
+ this.name = name;
+ this.comment = comment;
+ this.properties = properties;
+ this.parent = parent;
+ this.backingTag = backingTag;
+ }
+
+ /** Validates the domain name, optional parent, and explicit backing tag. */
+ @Override
+ public void validate() {
+ Preconditions.checkArgument(StringUtils.isNotBlank(name), "name must not be blank");
+ Preconditions.checkArgument(
+ parent == null || StringUtils.isNotBlank(parent), "parent must not be blank");
+ Preconditions.checkArgument(backingTag != null, "backingTag must not be null");
+ if (properties != null) {
+ properties.forEach(
+ (key, value) ->
+ Preconditions.checkArgument(
+ key != null && value != null, "properties must not contain null keys or values"));
+ }
+ backingTag.validate();
+ }
+
+ /** A tag to create without a value, or an existing tag to bind. */
+ @Getter
+ public static class BackingTag extends DomainBackingTagDTO {
+
+ @JsonProperty("create")
+ private final boolean create;
+
+ /** Creates a backing tag request for Jackson deserialization. */
+ public BackingTag() {
+ this(null, null, false);
+ }
+
+ /**
+ * Creates a backing tag request.
+ *
+ * @param name The tag name.
+ * @param value The optional existing assignment value.
+ * @param create Whether to create a new tag without values.
+ */
+ public BackingTag(String name, @Nullable String value, boolean create) {
+ super(name, value);
+ this.create = create;
+ }
+
+ /** Validates the tag and prohibits creating a tag with a value. */
+ @Override
+ public void validate() {
+ super.validate();
+ Preconditions.checkArgument(
+ !create || getValue() == null, "A new backing tag cannot have a value");
+ }
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/DomainParentSetRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/DomainParentSetRequest.java
new file mode 100644
index 0000000000..e5cdbf1846
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/DomainParentSetRequest.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import lombok.Getter;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.rest.RESTRequest;
+
+/** A request to set a domain's parent. */
+@Getter
+public class DomainParentSetRequest implements RESTRequest {
+
+ @JsonProperty("parent")
+ private final String parent;
+
+ /** Creates a request for Jackson deserialization. */
+ public DomainParentSetRequest() {
+ this(null);
+ }
+
+ /**
+ * Creates a set request.
+ *
+ * @param parent The new parent.
+ */
+ public DomainParentSetRequest(String parent) {
+ this.parent = parent;
+ }
+
+ /** Validates the requested value. */
+ @Override
+ public void validate() {
+ Preconditions.checkArgument(StringUtils.isNotBlank(parent), "parent must not be blank");
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/DomainSetRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/DomainSetRequest.java
new file mode 100644
index 0000000000..83dc61ee4d
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/DomainSetRequest.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import lombok.Getter;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.rest.RESTRequest;
+
+/** A request to set a domain's status. */
+@Getter
+public class DomainSetRequest implements RESTRequest {
+
+ @JsonProperty("status")
+ private final Domain.Status status;
+
+ /** Creates a request for Jackson deserialization. */
+ public DomainSetRequest() {
+ this(null);
+ }
+
+ /**
+ * Creates a set request.
+ *
+ * @param status The new status.
+ */
+ public DomainSetRequest(Domain.Status status) {
+ this.status = status;
+ }
+
+ /** Validates the requested value. */
+ @Override
+ public void validate() {
+ Preconditions.checkArgument(status != null, "status must not be null");
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/DomainUpdateRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/DomainUpdateRequest.java
new file mode 100644
index 0000000000..389be68066
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/DomainUpdateRequest.java
@@ -0,0 +1,203 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import com.google.common.base.Preconditions;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.domain.DomainChange;
+import org.apache.gravitino.rest.RESTRequest;
+
+/** Represents a request to update a domain. */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
+@JsonSubTypes({
+ @JsonSubTypes.Type(value = DomainUpdateRequest.RenameDomainRequest.class, name = "rename"),
+ @JsonSubTypes.Type(
+ value = DomainUpdateRequest.UpdateDomainCommentRequest.class,
+ name = "updateComment"),
+ @JsonSubTypes.Type(
+ value = DomainUpdateRequest.SetDomainPropertyRequest.class,
+ name = "setProperty"),
+ @JsonSubTypes.Type(
+ value = DomainUpdateRequest.RemoveDomainPropertyRequest.class,
+ name = "removeProperty")
+})
+public interface DomainUpdateRequest extends RESTRequest {
+
+ /**
+ * Returns the domain change.
+ *
+ * @return the domain change.
+ */
+ DomainChange domainChange();
+
+ /** The domain update request for renaming a domain. */
+ @EqualsAndHashCode
+ @ToString
+ class RenameDomainRequest implements DomainUpdateRequest {
+
+ @Getter
+ @JsonProperty("newName")
+ private final String newName;
+
+ /**
+ * Creates a new RenameDomainRequest.
+ *
+ * @param newName The new name of the domain.
+ */
+ public RenameDomainRequest(String newName) {
+ this.newName = newName;
+ }
+
+ /** This is the constructor that is used by Jackson deserializer */
+ public RenameDomainRequest() {
+ this.newName = null;
+ }
+
+ @Override
+ public DomainChange domainChange() {
+ return DomainChange.rename(newName);
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(StringUtils.isNotBlank(newName), "\"newName\" must not be blank");
+ }
+ }
+
+ /** The domain update request for updating a domain comment. */
+ @EqualsAndHashCode
+ @ToString
+ class UpdateDomainCommentRequest implements DomainUpdateRequest {
+
+ @Getter
+ @JsonProperty("newComment")
+ @Nullable
+ private final String newComment;
+
+ /**
+ * Creates a new UpdateDomainCommentRequest.
+ *
+ * @param newComment The new comment of the domain.
+ */
+ public UpdateDomainCommentRequest(@Nullable String newComment) {
+ this.newComment = newComment;
+ }
+
+ /** This is the constructor that is used by Jackson deserializer */
+ public UpdateDomainCommentRequest() {
+ this.newComment = null;
+ }
+
+ @Override
+ public DomainChange domainChange() {
+ return DomainChange.updateComment(newComment);
+ }
+
+ /** Validates the fields of the request. Always pass. */
+ @Override
+ public void validate() throws IllegalArgumentException {}
+ }
+
+ /** The domain update request for setting a domain property. */
+ @EqualsAndHashCode
+ @ToString
+ class SetDomainPropertyRequest implements DomainUpdateRequest {
+
+ @Getter
+ @JsonProperty("property")
+ private final String property;
+
+ @Getter
+ @JsonProperty("value")
+ private final String value;
+
+ /**
+ * Creates a new SetDomainPropertyRequest.
+ *
+ * @param property The property to set.
+ * @param value The value of the property.
+ */
+ public SetDomainPropertyRequest(String property, String value) {
+ this.property = property;
+ this.value = value;
+ }
+
+ /** This is the constructor that is used by Jackson deserializer */
+ public SetDomainPropertyRequest() {
+ this.property = null;
+ this.value = null;
+ }
+
+ @Override
+ public DomainChange domainChange() {
+ return DomainChange.setProperty(property, value);
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(property), "\"property\" must not be blank");
+ Preconditions.checkArgument(value != null, "\"value\" must not be null");
+ }
+ }
+
+ /** The domain update request for removing a domain property. */
+ @EqualsAndHashCode
+ @ToString
+ class RemoveDomainPropertyRequest implements DomainUpdateRequest {
+
+ @Getter
+ @JsonProperty("property")
+ private final String property;
+
+ /**
+ * Creates a new RemoveDomainPropertyRequest.
+ *
+ * @param property The property to remove.
+ */
+ public RemoveDomainPropertyRequest(String property) {
+ this.property = property;
+ }
+
+ /** This is the constructor that is used by Jackson deserializer */
+ public RemoveDomainPropertyRequest() {
+ this.property = null;
+ }
+
+ @Override
+ public DomainChange domainChange() {
+ return DomainChange.removeProperty(property);
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(property), "\"property\" must not be blank");
+ }
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/DomainUpdatesRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/DomainUpdatesRequest.java
new file mode 100644
index 0000000000..5f19a8a87b
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/DomainUpdatesRequest.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import java.util.List;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.gravitino.rest.RESTRequest;
+
+/** Represents a request to update a domain. */
+@Getter
+@EqualsAndHashCode
+@ToString
+public class DomainUpdatesRequest implements RESTRequest {
+
+ @JsonProperty("updates")
+ private final List<DomainUpdateRequest> updates;
+
+ /**
+ * Creates a new DomainUpdatesRequest.
+ *
+ * @param updates The updates to apply to the domain.
+ */
+ public DomainUpdatesRequest(List<DomainUpdateRequest> updates) {
+ this.updates = updates;
+ }
+
+ /** This is the constructor that is used by Jackson deserializer */
+ public DomainUpdatesRequest() {
+ this(null);
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(updates != null, "updates must not be null");
+ updates.forEach(
+ update -> {
+ Preconditions.checkArgument(update != null, "updates must not contain null");
+ update.validate();
+ });
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/responses/DomainListResponse.java b/common/src/main/java/org/apache/gravitino/dto/responses/DomainListResponse.java
new file mode 100644
index 0000000000..299d1e86eb
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/responses/DomainListResponse.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.responses;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import java.util.Arrays;
+import org.apache.gravitino.dto.domain.DomainDTO;
+
+/** A response containing a list of domains. */
+public class DomainListResponse extends BaseResponse {
+
+ @JsonProperty("domains")
+ private final DomainDTO[] domains;
+
+ /** Creates an empty response for Jackson deserialization. */
+ public DomainListResponse() {
+ super();
+ domains = null;
+ }
+
+ /**
+ * Creates a successful list response.
+ *
+ * @param domains The returned domains.
+ */
+ public DomainListResponse(DomainDTO[] domains) {
+ super(0);
+ this.domains = domains.clone();
+ }
+
+ /**
+ * @return The returned domains.
+ */
+ public DomainDTO[] getDomains() {
+ return domains.clone();
+ }
+
+ /** Validates that the list and its entries are present. */
+ @Override
+ public void validate() {
+ super.validate();
+ Preconditions.checkArgument(domains != null, "domains must not be null");
+ Arrays.stream(domains)
+ .forEach(
+ item -> Preconditions.checkArgument(item != null, "domains must not contain null"));
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/responses/DomainMemberListResponse.java b/common/src/main/java/org/apache/gravitino/dto/responses/DomainMemberListResponse.java
new file mode 100644
index 0000000000..03ee342716
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/responses/DomainMemberListResponse.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.responses;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import java.util.Arrays;
+import org.apache.gravitino.dto.domain.DomainMemberDTO;
+
+/** A response containing a list of members. */
+public class DomainMemberListResponse extends BaseResponse {
+
+ @JsonProperty("members")
+ private final DomainMemberDTO[] members;
+
+ /** Creates an empty response for Jackson deserialization. */
+ public DomainMemberListResponse() {
+ super();
+ members = null;
+ }
+
+ /**
+ * Creates a successful list response.
+ *
+ * @param members The returned members.
+ */
+ public DomainMemberListResponse(DomainMemberDTO[] members) {
+ super(0);
+ this.members = members.clone();
+ }
+
+ /**
+ * @return The returned members.
+ */
+ public DomainMemberDTO[] getMembers() {
+ return members.clone();
+ }
+
+ /** Validates that the list and its entries are present. */
+ @Override
+ public void validate() {
+ super.validate();
+ Preconditions.checkArgument(members != null, "members must not be null");
+ Arrays.stream(members)
+ .forEach(
+ item -> Preconditions.checkArgument(item != null, "members must not contain null"));
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/responses/DomainResponse.java b/common/src/main/java/org/apache/gravitino/dto/responses/DomainResponse.java
new file mode 100644
index 0000000000..55647c2809
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/responses/DomainResponse.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.responses;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import lombok.Getter;
+import org.apache.gravitino.dto.domain.DomainDTO;
+
+/** A successful response containing a domain snapshot. */
+@Getter
+public class DomainResponse extends BaseResponse {
+
+ @JsonProperty("domain")
+ private final DomainDTO domain;
+
+ /** Creates a response for Jackson deserialization. */
+ public DomainResponse() {
+ super();
+ domain = null;
+ }
+
+ /**
+ * Creates a successful domain response.
+ *
+ * @param domain The domain snapshot.
+ */
+ public DomainResponse(DomainDTO domain) {
+ super(0);
+ this.domain = domain;
+ }
+
+ /** Validates that the domain is present. */
+ @Override
+ public void validate() {
+ super.validate();
+ Preconditions.checkArgument(domain != null, "domain must not be null");
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/tag/MetadataObjectDTO.java b/common/src/main/java/org/apache/gravitino/dto/tag/MetadataObjectDTO.java
index 39a87f608c..4b2559f233 100644
--- a/common/src/main/java/org/apache/gravitino/dto/tag/MetadataObjectDTO.java
+++ b/common/src/main/java/org/apache/gravitino/dto/tag/MetadataObjectDTO.java
@@ -18,7 +18,9 @@
*/
package org.apache.gravitino.dto.tag;
+import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
+import javax.annotation.Nullable;
import lombok.EqualsAndHashCode;
import org.apache.gravitino.MetadataObject;
@@ -35,6 +37,14 @@ public class MetadataObjectDTO implements MetadataObject {
private MetadataObjectDTO() {}
+ @JsonCreator
+ private MetadataObjectDTO(
+ @JsonProperty("fullName") @Nullable String fullName, @JsonProperty("type") Type type) {
+ // Read both fields together: DOMAIN names may contain dots, regardless of JSON field order.
+ this.type = type;
+ setFullName(fullName);
+ }
+
@Override
public String parent() {
return parent;
@@ -61,11 +71,16 @@ public class MetadataObjectDTO implements MetadataObject {
/**
* Sets the full name of the metadata object. Only used by Jackson deserializer.
*
- * @param fullName The full name of the metadata object.
+ * @param fullName The full name of the metadata object, or null when absent.
*/
@JsonProperty("fullName")
- public void setFullName(String fullName) {
- int index = fullName.lastIndexOf(".");
+ public void setFullName(@Nullable String fullName) {
+ if (fullName == null) {
+ parent = null;
+ name = null;
+ return;
+ }
+ int index = type == Type.DOMAIN ? -1 : fullName.lastIndexOf(".");
if (index == -1) {
parent = null;
name = fullName;
diff --git a/common/src/test/java/org/apache/gravitino/dto/domain/TestDomainDTO.java b/common/src/test/java/org/apache/gravitino/dto/domain/TestDomainDTO.java
new file mode 100644
index 0000000000..04e7d4cb60
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/domain/TestDomainDTO.java
@@ -0,0 +1,259 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.dto.domain;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.domain.DomainMember;
+import org.apache.gravitino.domain.DomainRelation;
+import org.apache.gravitino.dto.AuditDTO;
+import org.apache.gravitino.dto.responses.DomainListResponse;
+import org.apache.gravitino.dto.responses.DomainMemberListResponse;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.tag.TagValue;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestDomainDTO {
+
+ private static final String DOMAIN_JSON =
+ "{\"name\":\"Finance\",\"comment\":\"Financial data\",\"properties\":{\"key\":\"value\"},"
+ + "\"status\":\"published\",\"parent\":\"Parent\",\"backingTag\":{\"name\":\"department\",\"value\":\"finance\"},"
+ + "\"audit\":{\"creator\":\"user\",\"createTime\":\"2026-10-01T00:00:00Z\",\"lastModifier\":null,\"lastModifiedTime\":null},"
+ + "\"relations\":[{\"relation\":\"direct\"},{\"relation\":\"inherited\",\"source\":{\"type\":\"schema\",\"fullName\":\"cat.schema\"}},"
+ + "{\"relation\":\"via_subdomain\",\"source\":{\"type\":\"domain\",\"fullName\":\"Finance.US\"}}]}";
+
+ private static final String MEMBER_JSON =
+ "{\"object\":{\"fullName\":\"cat.schema.table\",\"type\":\"table\"},"
+ + "\"relations\":[{\"relation\":\"direct\"},{\"relation\":\"inherited\",\"source\":{\"type\":\"catalog\",\"fullName\":\"cat\"}},"
+ + "{\"relation\":\"via_subdomain\",\"source\":{\"type\":\"domain\",\"fullName\":\"Finance.US\"}}]}";
+
+ private static final AuditDTO AUDIT =
+ AuditDTO.builder()
+ .withCreator("user")
+ .withCreateTime(Instant.parse("2026-10-01T00:00:00Z"))
+ .build();
+
+ @Test
+ public void testDomainOptionalFieldsAndRelations() throws IOException {
+ DomainRelation[] relations = {DomainRelation.direct(), DomainRelation.viaSubdomain("Tax/US")};
+ Map<String, String> properties = new HashMap<>();
+ properties.put("key", "value");
+ DomainDTO dto =
+ new DomainDTO(
+ "Finance", null, properties, Domain.Status.PUBLISHED, null, null, AUDIT, relations);
+ properties.clear();
+ relations[0] = null;
+ DomainRelationDTO[] copy = dto.getRelations();
+ copy[0] = null;
+ DomainListResponse response = new DomainListResponse(new DomainDTO[] {dto});
+ String json = JsonUtils.objectMapper().writeValueAsString(response);
+ JsonNode tree = JsonUtils.objectMapper().readTree(json);
+ JsonNode domain = tree.get("domains").get(0);
+ Assertions.assertTrue(domain.get("backingTag").isNull());
+ Assertions.assertTrue(domain.get("parent").isNull());
+ Assertions.assertFalse(domain.get("relations").get(0).has("source"));
+ DomainListResponse decoded = JsonUtils.objectMapper().readValue(json, DomainListResponse.class);
+ decoded.validate();
+ DomainDTO result = decoded.getDomains()[0];
+ Assertions.assertEquals("value", result.getProperties().get("key"));
+ Assertions.assertEquals(Domain.Status.PUBLISHED, result.getStatus());
+ Assertions.assertEquals(DomainRelation.Type.DIRECT, result.getRelations()[0].getRelation());
+ Assertions.assertEquals("Tax/US", result.getRelations()[1].getSource().fullName());
+ Assertions.assertEquals(
+ MetadataObject.Type.DOMAIN, result.getRelations()[1].getSource().type());
+ }
+
+ @Test
+ public void testBackingTagValues() throws IOException {
+ for (TagValue tag :
+ new TagValue[] {TagValue.noValue("department"), TagValue.of("department", "finance")}) {
+ DomainDTO dto =
+ new DomainDTO(
+ "Finance",
+ "comment",
+ Collections.emptyMap(),
+ Domain.Status.DRAFT,
+ "Parent",
+ tag,
+ AUDIT,
+ new DomainRelation[] {DomainRelation.direct()});
+ DomainDTO decoded =
+ JsonUtils.objectMapper()
+ .readValue(JsonUtils.objectMapper().writeValueAsString(dto), DomainDTO.class);
+ Assertions.assertEquals(tag.name(), decoded.getBackingTag().getName());
+ Assertions.assertEquals(tag.value().orElse(null), decoded.getBackingTag().getValue());
+ Assertions.assertEquals("Parent", decoded.getParent());
+ Assertions.assertEquals("comment", decoded.getComment());
+ Assertions.assertEquals("user", decoded.getAudit().creator());
+ }
+ }
+
+ @Test
+ public void testMemberRoundTrip() throws IOException {
+ DomainMember member =
+ new DomainMember() {
+ @Override
+ public MetadataObject object() {
+ return MetadataObjects.parse("cat.schema.table", MetadataObject.Type.TABLE);
+ }
+
+ @Override
+ public DomainRelation[] relations() {
+ return new DomainRelation[] {
+ DomainRelation.inherited(
+ MetadataObjects.parse("cat.schema", MetadataObject.Type.SCHEMA))
+ };
+ }
+ };
+ DomainMemberDTO dto = DomainMemberDTO.from(member);
+ DomainMemberDTO[] members = {dto};
+ DomainMemberListResponse response = new DomainMemberListResponse(members);
+ members[0] = null;
+ response.getMembers()[0] = null;
+ dto.getRelations()[0] = null;
+ DomainMemberListResponse decoded =
+ JsonUtils.objectMapper()
+ .readValue(
+ JsonUtils.objectMapper().writeValueAsString(response),
+ DomainMemberListResponse.class);
+ decoded.validate();
+ Assertions.assertEquals("cat.schema.table", decoded.getMembers()[0].getObject().fullName());
+ Assertions.assertEquals(MetadataObject.Type.TABLE, decoded.getMembers()[0].getObject().type());
+ Assertions.assertEquals(
+ DomainRelation.Type.INHERITED, decoded.getMembers()[0].getRelations()[0].getRelation());
+ Assertions.assertEquals(
+ "cat.schema", decoded.getMembers()[0].getRelations()[0].getSource().fullName());
+ }
+
+ @Test
+ public void testDottedSubdomainRelation() throws IOException {
+ DomainRelation relation = DomainRelation.viaSubdomain("Finance.US");
+ DomainRelationDTO decoded =
+ JsonUtils.objectMapper()
+ .readValue(
+ JsonUtils.objectMapper().writeValueAsString(DomainRelationDTO.from(relation)),
+ DomainRelationDTO.class);
+ Assertions.assertEquals(DomainRelation.Type.VIA_SUBDOMAIN, decoded.getRelation());
+ Assertions.assertEquals(MetadataObject.Type.DOMAIN, decoded.getSource().type());
+ Assertions.assertNull(decoded.getSource().parent());
+ Assertions.assertEquals("Finance.US", decoded.getSource().name());
+ Assertions.assertEquals(relation, DomainRelation.viaSubdomain(decoded.getSource().name()));
+ }
+
+ @Test
+ public void testDomainJsonSerialization() throws IOException {
+ DomainDTO dto =
+ new DomainDTO(
+ "Finance",
+ "Financial data",
+ Collections.singletonMap("key", "value"),
+ Domain.Status.PUBLISHED,
+ "Parent",
+ TagValue.of("department", "finance"),
+ AUDIT,
+ new DomainRelation[] {
+ DomainRelation.direct(),
+ DomainRelation.inherited(
+ MetadataObjects.parse("cat.schema", MetadataObject.Type.SCHEMA)),
+ DomainRelation.viaSubdomain("Finance.US")
+ });
+ assertJsonEquals(DOMAIN_JSON, dto);
+ }
+
+ @Test
+ public void testDomainJsonDeserialization() throws IOException {
+ DomainDTO dto = JsonUtils.objectMapper().readValue(DOMAIN_JSON, DomainDTO.class);
+ Assertions.assertEquals("Finance", dto.getName());
+ Assertions.assertEquals("Financial data", dto.getComment());
+ Assertions.assertEquals(Collections.singletonMap("key", "value"), dto.getProperties());
+ Assertions.assertEquals(Domain.Status.PUBLISHED, dto.getStatus());
+ Assertions.assertEquals("Parent", dto.getParent());
+ Assertions.assertEquals("department", dto.getBackingTag().getName());
+ Assertions.assertEquals("finance", dto.getBackingTag().getValue());
+ Assertions.assertEquals(AUDIT, dto.getAudit());
+ Assertions.assertEquals(3, dto.getRelations().length);
+ Assertions.assertEquals(DomainRelation.Type.DIRECT, dto.getRelations()[0].getRelation());
+ Assertions.assertNull(dto.getRelations()[0].getSource());
+ Assertions.assertEquals("cat.schema", dto.getRelations()[1].getSource().fullName());
+ Assertions.assertEquals("Finance.US", dto.getRelations()[2].getSource().name());
+ Assertions.assertNull(dto.getRelations()[2].getSource().parent());
+ assertJsonEquals(DOMAIN_JSON, dto);
+ }
+
+ @Test
+ public void testMemberJsonDeserializationAndSerialization() throws IOException {
+ DomainMemberDTO member = JsonUtils.objectMapper().readValue(MEMBER_JSON, DomainMemberDTO.class);
+ Assertions.assertEquals("cat.schema.table", member.getObject().fullName());
+ Assertions.assertEquals(MetadataObject.Type.TABLE, member.getObject().type());
+ Assertions.assertEquals(3, member.getRelations().length);
+ Assertions.assertEquals(DomainRelation.Type.DIRECT, member.getRelations()[0].getRelation());
+ Assertions.assertEquals(DomainRelation.Type.INHERITED, member.getRelations()[1].getRelation());
+ Assertions.assertEquals("cat", member.getRelations()[1].getSource().name());
+ Assertions.assertEquals(
+ DomainRelation.Type.VIA_SUBDOMAIN, member.getRelations()[2].getRelation());
+ Assertions.assertEquals("Finance.US", member.getRelations()[2].getSource().name());
+ assertJsonEquals(MEMBER_JSON, member);
+ }
+
+ @Test
+ public void testBackingTagJson() throws IOException {
+ for (String json :
+ new String[] {
+ "{\"name\":\"department\",\"value\":\"finance\"}",
+ "{\"name\":\"department\",\"value\":null}"
+ }) {
+ DomainBackingTagDTO tag = JsonUtils.objectMapper().readValue(json, DomainBackingTagDTO.class);
+ Assertions.assertEquals("department", tag.getName());
+ Assertions.assertEquals(
+ JsonUtils.objectMapper().readTree(json).get("value").isNull() ? null : "finance",
+ tag.getValue());
+ tag.validate();
+ assertJsonEquals(json, tag);
+ }
+ DomainBackingTagDTO noValue =
+ JsonUtils.objectMapper().readValue("{\"name\":\"department\"}", DomainBackingTagDTO.class);
+ Assertions.assertNull(noValue.getValue());
+ assertJsonEquals("{\"name\":\"department\",\"value\":null}", noValue);
+ }
+
+ @Test
+ public void testNullOrMissingRelations() throws IOException {
+ for (String json : new String[] {"{}", "{\"relations\":null}", "{\"relations\":[]}"}) {
+ DomainDTO domain = JsonUtils.objectMapper().readValue(json, DomainDTO.class);
+ DomainMemberDTO member = JsonUtils.objectMapper().readValue(json, DomainMemberDTO.class);
+ Assertions.assertEquals(0, domain.getRelations().length);
+ Assertions.assertEquals(0, member.getRelations().length);
+ }
+ }
+
+ private static void assertJsonEquals(String expected, Object value) throws IOException {
+ Assertions.assertEquals(
+ JsonUtils.objectMapper().readTree(expected),
+ JsonUtils.objectMapper().readTree(JsonUtils.objectMapper().writeValueAsString(value)));
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/requests/TestDomainBackingTagSetRequest.java b/common/src/test/java/org/apache/gravitino/dto/requests/TestDomainBackingTagSetRequest.java
new file mode 100644
index 0000000000..2ecbf0d443
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/requests/TestDomainBackingTagSetRequest.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import java.io.IOException;
+import org.apache.gravitino.dto.domain.DomainBackingTagDTO;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.tag.TagValue;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestDomainBackingTagSetRequest {
+
+ @Test
+ public void testMissingFieldIsRejected() throws IOException {
+ for (String json : new String[] {"{}", "{\"backing_tag\":null}"}) {
+ DomainBackingTagSetRequest request =
+ JsonUtils.objectMapper()
+ .copy()
+ .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .readValue(json, DomainBackingTagSetRequest.class);
+ Assertions.assertThrows(IllegalArgumentException.class, request::validate);
+ }
+ }
+
+ @Test
+ public void testExplicitNullRemovesBinding() throws IOException {
+ DomainBackingTagSetRequest request =
+ JsonUtils.objectMapper()
+ .readValue("{\"backingTag\":null}", DomainBackingTagSetRequest.class);
+ request.validate();
+ Assertions.assertNull(request.getBackingTag());
+ DomainBackingTagSetRequest removal = new DomainBackingTagSetRequest(null);
+ removal.validate();
+ // Production mappers omit null fields globally, but an explicit removal must remain explicit.
+ String json =
+ JsonUtils.objectMapper()
+ .copy()
+ .setSerializationInclusion(JsonInclude.Include.NON_NULL)
+ .writeValueAsString(removal);
+ Assertions.assertEquals(
+ JsonUtils.objectMapper().readTree("{\"backingTag\":null}"),
+ JsonUtils.objectMapper().readTree(json));
+ JsonUtils.objectMapper().readValue(json, DomainBackingTagSetRequest.class).validate();
+ }
+
+ @Test
+ public void testSetBinding() throws IOException {
+ DomainBackingTagSetRequest request =
+ JsonUtils.objectMapper()
+ .readValue(
+ "{\"backingTag\":{\"name\":\"department\",\"value\":\"finance\"}}",
+ DomainBackingTagSetRequest.class);
+ request.validate();
+ Assertions.assertEquals(
+ TagValue.of("department", "finance"), request.getBackingTag().tagValue());
+ DomainBackingTagSetRequest direct =
+ new DomainBackingTagSetRequest(new DomainBackingTagDTO("department", null));
+ direct.validate();
+ Assertions.assertEquals(TagValue.noValue("department"), direct.getBackingTag().tagValue());
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/requests/TestDomainRequests.java b/common/src/test/java/org/apache/gravitino/dto/requests/TestDomainRequests.java
new file mode 100644
index 0000000000..1145f060b1
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/requests/TestDomainRequests.java
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.domain.DomainChange;
+import org.apache.gravitino.dto.domain.DomainBackingTagDTO;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.rest.RESTRequest;
+import org.apache.gravitino.tag.TagValue;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestDomainRequests {
+
+ @Test
+ public void testCreateRoundTrip() throws IOException {
+ for (boolean create : new boolean[] {false, true}) {
+ DomainCreateRequest request =
+ new DomainCreateRequest(
+ "Finance",
+ "comment",
+ Collections.singletonMap("k", "v"),
+ "Parent",
+ new DomainCreateRequest.BackingTag("tag", create ? null : "value", create));
+ DomainCreateRequest result = roundTrip(request, DomainCreateRequest.class);
+ result.validate();
+ Assertions.assertEquals("Finance", result.getName());
+ Assertions.assertEquals("comment", result.getComment());
+ Assertions.assertEquals(Collections.singletonMap("k", "v"), result.getProperties());
+ Assertions.assertEquals("Parent", result.getParent());
+ Assertions.assertEquals(create, result.getBackingTag().isCreate());
+ Assertions.assertEquals(
+ create ? TagValue.noValue("tag") : TagValue.of("tag", "value"),
+ result.getBackingTag().tagValue());
+ }
+ DomainCreateRequest existing =
+ JsonUtils.objectMapper()
+ .readValue(
+ "{\"name\":\"Finance\",\"backingTag\":{\"name\":\"tag\"}}",
+ DomainCreateRequest.class);
+ existing.validate();
+ Assertions.assertFalse(existing.getBackingTag().isCreate());
+ Assertions.assertEquals(TagValue.noValue("tag"), existing.getBackingTag().tagValue());
+ }
+
+ @Test
+ public void testBackingTagValidation() {
+ for (DomainBackingTagDTO invalid :
+ new DomainBackingTagDTO[] {
+ new DomainBackingTagDTO(), new DomainBackingTagDTO(" ", null),
+ new DomainBackingTagDTO("tag", " "),
+ new DomainBackingTagDTO("tag", String.join("", Collections.nCopies(257, "x"))),
+ new DomainCreateRequest.BackingTag("tag", "value", true)
+ }) {
+ Assertions.assertThrows(IllegalArgumentException.class, invalid::validate);
+ Assertions.assertThrows(IllegalArgumentException.class, invalid::tagValue);
+ }
+ new DomainBackingTagDTO("tag", String.join("", Collections.nCopies(256, "x"))).validate();
+ Assertions.assertEquals(
+ TagValue.noValue("tag"), new DomainBackingTagDTO("tag", null).tagValue());
+ }
+
+ @Test
+ public void testSetRequests() throws IOException {
+ DomainSetRequest status =
+ roundTrip(new DomainSetRequest(Domain.Status.PUBLISHED), DomainSetRequest.class);
+ status.validate();
+ Assertions.assertEquals(Domain.Status.PUBLISHED, status.getStatus());
+ DomainParentSetRequest parent =
+ roundTrip(new DomainParentSetRequest("Parent/US"), DomainParentSetRequest.class);
+ parent.validate();
+ Assertions.assertEquals("Parent/US", parent.getParent());
+ for (DomainBackingTagDTO tag :
+ new DomainBackingTagDTO[] {null, new DomainBackingTagDTO("tag", "value")}) {
+ DomainBackingTagSetRequest request =
+ roundTrip(new DomainBackingTagSetRequest(tag), DomainBackingTagSetRequest.class);
+ request.validate();
+ if (tag == null) {
+ Assertions.assertNull(request.getBackingTag());
+ } else {
+ Assertions.assertEquals(TagValue.of("tag", "value"), request.getBackingTag().tagValue());
+ }
+ }
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> new DomainBackingTagSetRequest().validate());
+ }
+
+ @Test
+ public void testRequestValidation() {
+ for (RESTRequest invalid :
+ new RESTRequest[] {
+ new DomainCreateRequest(),
+ new DomainCreateRequest(
+ " ", null, null, null, new DomainCreateRequest.BackingTag("tag", null, false)),
+ new DomainCreateRequest(
+ "Finance", null, null, " ", new DomainCreateRequest.BackingTag("tag", null, false)),
+ new DomainCreateRequest(
+ "Finance",
+ null,
+ Collections.singletonMap("key", null),
+ null,
+ new DomainCreateRequest.BackingTag("tag", null, false)),
+ new DomainSetRequest(),
+ new DomainParentSetRequest(),
+ new DomainParentSetRequest(" "),
+ new DomainBackingTagSetRequest(new DomainBackingTagDTO()),
+ new DomainUpdatesRequest(),
+ new DomainUpdatesRequest(Arrays.asList((DomainUpdateRequest) null)),
+ new DomainUpdateRequest.RenameDomainRequest(),
+ new DomainUpdateRequest.RenameDomainRequest(" "),
+ new DomainUpdateRequest.SetDomainPropertyRequest(),
+ new DomainUpdateRequest.SetDomainPropertyRequest("key", null),
+ new DomainUpdateRequest.RemoveDomainPropertyRequest(),
+ new DomainUpdateRequest.RemoveDomainPropertyRequest(" ")
+ }) {
+ Assertions.assertThrows(IllegalArgumentException.class, invalid::validate);
+ }
+ new DomainUpdatesRequest(Collections.emptyList()).validate();
+ DomainUpdateRequest.SetDomainPropertyRequest emptyValue =
+ new DomainUpdateRequest.SetDomainPropertyRequest("key", "");
+ emptyValue.validate();
+ Assertions.assertEquals(DomainChange.setProperty("key", ""), emptyValue.domainChange());
+ DomainUpdateRequest.UpdateDomainCommentRequest clearComment =
+ new DomainUpdateRequest.UpdateDomainCommentRequest();
+ clearComment.validate();
+ Assertions.assertEquals(DomainChange.updateComment(null), clearComment.domainChange());
+ Assertions.assertEquals(
+ DomainChange.rename("New"),
+ new DomainUpdateRequest.RenameDomainRequest("New").domainChange());
+ Assertions.assertEquals(
+ DomainChange.removeProperty("key"),
+ new DomainUpdateRequest.RemoveDomainPropertyRequest("key").domainChange());
+ }
+
+ private static <T> T roundTrip(T value, Class<T> type) throws IOException {
+ return JsonUtils.objectMapper()
+ .readValue(JsonUtils.objectMapper().writeValueAsString(value), type);
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/requests/TestDomainUpdatesRequest.java b/common/src/test/java/org/apache/gravitino/dto/requests/TestDomainUpdatesRequest.java
new file mode 100644
index 0000000000..d9caad2a23
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/requests/TestDomainUpdatesRequest.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.collect.ImmutableList;
+import java.util.List;
+import org.apache.gravitino.json.JsonUtils;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestDomainUpdatesRequest {
+
+ @Test
+ public void testRenameDomainRequestSerDe() throws JsonProcessingException {
+ DomainUpdateRequest.RenameDomainRequest request =
+ new DomainUpdateRequest.RenameDomainRequest("domain_test_new");
+ String serJson = JsonUtils.objectMapper().writeValueAsString(request);
+ DomainUpdateRequest.RenameDomainRequest deserRequest =
+ JsonUtils.objectMapper().readValue(serJson, DomainUpdateRequest.RenameDomainRequest.class);
+ Assertions.assertEquals(request, deserRequest);
+ Assertions.assertEquals("domain_test_new", deserRequest.getNewName());
+ }
+
+ @Test
+ public void testUpdateDomainCommentRequestSerDe() throws JsonProcessingException {
+ DomainUpdateRequest.UpdateDomainCommentRequest request =
+ new DomainUpdateRequest.UpdateDomainCommentRequest("domain comment new");
+ String serJson = JsonUtils.objectMapper().writeValueAsString(request);
+ DomainUpdateRequest.UpdateDomainCommentRequest deserRequest =
+ JsonUtils.objectMapper()
+ .readValue(serJson, DomainUpdateRequest.UpdateDomainCommentRequest.class);
+ Assertions.assertEquals(request, deserRequest);
+ Assertions.assertEquals("domain comment new", deserRequest.getNewComment());
+ }
+
+ @Test
+ public void testSetDomainPropertyRequestSerDe() throws JsonProcessingException {
+ DomainUpdateRequest.SetDomainPropertyRequest request =
+ new DomainUpdateRequest.SetDomainPropertyRequest("key", "value");
+ String serJson = JsonUtils.objectMapper().writeValueAsString(request);
+ DomainUpdateRequest.SetDomainPropertyRequest deserRequest =
+ JsonUtils.objectMapper()
+ .readValue(serJson, DomainUpdateRequest.SetDomainPropertyRequest.class);
+ Assertions.assertEquals(request, deserRequest);
+ Assertions.assertEquals("key", deserRequest.getProperty());
+ Assertions.assertEquals("value", deserRequest.getValue());
+ }
+
+ @Test
+ public void testRemoveDomainPropertyRequestSerDe() throws JsonProcessingException {
+ DomainUpdateRequest.RemoveDomainPropertyRequest request =
+ new DomainUpdateRequest.RemoveDomainPropertyRequest("key");
+ String serJson = JsonUtils.objectMapper().writeValueAsString(request);
+ DomainUpdateRequest.RemoveDomainPropertyRequest deserRequest =
+ JsonUtils.objectMapper()
+ .readValue(serJson, DomainUpdateRequest.RemoveDomainPropertyRequest.class);
+ Assertions.assertEquals(request, deserRequest);
+ Assertions.assertEquals("key", deserRequest.getProperty());
+ }
+
+ @Test
+ public void testDomainUpdatesRequestSerDe() throws JsonProcessingException {
+ DomainUpdateRequest request = new DomainUpdateRequest.RenameDomainRequest("domain_test_new");
+ DomainUpdateRequest request1 =
+ new DomainUpdateRequest.UpdateDomainCommentRequest("domain comment new");
+ DomainUpdateRequest request2 = new DomainUpdateRequest.SetDomainPropertyRequest("key", "value");
+ DomainUpdateRequest request3 = new DomainUpdateRequest.RemoveDomainPropertyRequest("key");
+
+ List<DomainUpdateRequest> updates = ImmutableList.of(request, request1, request2, request3);
+ DomainUpdatesRequest domainUpdatesRequest = new DomainUpdatesRequest(updates);
+ String serJson = JsonUtils.objectMapper().writeValueAsString(domainUpdatesRequest);
+ DomainUpdatesRequest deserRequest =
+ JsonUtils.objectMapper().readValue(serJson, DomainUpdatesRequest.class);
+ Assertions.assertEquals(domainUpdatesRequest, deserRequest);
+ Assertions.assertEquals(updates, deserRequest.getUpdates());
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/responses/TestDomainListResponse.java b/common/src/test/java/org/apache/gravitino/dto/responses/TestDomainListResponse.java
new file mode 100644
index 0000000000..cb868b36d8
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/responses/TestDomainListResponse.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.dto.responses;
+
+import java.io.IOException;
+import org.apache.gravitino.dto.domain.DomainDTO;
+import org.apache.gravitino.json.JsonUtils;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestDomainListResponse {
+
+ private static final String ITEM_JSON =
+ "{\"name\":\"Finance\",\"comment\":null,\"properties\":{},\"status\":\"draft\","
+ + "\"parent\":null,\"backingTag\":null,\"audit\":{\"creator\":\"user\","
+ + "\"createTime\":\"2026-10-01T00:00:00Z\",\"lastModifier\":null,\"lastModifiedTime\":null}}";
+
+ @Test
+ public void testJsonSerialization() throws IOException {
+ DomainDTO item = JsonUtils.objectMapper().readValue(ITEM_JSON, DomainDTO.class);
+ DomainListResponse response = new DomainListResponse(new DomainDTO[] {item});
+ response.validate();
+ Assertions.assertEquals(0, response.getCode());
+ assertJsonEquals("{\"code\":0,\"domains\":[" + ITEM_JSON + "]}", response);
+ }
+
+ @Test
+ public void testJsonDeserialization() throws IOException {
+ String json = "{\"code\":0,\"domains\":[" + ITEM_JSON + "]}";
+ DomainListResponse response =
+ JsonUtils.objectMapper().readValue(json, DomainListResponse.class);
+ response.validate();
+ Assertions.assertEquals(0, response.getCode());
+ Assertions.assertEquals(1, response.getDomains().length);
+ Assertions.assertEquals("Finance", response.getDomains()[0].getName());
+ Assertions.assertEquals("user", response.getDomains()[0].getAudit().creator());
+ assertJsonEquals(json, response);
+ }
+
+ @Test
+ public void testEmptyList() throws IOException {
+ String json = "{\"code\":0,\"domains\":[]}";
+ DomainListResponse response =
+ JsonUtils.objectMapper().readValue(json, DomainListResponse.class);
+ response.validate();
+ Assertions.assertEquals(0, response.getDomains().length);
+ assertJsonEquals(json, response);
+ assertJsonEquals(json, new DomainListResponse(new DomainDTO[0]));
+ }
+
+ @Test
+ public void testValidate() throws IOException {
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> new DomainListResponse().validate());
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> new DomainListResponse(new DomainDTO[] {null}).validate());
+ for (String json :
+ new String[] {
+ "{\"code\":0}",
+ "{\"code\":0,\"domains\":null}",
+ "{\"code\":0,\"domains\":[null]}",
+ "{\"code\":-1,\"domains\":[]}"
+ }) {
+ DomainListResponse response =
+ JsonUtils.objectMapper().readValue(json, DomainListResponse.class);
+ Assertions.assertThrows(IllegalArgumentException.class, response::validate);
+ }
+ }
+
+ @Test
+ public void testDefensiveCopies() throws IOException {
+ DomainDTO item = JsonUtils.objectMapper().readValue(ITEM_JSON, DomainDTO.class);
+ DomainDTO[] input = {item};
+ DomainListResponse response = new DomainListResponse(input);
+ input[0] = null;
+ Assertions.assertSame(item, response.getDomains()[0]);
+ response.getDomains()[0] = null;
+ Assertions.assertSame(item, response.getDomains()[0]);
+ response.validate();
+ }
+
+ private static void assertJsonEquals(String expected, Object response) throws IOException {
+ Assertions.assertEquals(
+ JsonUtils.objectMapper().readTree(expected),
+ JsonUtils.objectMapper().readTree(JsonUtils.objectMapper().writeValueAsString(response)));
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/responses/TestDomainMemberListResponse.java b/common/src/test/java/org/apache/gravitino/dto/responses/TestDomainMemberListResponse.java
new file mode 100644
index 0000000000..f295d78aee
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/responses/TestDomainMemberListResponse.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.dto.responses;
+
+import java.io.IOException;
+import org.apache.gravitino.dto.domain.DomainMemberDTO;
+import org.apache.gravitino.json.JsonUtils;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestDomainMemberListResponse {
+
+ private static final String ITEM_JSON =
+ "{\"object\":{\"type\":\"table\",\"fullName\":\"cat.schema.table\"},"
+ + "\"relations\":[{\"relation\":\"via_subdomain\",\"source\":{\"type\":\"domain\",\"fullName\":\"Finance.US\"}}]}";
+
+ @Test
+ public void testJsonSerialization() throws IOException {
+ DomainMemberDTO item = JsonUtils.objectMapper().readValue(ITEM_JSON, DomainMemberDTO.class);
+ DomainMemberListResponse response = new DomainMemberListResponse(new DomainMemberDTO[] {item});
+ response.validate();
+ Assertions.assertEquals(0, response.getCode());
+ assertJsonEquals("{\"code\":0,\"members\":[" + ITEM_JSON + "]}", response);
+ }
+
+ @Test
+ public void testJsonDeserialization() throws IOException {
+ String json = "{\"code\":0,\"members\":[" + ITEM_JSON + "]}";
+ DomainMemberListResponse response =
+ JsonUtils.objectMapper().readValue(json, DomainMemberListResponse.class);
+ response.validate();
+ Assertions.assertEquals(0, response.getCode());
+ Assertions.assertEquals(1, response.getMembers().length);
+ Assertions.assertEquals("cat.schema.table", response.getMembers()[0].getObject().fullName());
+ Assertions.assertEquals(
+ "Finance.US", response.getMembers()[0].getRelations()[0].getSource().name());
+ Assertions.assertNull(response.getMembers()[0].getRelations()[0].getSource().parent());
+ assertJsonEquals(json, response);
+ }
+
+ @Test
+ public void testEmptyList() throws IOException {
+ String json = "{\"code\":0,\"members\":[]}";
+ DomainMemberListResponse response =
+ JsonUtils.objectMapper().readValue(json, DomainMemberListResponse.class);
+ response.validate();
+ Assertions.assertEquals(0, response.getMembers().length);
+ assertJsonEquals(json, response);
+ assertJsonEquals(json, new DomainMemberListResponse(new DomainMemberDTO[0]));
+ }
+
+ @Test
+ public void testValidate() throws IOException {
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> new DomainMemberListResponse().validate());
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> new DomainMemberListResponse(new DomainMemberDTO[] {null}).validate());
+ for (String json :
+ new String[] {
+ "{\"code\":0}",
+ "{\"code\":0,\"members\":null}",
+ "{\"code\":0,\"members\":[null]}",
+ "{\"code\":-1,\"members\":[]}"
+ }) {
+ DomainMemberListResponse response =
+ JsonUtils.objectMapper().readValue(json, DomainMemberListResponse.class);
+ Assertions.assertThrows(IllegalArgumentException.class, response::validate);
+ }
+ }
+
+ @Test
+ public void testDefensiveCopies() throws IOException {
+ DomainMemberDTO item = JsonUtils.objectMapper().readValue(ITEM_JSON, DomainMemberDTO.class);
+ DomainMemberDTO[] input = {item};
+ DomainMemberListResponse response = new DomainMemberListResponse(input);
+ input[0] = null;
+ Assertions.assertSame(item, response.getMembers()[0]);
+ response.getMembers()[0] = null;
+ Assertions.assertSame(item, response.getMembers()[0]);
+ response.validate();
+ }
+
+ private static void assertJsonEquals(String expected, Object response) throws IOException {
+ Assertions.assertEquals(
+ JsonUtils.objectMapper().readTree(expected),
+ JsonUtils.objectMapper().readTree(JsonUtils.objectMapper().writeValueAsString(response)));
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/responses/TestDomainResponse.java b/common/src/test/java/org/apache/gravitino/dto/responses/TestDomainResponse.java
new file mode 100644
index 0000000000..4f55de314b
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/responses/TestDomainResponse.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.dto.responses;
+
+import java.io.IOException;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.dto.domain.DomainDTO;
+import org.apache.gravitino.json.JsonUtils;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestDomainResponse {
+
+ private static final String DOMAIN_JSON =
+ "{\"name\":\"Finance\",\"comment\":null,\"properties\":{},\"status\":\"draft\","
+ + "\"parent\":null,\"backingTag\":null,\"audit\":{\"creator\":\"user\","
+ + "\"createTime\":\"2026-10-01T00:00:00Z\",\"lastModifier\":null,\"lastModifiedTime\":null}}";
+
+ @Test
+ public void testJsonSerialization() throws IOException {
+ DomainDTO domain = JsonUtils.objectMapper().readValue(DOMAIN_JSON, DomainDTO.class);
+ DomainResponse response = new DomainResponse(domain);
+ response.validate();
+ Assertions.assertEquals(0, response.getCode());
+ Assertions.assertSame(domain, response.getDomain());
+ assertJsonEquals("{\"code\":0,\"domain\":" + DOMAIN_JSON + "}", response);
+ }
+
+ @Test
+ public void testJsonDeserialization() throws IOException {
+ String json = "{\"code\":0,\"domain\":" + DOMAIN_JSON + "}";
+ DomainResponse response = JsonUtils.objectMapper().readValue(json, DomainResponse.class);
+ response.validate();
+ Assertions.assertEquals(0, response.getCode());
+ Assertions.assertEquals("Finance", response.getDomain().getName());
+ Assertions.assertEquals(Domain.Status.DRAFT, response.getDomain().getStatus());
+ Assertions.assertEquals("user", response.getDomain().getAudit().creator());
+ Assertions.assertEquals(0, response.getDomain().getRelations().length);
+ assertJsonEquals(json, response);
+ }
+
+ @Test
+ public void testValidate() throws IOException {
+ Assertions.assertThrows(IllegalArgumentException.class, () -> new DomainResponse().validate());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> new DomainResponse(null).validate());
+ for (String json :
+ new String[] {
+ "{\"code\":0}",
+ "{\"code\":0,\"domain\":null}",
+ "{\"code\":-1,\"domain\":" + DOMAIN_JSON + "}"
+ }) {
+ DomainResponse response = JsonUtils.objectMapper().readValue(json, DomainResponse.class);
+ Assertions.assertThrows(IllegalArgumentException.class, response::validate);
+ }
+ }
+
+ private static void assertJsonEquals(String expected, Object response) throws IOException {
+ Assertions.assertEquals(
+ JsonUtils.objectMapper().readTree(expected),
+ JsonUtils.objectMapper().readTree(JsonUtils.objectMapper().writeValueAsString(response)));
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/tag/TestMetadataObjectDTO.java b/common/src/test/java/org/apache/gravitino/dto/tag/TestMetadataObjectDTO.java
index 573890cf15..e61e99f90a 100644
--- a/common/src/test/java/org/apache/gravitino/dto/tag/TestMetadataObjectDTO.java
+++ b/common/src/test/java/org/apache/gravitino/dto/tag/TestMetadataObjectDTO.java
@@ -147,4 +147,43 @@ public class TestMetadataObjectDTO {
JsonUtils.objectMapper().readValue(serJson, MetadataObjectDTO.class);
Assertions.assertEquals(filesetDTO, deserFilesetDTO);
}
+
+ @Test
+ void testDottedDomainNameWithEitherFieldOrder() throws JsonProcessingException {
+ MetadataObjectDTO expected =
+ MetadataObjectDTO.builder()
+ .withName("Finance.US")
+ .withType(MetadataObject.Type.DOMAIN)
+ .build();
+ for (String json :
+ new String[] {
+ "{\"fullName\":\"Finance.US\",\"type\":\"domain\"}",
+ "{\"type\":\"domain\",\"fullName\":\"Finance.US\"}"
+ }) {
+ MetadataObjectDTO decoded = JsonUtils.objectMapper().readValue(json, MetadataObjectDTO.class);
+ Assertions.assertEquals(expected, decoded);
+ Assertions.assertEquals("Finance.US", decoded.name());
+ Assertions.assertEquals("Finance.US", decoded.fullName());
+ Assertions.assertNull(decoded.parent());
+ }
+ }
+
+ @Test
+ void testMissingOrNullFullName() throws JsonProcessingException {
+ for (MetadataObject.Type type : MetadataObject.Type.values()) {
+ for (String fields : new String[] {"", ",\"fullName\":null"}) {
+ MetadataObjectDTO dto =
+ JsonUtils.objectMapper()
+ .readValue(
+ "{\"type\":\"" + type.name() + "\"" + fields + "}", MetadataObjectDTO.class);
+ Assertions.assertEquals(type, dto.type());
+ Assertions.assertNull(dto.name());
+ Assertions.assertNull(dto.parent());
+ Assertions.assertNull(dto.fullName());
+ }
+ }
+ MetadataObjectDTO empty = JsonUtils.objectMapper().readValue("{}", MetadataObjectDTO.class);
+ Assertions.assertNull(empty.type());
+ Assertions.assertNull(empty.fullName());
+ }
}
diff --git a/docs/open-api/domains.yaml b/docs/open-api/domains.yaml
new file mode 100644
index 0000000000..6b02899e73
--- /dev/null
+++ b/docs/open-api/domains.yaml
@@ -0,0 +1,868 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+---
+
+paths:
+ # Domain authorization and DRAFT visibility are pending access-control integration.
+ /metalakes/{metalake}/domains:
+ parameters:
+ - $ref: "./openapi.yaml#/components/parameters/metalake"
+ get:
+ tags: [domain]
+ summary: List domains
+ operationId: listDomains
+ description: >-
+ List domains. Domain authorization and DRAFT visibility are pending access-control integration.
+ parameters:
+ - name: details
+ in: query
+ description: Return domain snapshots instead of names.
+ schema:
+ type: boolean
+ default: false
+ responses:
+ "200":
+ description: Successful domain operation.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ oneOf:
+ - $ref: "#/components/schemas/DomainNameListResponse"
+ - $ref: "#/components/schemas/DomainListResponse"
+ "404":
+ description: The metalake does not exist.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is not in use.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+ post:
+ tags: [domain]
+ summary: Create a domain
+ operationId: createDomain
+ description: >-
+ Creates a DRAFT domain, its optional parent edge and an optional new backing tag atomically. A failure leaves no new domain or tag behind. Domain authorization is pending access-control integration.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/DomainCreateRequest"
+ responses:
+ "200":
+ description: Successful domain operation.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "#/components/schemas/DomainResponse"
+ "400":
+ $ref: "#/components/responses/BadRequestResponse"
+ "404":
+ description: The metalake, requested parent domain, or existing backing tag to bind does not exist.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is disabled, the name or backing tag conflicts, the domain has subdomains, or a concurrent update could not complete.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+
+ /metalakes/{metalake}/domains/{domain}:
+ parameters:
+ - $ref: "./openapi.yaml#/components/parameters/metalake"
+ - $ref: "#/components/parameters/domain"
+ get:
+ tags: [domain]
+ summary: Get a domain
+ operationId: getDomain
+ description: >-
+ Get a domain. Domain authorization and DRAFT visibility are pending access-control integration.
+ responses:
+ "200":
+ description: Successful domain operation.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "#/components/schemas/DomainResponse"
+ "404":
+ description: The metalake or domain does not exist.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is not in use.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+ put:
+ tags: [domain]
+ summary: Alter a domain
+ operationId: alterDomain
+ description: >-
+ Alter a domain. Domain authorization and DRAFT visibility are pending access-control integration.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/DomainUpdatesRequest"
+ responses:
+ "200":
+ description: Successful domain operation.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "#/components/schemas/DomainResponse"
+ "400":
+ $ref: "#/components/responses/BadRequestResponse"
+ "404":
+ description: The metalake or domain does not exist.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is disabled, the name or backing tag conflicts, the domain has subdomains, or a concurrent update could not complete.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+ patch:
+ tags: [domain]
+ summary: Publish or unpublish a domain
+ operationId: setDomainStatus
+ description: >-
+ Sets the domain status and returns its snapshot. Publishing requires a published parent; unpublishing requires no published subdomains. Setting the current status is a no-op. Domain authorization is pending access-control integration.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/DomainSetRequest"
+ responses:
+ "200":
+ description: Successful domain operation.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "#/components/schemas/DomainResponse"
+ "400":
+ $ref: "#/components/responses/BadRequestResponse"
+ "404":
+ description: The metalake or domain does not exist.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is disabled, the name or backing tag conflicts, the domain has subdomains, or a concurrent update could not complete.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+ delete:
+ tags: [domain]
+ summary: Delete a domain
+ operationId: deleteDomain
+ description: >-
+ Deletes only the domain and its parent edge. The backing tag, its assignments and member
+ metadata objects remain unchanged; member objects do not prevent deletion. Deletion does
+ not cascade to subdomains: a domain with subdomains fails with HTTP 409,
+ NonEmptyDomainException and error code 1005. Returns dropped=false if the domain is absent.
+ Domain authorization is pending access-control integration.
+ responses:
+ "200":
+ description: Successful domain operation.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "#/components/schemas/DomainDropResponse"
+ "404":
+ description: The metalake does not exist. An absent domain returns HTTP 200 with dropped=false.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is disabled, the name or backing tag conflicts, the domain has subdomains, or a concurrent update could not complete.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+
+ /metalakes/{metalake}/domains/{domain}/parent:
+ parameters:
+ - $ref: "./openapi.yaml#/components/parameters/metalake"
+ - $ref: "#/components/parameters/domain"
+ put:
+ tags: [domain]
+ summary: Attach or move a domain
+ operationId: setDomainParent
+ description: >-
+ Attaches the child addressed by this path under a top-level parent, replacing its current parent. The backing tag is unchanged. Domain authorization is pending access-control integration.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/DomainParentSetRequest"
+ responses:
+ "200":
+ description: Successful domain operation.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "#/components/schemas/DomainResponse"
+ "400":
+ $ref: "#/components/responses/BadRequestResponse"
+ "404":
+ description: The metalake, domain, or requested parent domain does not exist.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is disabled, the name or backing tag conflicts, the domain has subdomains, or a concurrent update could not complete.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+ delete:
+ tags: [domain]
+ summary: Detach a domain
+ operationId: removeDomainParent
+ description: >-
+ Removes the current parent edge and returns the child snapshot. A top-level domain is unchanged. The backing tag is unchanged. Domain authorization is pending access-control integration.
+ responses:
+ "200":
+ description: Successful domain operation.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "#/components/schemas/DomainResponse"
+ "400":
+ $ref: "#/components/responses/BadRequestResponse"
+ "404":
+ description: The metalake or domain does not exist.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is disabled, the name or backing tag conflicts, the domain has subdomains, or a concurrent update could not complete.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+
+ /metalakes/{metalake}/domains/{domain}/backingTag:
+ parameters:
+ - $ref: "./openapi.yaml#/components/parameters/metalake"
+ - $ref: "#/components/parameters/domain"
+ put:
+ tags: [domain]
+ summary: Set or remove the backing tag
+ operationId: setDomainBackingTag
+ description: >-
+ Binds an existing tag with an optional exact value, or removes the binding when backingTag is null. Members are not migrated; previous tag assignments remain unchanged. Domain authorization is pending access-control integration.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/DomainBackingTagSetRequest"
+ responses:
+ "200":
+ description: Successful domain operation.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "#/components/schemas/DomainResponse"
+ "400":
+ $ref: "#/components/responses/BadRequestResponse"
+ "404":
+ description: The metalake, domain, or supplied backing tag does not exist.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is disabled, the name or backing tag conflicts, the domain has subdomains, or a concurrent update could not complete.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+
+ /metalakes/{metalake}/domains/{domain}/subdomains:
+ parameters:
+ - $ref: "./openapi.yaml#/components/parameters/metalake"
+ - $ref: "#/components/parameters/domain"
+ get:
+ tags: [domain]
+ summary: List subdomains
+ operationId: listSubdomains
+ description: >-
+ List subdomains. Domain authorization and DRAFT visibility are pending access-control integration.
+ parameters:
+ - name: details
+ in: query
+ description: Return domain snapshots instead of names.
+ schema:
+ type: boolean
+ default: false
+ responses:
+ "200":
+ description: Successful domain operation.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ oneOf:
+ - $ref: "#/components/schemas/DomainNameListResponse"
+ - $ref: "#/components/schemas/DomainListResponse"
+ "404":
+ description: The metalake or domain does not exist.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is not in use.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+
+ /metalakes/{metalake}/domains/{domain}/objects:
+ parameters:
+ - $ref: "./openapi.yaml#/components/parameters/metalake"
+ - name: domain
+ in: path
+ required: true
+ description: Domain name. Encode slashes as %2F in this path segment.
+ schema:
+ type: string
+ get:
+ tags: [domain]
+ summary: List recorded domain members
+ operationId: listDomainMembers
+ description: >-
+ Lists recorded leaf objects in the domain's scope, including subdomains, once each with
+ all applicable relations. Tagged catalogs and schemas expand to recorded leaves; an empty
+ result does not imply that unrecorded external objects are not members. Filters intersect.
+ No paging or counts are provided. Domain authorization, DRAFT visibility and member access
+ filtering are pending domain access-control integration.
+ parameters:
+ - name: domains
+ in: query
+ description: >-
+ Repeated domain names selecting the union of their scopes. Omit to select the whole
+ scope. Selecting the listed domain also selects its subdomains. Unknown names are
+ ignored; if all supplied names are unknown, the result is empty. Commas are literal
+ characters in names, not separators.
+ style: form
+ explode: true
+ schema:
+ type: array
+ items:
+ type: string
+ minLength: 1
+ - name: types
+ in: query
+ description: Comma-separated leaf types, case-insensitive. Omit to include all supported types.
+ style: form
+ explode: false
+ schema:
+ type: array
+ items:
+ $ref: "#/components/schemas/MemberType"
+ - name: nameContains
+ in: query
+ description: Nonblank substring of the member's full name, matched case-insensitively.
+ schema:
+ type: string
+ minLength: 1
+ responses:
+ "200":
+ description: The matching recorded members.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "#/components/schemas/DomainMemberListResponse"
+ "400":
+ $ref: "#/components/responses/BadRequestResponse"
+ "404":
+ description: The metalake or domain does not exist.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is not in use.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+
+ /metalakes/{metalake}/objects/{type}/{fullName}/domains:
+ parameters:
+ - $ref: "./openapi.yaml#/components/parameters/metalake"
+ - name: type
+ in: path
+ required: true
+ description: Leaf metadata object type, case-insensitive. Catalogs and schemas are not members.
+ schema:
+ $ref: "#/components/schemas/MemberType"
+ - name: fullName
+ in: path
+ required: true
+ description: Full name of the leaf metadata object, encoded as one path segment.
+ schema:
+ type: string
+ get:
+ tags: [domain]
+ summary: List domains containing a metadata object
+ operationId: listDomainsForMetadataObject
+ description: >-
+ Lists domains whose scopes contain the leaf object, including parents of directly matched
+ subdomains. Detailed responses carry every applicable relation without precedence.
+ Domain authorization, DRAFT visibility and member access filtering are pending domain
+ access-control integration. No paging or counts are provided.
+ parameters:
+ - name: details
+ in: query
+ description: Return domain snapshots with relations instead of names.
+ schema:
+ type: boolean
+ default: false
+ responses:
+ "200":
+ description: Domain names, or snapshots when details is true.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ oneOf:
+ - $ref: "#/components/schemas/DomainNameListResponse"
+ - $ref: "#/components/schemas/DomainListResponse"
+ "400":
+ $ref: "#/components/responses/BadRequestResponse"
+ "404":
+ description: The metalake or metadata object does not exist.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "409":
+ description: The metalake is not in use.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "#/components/responses/ServerErrorResponse"
+
+components:
+ responses:
+ BadRequestResponse:
+ description: Invalid JSON or domain request parameters.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ ServerErrorResponse:
+ description: The server could not complete the domain operation.
+ content:
+ application/json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ parameters:
+ domain:
+ name: domain
+ in: path
+ required: true
+ description: Domain name. Encode slashes as %2F; reverse proxies must preserve this encoding.
+ schema:
+ type: string
+ schemas:
+ DomainNameListResponse:
+ allOf:
+ - $ref: "./openapi.yaml#/components/schemas/NameListResponse"
+ - type: object
+ required: [names]
+
+ MemberType:
+ type: string
+ description: A supported leaf domain member type.
+ enum: [TABLE, VIEW, FILESET, TOPIC, MODEL, SEMANTIC_MODEL]
+
+ DomainRelation:
+ type: object
+ description: One applicable membership relation, with no precedence over other relations.
+ required: [relation]
+ properties:
+ relation:
+ type: string
+ enum: [direct, inherited, via_subdomain]
+ source:
+ description: >-
+ Omitted for DIRECT; the nearest tagged catalog or schema for INHERITED;
+ the subdomain metadata object for VIA_SUBDOMAIN.
+ allOf:
+ - $ref: "#/components/schemas/RelationSource"
+
+ RelationSource:
+ type: object
+ required: [fullName, type]
+ properties:
+ fullName:
+ type: string
+ type:
+ type: string
+ enum: [catalog, schema, domain]
+
+ MemberObject:
+ type: object
+ description: A leaf metadata object serialized by the server.
+ required: [fullName, type]
+ properties:
+ fullName:
+ type: string
+ type:
+ type: string
+ enum: [table, view, fileset, topic, model, semantic_model]
+
+ DomainMember:
+ type: object
+ required: [object, relations]
+ properties:
+ object:
+ $ref: "#/components/schemas/MemberObject"
+ relations:
+ type: array
+ minItems: 1
+ items:
+ $ref: "#/components/schemas/DomainRelation"
+
+ Domain:
+ type: object
+ required: [name, properties, status, audit]
+ properties:
+ name:
+ type: string
+ comment:
+ type: string
+ nullable: true
+ properties:
+ type: object
+ additionalProperties:
+ type: string
+ status:
+ type: string
+ enum: [draft, published]
+ parent:
+ type: string
+ nullable: true
+ description: Parent domain name, or null for a top-level domain.
+ backingTag:
+ type: object
+ nullable: true
+ required: [name]
+ description: Null when unbound or when the backing tag has been deleted.
+ properties:
+ name:
+ type: string
+ value:
+ type: string
+ nullable: true
+ description: Null matches any effective assignment of this tag, including valueless assignments.
+ audit:
+ $ref: "./openapi.yaml#/components/schemas/Audit"
+ relations:
+ type: array
+ minItems: 1
+ items:
+ $ref: "#/components/schemas/DomainRelation"
+
+ DomainMemberListResponse:
+ example:
+ code: 0
+ members:
+ - object:
+ fullName: cat.schema.table
+ type: table
+ relations:
+ - relation: direct
+ - relation: inherited
+ source:
+ fullName: cat.schema
+ type: schema
+ - relation: via_subdomain
+ source:
+ fullName: Finance.US
+ type: domain
+ type: object
+ required: [code, members]
+ properties:
+ code:
+ type: integer
+ enum: [0]
+ members:
+ type: array
+ items:
+ $ref: "#/components/schemas/DomainMember"
+
+ DomainListResponse:
+ example:
+ code: 0
+ domains:
+ - name: Finance
+ properties: {}
+ status: published
+ audit:
+ creator: user
+ createTime: "2026-10-01T00:00:00Z"
+ relations:
+ - relation: direct
+ type: object
+ required: [code, domains]
+ properties:
+ code:
+ type: integer
+ enum: [0]
+ domains:
+ type: array
+ items:
+ $ref: "#/components/schemas/Domain"
+
+ DomainResponse:
+ example:
+ code: 0
+ domain:
+ name: Finance
+ properties: {}
+ status: draft
+ audit:
+ creator: user
+ createTime: "2026-10-01T00:00:00Z"
+ type: object
+ required: [code, domain]
+ properties:
+ code:
+ type: integer
+ enum: [0]
+ domain:
+ $ref: "#/components/schemas/Domain"
+
+ DomainDropResponse:
+ type: object
+ required: [code, dropped]
+ properties:
+ code:
+ type: integer
+ enum: [0]
+ dropped:
+ type: boolean
+
+ BackingTag:
+ type: object
+ required: [name]
+ properties:
+ name:
+ type: string
+ minLength: 1
+ value:
+ type: string
+ nullable: true
+ minLength: 1
+ maxLength: 256
+ description: Exact assignment value; null binds any effective assignment of the tag.
+
+ DomainCreateRequest:
+ type: object
+ required: [name, backingTag]
+ properties:
+ name:
+ type: string
+ minLength: 1
+ maxLength: 128
+ comment:
+ type: string
+ nullable: true
+ properties:
+ type: object
+ nullable: true
+ additionalProperties:
+ type: string
+ parent:
+ type: string
+ nullable: true
+ minLength: 1
+ description: Optional top-level parent. A subdomain is created atomically under it.
+ backingTag:
+ allOf:
+ - $ref: "#/components/schemas/BackingTag"
+ - type: object
+ properties:
+ create:
+ type: boolean
+ default: false
+ description: True creates a new valueless tag; value must be null or omitted. False binds an existing tag.
+ example:
+ name: Finance
+ backingTag:
+ name: department
+ value: finance
+ create: false
+
+ DomainSetRequest:
+ example:
+ status: published
+ type: object
+ required: [status]
+ properties:
+ status:
+ type: string
+ enum: [draft, published, DRAFT, PUBLISHED]
+
+ DomainParentSetRequest:
+ type: object
+ required: [parent]
+ properties:
+ parent:
+ type: string
+ minLength: 1
+
+ DomainBackingTagSetRequest:
+ type: object
+ required: [backingTag]
+ description: The backingTag field must be present. An explicit null removes the current binding; an omitted field is invalid.
+ properties:
+ backingTag:
+ type: object
+ nullable: true
+ required: [name]
+ properties:
+ name:
+ type: string
+ minLength: 1
+ value:
+ type: string
+ nullable: true
+ minLength: 1
+ maxLength: 256
+ description: Exact assignment value; null binds any effective assignment of the tag.
+
+ DomainUpdatesRequest:
+ type: object
+ required: [updates]
+ properties:
+ updates:
+ type: array
+ items:
+ $ref: "#/components/schemas/DomainUpdateRequest"
+
+ DomainUpdateRequest:
+ oneOf:
+ - $ref: "#/components/schemas/RenameDomainRequest"
+ - $ref: "#/components/schemas/UpdateDomainCommentRequest"
+ - $ref: "#/components/schemas/SetDomainPropertyRequest"
+ - $ref: "#/components/schemas/RemoveDomainPropertyRequest"
+ discriminator:
+ propertyName: "@type"
+ mapping:
+ rename: "#/components/schemas/RenameDomainRequest"
+ updateComment: "#/components/schemas/UpdateDomainCommentRequest"
+ setProperty: "#/components/schemas/SetDomainPropertyRequest"
+ removeProperty: "#/components/schemas/RemoveDomainPropertyRequest"
+
+ RenameDomainRequest:
+ type: object
+ required: ["@type", newName]
+ properties:
+ "@type":
+ type: string
+ enum: [rename]
+ newName:
+ type: string
+ minLength: 1
+
+ UpdateDomainCommentRequest:
+ type: object
+ required: ["@type"]
+ properties:
+ "@type":
+ type: string
+ enum: [updateComment]
+ newComment:
+ type: string
+ nullable: true
+
+ SetDomainPropertyRequest:
+ type: object
+ required: ["@type", property, value]
+ properties:
+ "@type":
+ type: string
+ enum: [setProperty]
+ property:
+ type: string
+ minLength: 1
+ value:
+ type: string
+
+ RemoveDomainPropertyRequest:
+ type: object
+ required: ["@type", property]
+ properties:
+ "@type":
+ type: string
+ enum: [removeProperty]
+ property:
+ type: string
+ minLength: 1
diff --git a/docs/open-api/openapi.yaml b/docs/open-api/openapi.yaml
index 4a8b03c4df..633518e233 100644
--- a/docs/open-api/openapi.yaml
+++ b/docs/open-api/openapi.yaml
@@ -294,6 +294,27 @@ paths:
/metalakes/{metalake}/secrets/providers:
$ref: "./secrets.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1secrets~1providers"
+ /metalakes/{metalake}/domains/{domain}/objects:
+ $ref: "./domains.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1domains~1%7Bdomain%7D~1objects"
+
+ /metalakes/{metalake}/objects/{type}/{fullName}/domains:
+ $ref: "./domains.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1objects~1%7Btype%7D~1%7BfullName%7D~1domains"
+
+ /metalakes/{metalake}/domains:
+ $ref: "./domains.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1domains"
+
+ /metalakes/{metalake}/domains/{domain}:
+ $ref: "./domains.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1domains~1%7Bdomain%7D"
+
+ /metalakes/{metalake}/domains/{domain}/parent:
+ $ref: "./domains.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1domains~1%7Bdomain%7D~1parent"
+
+ /metalakes/{metalake}/domains/{domain}/backingTag:
+ $ref: "./domains.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1domains~1%7Bdomain%7D~1backingTag"
+
+ /metalakes/{metalake}/domains/{domain}/subdomains:
+ $ref: "./domains.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1domains~1%7Bdomain%7D~1subdomains"
+
components:
schemas:
diff --git a/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java b/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
index 7926a10b10..fffaaa96e2 100644
--- a/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
+++ b/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
@@ -41,6 +41,7 @@ import org.apache.gravitino.catalog.TableDispatcher;
import org.apache.gravitino.catalog.TopicDispatcher;
import org.apache.gravitino.catalog.ViewDispatcher;
import org.apache.gravitino.credential.CredentialOperationDispatcher;
+import org.apache.gravitino.domain.DomainDispatcher;
import org.apache.gravitino.job.JobOperationDispatcher;
import org.apache.gravitino.lineage.LineageConfig;
import org.apache.gravitino.lineage.LineageDispatcher;
@@ -179,6 +180,7 @@ public class GravitinoServer extends ResourceConfig {
bind(gravitinoEnv.filesetDispatcher()).to(FilesetDispatcher.class).ranked(1);
bind(gravitinoEnv.topicDispatcher()).to(TopicDispatcher.class).ranked(1);
bind(gravitinoEnv.tagDispatcher()).to(TagDispatcher.class).ranked(1);
+ bind(gravitinoEnv.domainDispatcher()).to(DomainDispatcher.class).ranked(1);
bind(gravitinoEnv.policyDispatcher()).to(PolicyDispatcher.class).ranked(1);
bind(gravitinoEnv.credentialOperationDispatcher())
.to(CredentialOperationDispatcher.class)
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/DomainMembershipOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/DomainMembershipOperations.java
new file mode 100644
index 0000000000..0f405a0f37
--- /dev/null
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/DomainMembershipOperations.java
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.server.web.rest;
+
+import com.codahale.metrics.annotation.ResponseMetered;
+import com.codahale.metrics.annotation.Timed;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import javax.annotation.Nullable;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.domain.DomainDispatcher;
+import org.apache.gravitino.domain.DomainMember;
+import org.apache.gravitino.domain.DomainMemberFilter;
+import org.apache.gravitino.dto.domain.DomainMemberDTO;
+import org.apache.gravitino.dto.responses.DomainMemberListResponse;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.server.web.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** REST queries for the recorded leaf members in a domain's scope. */
+@Path("/metalakes/{metalake}/domains/{domain}/objects")
+public class DomainMembershipOperations {
+
+ private static final Logger LOG = LoggerFactory.getLogger(DomainMembershipOperations.class);
+ private final DomainDispatcher domainDispatcher;
+ @Context private HttpServletRequest httpRequest;
+
+ /**
+ * Creates the domain membership resource.
+ *
+ * @param domainDispatcher The domain dispatcher.
+ */
+ @Inject
+ public DomainMembershipOperations(DomainDispatcher domainDispatcher) {
+ this.domainDispatcher = domainDispatcher;
+ }
+
+ /**
+ * Lists members matching the intersection of the supplied filters.
+ *
+ * @param metalake The metalake name.
+ * @param domain The domain name.
+ * @param types Comma-separated leaf types, or null for all supported types.
+ * @param nameContains Case-insensitive full-name substring, or null for any name.
+ * @param domains Repeated domain names selecting the union of their scopes.
+ * @return The matching recorded members with all applicable relations.
+ */
+ @GET
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "list-domain-members." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "list-domain-members", absolute = true)
+ public Response listMembers(
+ @PathParam("metalake") String metalake,
+ @PathParam("domain") String domain,
+ @QueryParam("types") @Nullable String types,
+ @QueryParam("nameContains") @Nullable String nameContains,
+ @QueryParam("domains") List<String> domains) {
+ LOG.info("Received list members request for domain {} under metalake {}", domain, metalake);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ DomainMemberFilter.Builder filter =
+ DomainMemberFilter.builder().withNameContains(nameContains);
+ if (types != null) {
+ filter.withTypes(
+ Arrays.stream(types.split(",", -1))
+ .map(DomainMembershipOperations::parseMemberType)
+ .toArray(MetadataObject.Type[]::new));
+ }
+ if (domains != null) {
+ filter.withDomains(domains.toArray(new String[0]));
+ }
+ // Domain visibility and member authorization will be added with domain access control.
+ DomainMemberDTO[] members =
+ Arrays.stream(domainDispatcher.listMembers(metalake, domain, filter.build()))
+ .map(DomainMemberDTO::from)
+ .toArray(DomainMemberDTO[]::new);
+ return Utils.ok(new DomainMemberListResponse(members));
+ });
+ } catch (Exception e) {
+ return ExceptionHandlers.handleDomainException(OperationType.LIST, domain, metalake, e);
+ }
+ }
+
+ private static MetadataObject.Type parseMemberType(String value) {
+ try {
+ MetadataObject.Type type = MetadataObject.Type.valueOf(value.trim().toUpperCase(Locale.ROOT));
+ if (DomainMember.SUPPORTED_TYPES.contains(type)) {
+ return type;
+ }
+ } catch (IllegalArgumentException ignored) {
+ // Report unknown and unsupported types with the same public API error message.
+ }
+ throw new IllegalArgumentException(
+ "Unsupported domain member type '"
+ + value
+ + "'. Supported types: "
+ + DomainMember.SUPPORTED_TYPES);
+ }
+}
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/DomainOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/DomainOperations.java
new file mode 100644
index 0000000000..87a92d5be2
--- /dev/null
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/DomainOperations.java
@@ -0,0 +1,398 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.server.web.rest;
+
+import com.codahale.metrics.annotation.ResponseMetered;
+import com.codahale.metrics.annotation.Timed;
+import java.util.Arrays;
+import java.util.function.Supplier;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.PATCH;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.domain.DomainChange;
+import org.apache.gravitino.domain.DomainDispatcher;
+import org.apache.gravitino.dto.domain.DomainDTO;
+import org.apache.gravitino.dto.requests.DomainBackingTagSetRequest;
+import org.apache.gravitino.dto.requests.DomainCreateRequest;
+import org.apache.gravitino.dto.requests.DomainParentSetRequest;
+import org.apache.gravitino.dto.requests.DomainSetRequest;
+import org.apache.gravitino.dto.requests.DomainUpdateRequest;
+import org.apache.gravitino.dto.requests.DomainUpdatesRequest;
+import org.apache.gravitino.dto.responses.DomainListResponse;
+import org.apache.gravitino.dto.responses.DomainResponse;
+import org.apache.gravitino.dto.responses.DropResponse;
+import org.apache.gravitino.dto.responses.NameListResponse;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.rest.RESTRequest;
+import org.apache.gravitino.server.web.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** REST operations for domains. Domain access control is integrated separately. */
+@Path("/metalakes/{metalake}/domains")
+@Produces("application/vnd.gravitino.v1+json")
+public class DomainOperations {
+
+ private static final Logger LOG = LoggerFactory.getLogger(DomainOperations.class);
+ private final DomainDispatcher domainDispatcher;
+ @Context private HttpServletRequest httpRequest;
+
+ /**
+ * Creates the domain resource.
+ *
+ * @param domainDispatcher The domain dispatcher.
+ */
+ @Inject
+ public DomainOperations(DomainDispatcher domainDispatcher) {
+ this.domainDispatcher = domainDispatcher;
+ }
+
+ /**
+ * Lists the domain names or snapshots in a metalake.
+ *
+ * @param metalake The metalake name.
+ * @param details Whether to include domain snapshots.
+ * @return The REST response.
+ */
+ @GET
+ @Timed(name = "list-domains." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "list-domains", absolute = true)
+ public Response listDomains(
+ @PathParam("metalake") String metalake,
+ @QueryParam("details") @DefaultValue("false") boolean details) {
+ return execute(
+ OperationType.LIST,
+ metalake,
+ "",
+ () -> {
+ return details
+ ? listResponse(domainDispatcher.listDomainInfos(metalake))
+ : Utils.ok(new NameListResponse(domainDispatcher.listDomains(metalake)));
+ });
+ }
+
+ /**
+ * Creates a draft domain and its optional parent edge atomically.
+ *
+ * @param metalake The metalake name.
+ * @param request The requested domain change.
+ * @return The REST response.
+ */
+ @POST
+ @Consumes("application/json")
+ @Timed(name = "create-domain." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "create-domain", absolute = true)
+ public Response createDomain(
+ @PathParam("metalake") String metalake, DomainCreateRequest request) {
+ return execute(
+ OperationType.CREATE,
+ metalake,
+ "",
+ () -> {
+ validateRequest(request);
+ DomainCreateRequest.BackingTag tag = request.getBackingTag();
+ DomainEntity created =
+ request.getParent() == null
+ ? domainDispatcher.createDomain(
+ metalake,
+ request.getName(),
+ request.getComment(),
+ request.getProperties(),
+ tag.tagValue(),
+ tag.isCreate())
+ : domainDispatcher.createSubdomain(
+ metalake,
+ request.getParent(),
+ request.getName(),
+ request.getComment(),
+ request.getProperties(),
+ tag.tagValue(),
+ tag.isCreate());
+ return domainResponse(created);
+ });
+ }
+
+ /**
+ * Gets a domain snapshot.
+ *
+ * @param metalake The metalake name.
+ * @param domain The domain name.
+ * @return The REST response.
+ */
+ @GET
+ @Path("{domain}")
+ @Timed(name = "get-domain." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "get-domain", absolute = true)
+ public Response getDomain(
+ @PathParam("metalake") String metalake, @PathParam("domain") String domain) {
+ return execute(
+ OperationType.GET,
+ metalake,
+ domain,
+ () -> {
+ return domainResponse(domainDispatcher.getDomain(metalake, domain));
+ });
+ }
+
+ /**
+ * Applies name, comment and property updates to a domain.
+ *
+ * @param metalake The metalake name.
+ * @param domain The domain name.
+ * @param request The requested domain change.
+ * @return The REST response.
+ */
+ @PUT
+ @Path("{domain}")
+ @Consumes("application/json")
+ @Timed(name = "alter-domain." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "alter-domain", absolute = true)
+ public Response alterDomain(
+ @PathParam("metalake") String metalake,
+ @PathParam("domain") String domain,
+ DomainUpdatesRequest request) {
+ return execute(
+ OperationType.ALTER,
+ metalake,
+ domain,
+ () -> {
+ validateRequest(request);
+ DomainChange[] changes =
+ request.getUpdates().stream()
+ .map(DomainUpdateRequest::domainChange)
+ .toArray(DomainChange[]::new);
+ return domainResponse(domainDispatcher.alterDomain(metalake, domain, changes));
+ });
+ }
+
+ /**
+ * Publishes or unpublishes a domain and returns the updated snapshot.
+ *
+ * @param metalake The metalake name.
+ * @param domain The domain name.
+ * @param request The requested domain change.
+ * @return The REST response.
+ */
+ @PATCH
+ @Path("{domain}")
+ @Consumes("application/json")
+ @Timed(name = "set-domain-status." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "set-domain-status", absolute = true)
+ public Response setDomain(
+ @PathParam("metalake") String metalake,
+ @PathParam("domain") String domain,
+ DomainSetRequest request) {
+ return execute(
+ OperationType.ALTER,
+ metalake,
+ domain,
+ () -> {
+ validateRequest(request);
+ return domainResponse(
+ request.getStatus() == Domain.Status.PUBLISHED
+ ? domainDispatcher.publishDomain(metalake, domain)
+ : domainDispatcher.unpublishDomain(metalake, domain));
+ });
+ }
+
+ /**
+ * Deletes a domain, returning false when it is absent.
+ *
+ * @param metalake The metalake name.
+ * @param domain The domain name.
+ * @return The REST response.
+ */
+ @DELETE
+ @Path("{domain}")
+ @Timed(name = "delete-domain." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "delete-domain", absolute = true)
+ public Response deleteDomain(
+ @PathParam("metalake") String metalake, @PathParam("domain") String domain) {
+ return execute(
+ OperationType.DELETE,
+ metalake,
+ domain,
+ () -> {
+ return Utils.ok(new DropResponse(domainDispatcher.deleteDomain(metalake, domain)));
+ });
+ }
+
+ /**
+ * Attaches or moves a domain under a top-level parent.
+ *
+ * @param metalake The metalake name.
+ * @param domain The domain name.
+ * @param request The requested domain change.
+ * @return The REST response.
+ */
+ @PUT
+ @Path("{domain}/parent")
+ @Consumes("application/json")
+ @Timed(name = "set-domain-parent." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "set-domain-parent", absolute = true)
+ public Response setParent(
+ @PathParam("metalake") String metalake,
+ @PathParam("domain") String domain,
+ DomainParentSetRequest request) {
+ return execute(
+ OperationType.ALTER,
+ metalake,
+ domain,
+ () -> {
+ validateRequest(request);
+ return domainResponse(
+ domainDispatcher.attachDomain(metalake, domain, request.getParent()));
+ });
+ }
+
+ /**
+ * Detaches a domain; a top-level domain is unchanged.
+ *
+ * @param metalake The metalake name.
+ * @param domain The domain name.
+ * @return The REST response.
+ */
+ @DELETE
+ @Path("{domain}/parent")
+ @Timed(name = "remove-domain-parent." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "remove-domain-parent", absolute = true)
+ public Response removeParent(
+ @PathParam("metalake") String metalake, @PathParam("domain") String domain) {
+ return execute(
+ OperationType.ALTER,
+ metalake,
+ domain,
+ () -> {
+ return domainResponse(domainDispatcher.detachDomain(metalake, domain));
+ });
+ }
+
+ /**
+ * Replaces the backing tag or removes it when backingTag is null.
+ *
+ * @param metalake The metalake name.
+ * @param domain The domain name.
+ * @param request The requested domain change.
+ * @return The REST response.
+ */
+ @PUT
+ @Path("{domain}/backingTag")
+ @Consumes("application/json")
+ @Timed(name = "set-domain-backing-tag." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "set-domain-backing-tag", absolute = true)
+ public Response setBackingTag(
+ @PathParam("metalake") String metalake,
+ @PathParam("domain") String domain,
+ DomainBackingTagSetRequest request) {
+ return execute(
+ OperationType.ALTER,
+ metalake,
+ domain,
+ () -> {
+ validateRequest(request);
+ return domainResponse(
+ domainDispatcher.updateBackingTag(
+ metalake,
+ domain,
+ request.getBackingTag() == null ? null : request.getBackingTag().tagValue()));
+ });
+ }
+
+ /**
+ * Lists the subdomain names or snapshots.
+ *
+ * @param metalake The metalake name.
+ * @param domain The domain name.
+ * @param details Whether to include domain snapshots.
+ * @return The REST response.
+ */
+ @GET
+ @Path("{domain}/subdomains")
+ @Timed(name = "list-subdomains." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "list-subdomains", absolute = true)
+ public Response listSubdomains(
+ @PathParam("metalake") String metalake,
+ @PathParam("domain") String domain,
+ @QueryParam("details") @DefaultValue("false") boolean details) {
+ return execute(
+ OperationType.LIST,
+ metalake,
+ domain,
+ () -> {
+ return details
+ ? listResponse(domainDispatcher.listSubdomainInfos(metalake, domain))
+ : Utils.ok(new NameListResponse(domainDispatcher.listSubdomains(metalake, domain)));
+ });
+ }
+
+ // Shared with the reverse membership query so every endpoint has the same snapshot shape.
+ static DomainDTO toDTO(DomainEntity domain) {
+ return new DomainDTO(
+ domain.name(),
+ domain.comment(),
+ domain.properties(),
+ domain.status(),
+ domain.parent().orElse(null),
+ domain.backingTag().orElse(null),
+ DTOConverters.toDTO(domain.auditInfo()),
+ domain.relations());
+ }
+
+ private Response execute(
+ OperationType operation, String metalake, String domain, Supplier<Response> action) {
+ LOG.info("Received domain {} request for {} under metalake {}", operation, domain, metalake);
+ try {
+ return Utils.doAs(httpRequest, action::get);
+ } catch (Exception e) {
+ return ExceptionHandlers.handleDomainException(operation, domain, metalake, e);
+ }
+ }
+
+ private static void validateRequest(RESTRequest request) {
+ if (request == null) {
+ throw new IllegalArgumentException("Request body cannot be null");
+ }
+ request.validate();
+ }
+
+ private static Response domainResponse(DomainEntity domain) {
+ return Utils.ok(new DomainResponse(toDTO(domain)));
+ }
+
+ private static Response listResponse(DomainEntity[] domains) {
+ return Utils.ok(
+ new DomainListResponse(
+ Arrays.stream(domains).map(DomainOperations::toDTO).toArray(DomainDTO[]::new)));
+ }
+}
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
index eb7efd56d2..7f5b35b55f 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
@@ -40,6 +40,7 @@ import org.apache.gravitino.exceptions.ModelAlreadyExistsException;
import org.apache.gravitino.exceptions.ModelVersionAliasesAlreadyExistException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.exceptions.NonEmptyCatalogException;
+import org.apache.gravitino.exceptions.NonEmptyDomainException;
import org.apache.gravitino.exceptions.NonEmptyMetalakeException;
import org.apache.gravitino.exceptions.NonEmptySchemaException;
import org.apache.gravitino.exceptions.NotFoundException;
@@ -134,6 +135,20 @@ public class ExceptionHandlers {
return GroupPermissionOperationExceptionHandler.INSTANCE.handle(op, roles, parent, e);
}
+ /**
+ * Maps domain query failures to REST error responses.
+ *
+ * @param op The operation.
+ * @param name The queried domain or metadata object.
+ * @param metalake The metalake name.
+ * @param e The failure.
+ * @return The error response.
+ */
+ public static Response handleDomainException(
+ OperationType op, String name, String metalake, Exception e) {
+ return DomainExceptionHandler.INSTANCE.handle(op, name, metalake, e);
+ }
+
public static Response handleTagException(
OperationType op, String tag, String parent, Exception e) {
return TagExceptionHandler.INSTANCE.handle(op, tag, parent, e);
@@ -888,6 +903,39 @@ public class ExceptionHandlers {
}
}
+ private static class DomainExceptionHandler extends BaseExceptionHandler {
+
+ private static final ExceptionHandler INSTANCE = new DomainExceptionHandler();
+
+ @Override
+ public Response handle(OperationType op, String name, String metalake, Exception e) {
+ String message =
+ String.format(
+ "Failed to execute domain operation [%s] on [%s] under metalake [%s], reason [%s]",
+ op, name, metalake, getErrorMsg(e));
+ LOG.warn(message, e);
+ if (e instanceof IllegalArgumentException) {
+ return Utils.illegalArguments(message, e);
+ }
+ if (e instanceof NotFoundException) {
+ return Utils.notFound(message, e);
+ }
+ if (e instanceof NotInUseException) {
+ return Utils.notInUse(message, e);
+ }
+ if (e instanceof AlreadyExistsException) {
+ return Utils.alreadyExists(message, e);
+ }
+ if (e instanceof NonEmptyDomainException) {
+ return Utils.nonEmpty(message, e);
+ }
+ if (e instanceof ForbiddenException) {
+ return Utils.forbidden(message, e);
+ }
+ return super.handle(op, name, metalake, e);
+ }
+ }
+
private static class PolicyExceptionHandler extends BaseExceptionHandler {
private static final ExceptionHandler INSTANCE = new PolicyExceptionHandler();
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectDomainOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectDomainOperations.java
new file mode 100644
index 0000000000..f69be7e118
--- /dev/null
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectDomainOperations.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.server.web.rest;
+
+import com.codahale.metrics.annotation.ResponseMetered;
+import com.codahale.metrics.annotation.Timed;
+import java.util.Arrays;
+import java.util.Locale;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.domain.DomainDispatcher;
+import org.apache.gravitino.domain.DomainMember;
+import org.apache.gravitino.dto.domain.DomainDTO;
+import org.apache.gravitino.dto.responses.DomainListResponse;
+import org.apache.gravitino.dto.responses.NameListResponse;
+import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.server.web.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** REST queries for the domains whose scopes contain a recorded leaf object. */
+@Path("/metalakes/{metalake}/objects/{type}/{fullName}/domains")
+public class MetadataObjectDomainOperations {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MetadataObjectDomainOperations.class);
+ private final DomainDispatcher domainDispatcher;
+ @Context private HttpServletRequest httpRequest;
+
+ /**
+ * Creates the object's domain resource.
+ *
+ * @param domainDispatcher The domain dispatcher.
+ */
+ @Inject
+ public MetadataObjectDomainOperations(DomainDispatcher domainDispatcher) {
+ this.domainDispatcher = domainDispatcher;
+ }
+
+ /**
+ * Lists domains containing a leaf metadata object.
+ *
+ * @param metalake The metalake name.
+ * @param type The supported leaf object type.
+ * @param fullName The object's full name.
+ * @param details Whether to return snapshots including relations instead of names.
+ * @return The domain names or snapshots.
+ */
+ @GET
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "list-object-domains." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "list-object-domains", absolute = true)
+ public Response listDomains(
+ @PathParam("metalake") String metalake,
+ @PathParam("type") String type,
+ @PathParam("fullName") String fullName,
+ @QueryParam("details") @DefaultValue("false") boolean details) {
+ LOG.info("Received list domains request for {} {} under metalake {}", type, fullName, metalake);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ MetadataObject.Type objectType =
+ MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT));
+ if (!DomainMember.SUPPORTED_TYPES.contains(objectType)) {
+ throw new IllegalArgumentException(
+ "Type " + objectType + " cannot be a domain member");
+ }
+ MetadataObject object = MetadataObjects.parse(fullName, objectType);
+ // Domain visibility and member authorization will be added with domain access control.
+ DomainEntity[] domains =
+ domainDispatcher.listDomainsForMetadataObject(metalake, object);
+ if (!details) {
+ return Utils.ok(
+ new NameListResponse(
+ Arrays.stream(domains).map(DomainEntity::name).toArray(String[]::new)));
+ }
+ DomainDTO[] dtos =
+ Arrays.stream(domains).map(DomainOperations::toDTO).toArray(DomainDTO[]::new);
+ return Utils.ok(new DomainListResponse(dtos));
+ });
+ } catch (Exception e) {
+ return ExceptionHandlers.handleDomainException(OperationType.LIST, fullName, metalake, e);
+ }
+ }
+}
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestDomainMembershipOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestDomainMembershipOperations.java
new file mode 100644
index 0000000000..9cc99abe41
--- /dev/null
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestDomainMembershipOperations.java
@@ -0,0 +1,350 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.server.web.rest;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Map;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.domain.DomainDispatcher;
+import org.apache.gravitino.domain.DomainMember;
+import org.apache.gravitino.domain.DomainMemberFilter;
+import org.apache.gravitino.domain.DomainMemberInfo;
+import org.apache.gravitino.domain.DomainRelation;
+import org.apache.gravitino.dto.domain.DomainDTO;
+import org.apache.gravitino.dto.responses.DomainListResponse;
+import org.apache.gravitino.dto.responses.DomainMemberListResponse;
+import org.apache.gravitino.dto.responses.ErrorResponse;
+import org.apache.gravitino.dto.responses.NameListResponse;
+import org.apache.gravitino.exceptions.NoSuchDomainException;
+import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.rest.RESTUtils;
+import org.apache.gravitino.server.web.ObjectMapperProvider;
+import org.glassfish.jersey.client.ClientConfig;
+import org.glassfish.jersey.internal.inject.AbstractBinder;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.test.TestProperties;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.ArgumentCaptor;
+
+public class TestDomainMembershipOperations extends BaseOperationsTest {
+
+ private static final String MEMBERS = "/metalakes/test/domains/Finance/objects";
+ private static final String OBJECT_DOMAINS =
+ "/metalakes/test/objects/table/cat.schema.table/domains";
+
+ private final DomainDispatcher dispatcher = mock(DomainDispatcher.class);
+
+ private static class MockServletRequestFactory extends ServletRequestFactoryBase {
+
+ @Override
+ public HttpServletRequest get() {
+ return mock(HttpServletRequest.class);
+ }
+ }
+
+ @Override
+ protected void configureClient(ClientConfig config) {
+ config.register(new ObjectMapperProvider());
+ }
+
+ @Override
+ protected Application configure() {
+ try {
+ forceSet(
+ TestProperties.CONTAINER_PORT, String.valueOf(RESTUtils.findAvailablePort(2000, 3000)));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return new ResourceConfig(
+ DomainMembershipOperations.class, MetadataObjectDomainOperations.class)
+ .register(new ObjectMapperProvider())
+ .register(
+ new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(dispatcher).to(DomainDispatcher.class);
+ bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);
+ }
+ });
+ }
+
+ @Test
+ public void testMemberFiltersAndRelations() {
+ MetadataObject table = MetadataObjects.parse("cat.schema.table", MetadataObject.Type.TABLE);
+ DomainRelation[] relations = {
+ DomainRelation.direct(),
+ DomainRelation.inherited(MetadataObjects.parse("cat.schema", MetadataObject.Type.SCHEMA)),
+ DomainRelation.viaSubdomain("Tax,Trading")
+ };
+ when(dispatcher.listMembers(eq("test"), eq("Finance"), any()))
+ .thenReturn(new DomainMember[] {new DomainMemberInfo(table, relations)});
+ try (Response response =
+ target(MEMBERS)
+ .queryParam("types", "table,VIEW")
+ .queryParam("domains", "Tax,Trading", "Markets/US")
+ .queryParam("nameContains", "TaBlE")
+ .request()
+ .get()) {
+ assertEquals(200, response.getStatus());
+ DomainMemberListResponse result = response.readEntity(DomainMemberListResponse.class);
+ result.validate();
+ assertEquals(1, result.getMembers().length);
+ assertEquals(table.fullName(), result.getMembers()[0].getObject().fullName());
+ assertEquals(table.type(), result.getMembers()[0].getObject().type());
+ assertEquals(3, result.getMembers()[0].getRelations().length);
+ assertEquals(
+ DomainRelation.Type.DIRECT, result.getMembers()[0].getRelations()[0].getRelation());
+ assertNull(result.getMembers()[0].getRelations()[0].getSource());
+ assertEquals("cat.schema", result.getMembers()[0].getRelations()[1].getSource().fullName());
+ assertEquals("Tax,Trading", result.getMembers()[0].getRelations()[2].getSource().name());
+ }
+ ArgumentCaptor<DomainMemberFilter> filter = ArgumentCaptor.forClass(DomainMemberFilter.class);
+ verify(dispatcher).listMembers(eq("test"), eq("Finance"), filter.capture());
+ assertEquals(
+ DomainMemberFilter.builder()
+ .withTypes(MetadataObject.Type.TABLE, MetadataObject.Type.VIEW)
+ .withDomains("Tax,Trading", "Markets/US")
+ .withNameContains("TaBlE")
+ .build(),
+ filter.getValue());
+ }
+
+ @Test
+ public void testDefaultFiltersAndEmptyResults() {
+ when(dispatcher.listMembers("test", "Finance", DomainMemberFilter.builder().build()))
+ .thenReturn(new DomainMember[0]);
+ try (Response response = target(MEMBERS).request().get()) {
+ assertEquals(200, response.getStatus());
+ assertEquals(0, response.readEntity(DomainMemberListResponse.class).getMembers().length);
+ }
+ when(dispatcher.listDomainsForMetadataObject(eq("test"), any()))
+ .thenReturn(new DomainEntity[0]);
+ try (Response response = target(OBJECT_DOMAINS).request().get()) {
+ assertEquals(200, response.getStatus());
+ assertEquals(0, response.readEntity(NameListResponse.class).getNames().length);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"TABLE", "VIEW", "FILESET", "TOPIC", "MODEL", "SEMANTIC_MODEL"})
+ public void testSupportedMemberTypes(String type) {
+ when(dispatcher.listMembers(eq("test"), eq("Finance"), any())).thenReturn(new DomainMember[0]);
+ try (Response response = target(MEMBERS).queryParam("types", type).request().get()) {
+ assertEquals(200, response.getStatus());
+ }
+ when(dispatcher.listDomainsForMetadataObject(eq("test"), any()))
+ .thenReturn(new DomainEntity[0]);
+ try (Response response =
+ target("/metalakes/test/objects/" + type + "/cat.schema.member/domains")
+ .queryParam("details", true)
+ .request()
+ .get()) {
+ assertEquals(200, response.getStatus());
+ assertEquals(0, response.readEntity(DomainListResponse.class).getDomains().length);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "",
+ "TABLE,",
+ ",TABLE",
+ "TABLE,,VIEW",
+ "CATALOG",
+ "SCHEMA",
+ "COLUMN",
+ "FUNCTION",
+ "DOMAIN",
+ "UNKNOWN"
+ })
+ public void testInvalidTypes(String types) {
+ try (Response response = target(MEMBERS).queryParam("types", types).request().get()) {
+ assertEquals(400, response.getStatus());
+ ErrorResponse error = response.readEntity(ErrorResponse.class);
+ assertEquals("IllegalArgumentException", error.getType());
+ assertTrue(error.getMessage().contains("Supported types:"));
+ for (MetadataObject.Type supported : DomainMember.SUPPORTED_TYPES) {
+ assertTrue(error.getMessage().contains(supported.name()));
+ }
+ }
+ verifyNoInteractions(dispatcher);
+ }
+
+ @Test
+ public void testBlankFilters() {
+ for (String parameter : new String[] {"domains", "nameContains"}) {
+ try (Response response = target(MEMBERS).queryParam(parameter, " ").request().get()) {
+ assertError(response, 400, "IllegalArgumentException");
+ }
+ }
+ verifyNoInteractions(dispatcher);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"CATALOG", "SCHEMA", "COLUMN", "FUNCTION", "DOMAIN", "UNKNOWN"})
+ public void testUnsupportedObjectTypes(String type) {
+ try (Response response =
+ target("/metalakes/test/objects/" + type + "/cat.schema.table/domains").request().get()) {
+ assertError(response, 400, "IllegalArgumentException");
+ }
+ verifyNoInteractions(dispatcher);
+ }
+
+ @Test
+ public void testInvalidFullName() {
+ try (Response response =
+ target("/metalakes/test/objects/table/table/domains").request().get()) {
+ assertError(response, 400, "IllegalArgumentException");
+ }
+ verifyNoInteractions(dispatcher);
+ }
+
+ @Test
+ public void testDomainSnapshotsAndNames() {
+ DomainEntity domain =
+ DomainEntity.builder()
+ .withId(1L)
+ .withName("Tax")
+ .withNamespace(Namespace.of("test"))
+ .withComment("Tax domain")
+ .withProperties(Map.of("key", "value"))
+ .withStatus(Domain.Status.DRAFT)
+ .withParent("Finance")
+ .withBackingTagId(2L)
+ .withBackingTagName("department")
+ .withBackingTagValue("tax")
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator("user")
+ .withCreateTime(Instant.parse("2026-10-01T00:00:00Z"))
+ .build())
+ .withRelations(new DomainRelation[] {DomainRelation.direct()})
+ .build();
+ when(dispatcher.listDomainsForMetadataObject(eq("test"), any()))
+ .thenReturn(new DomainEntity[] {domain});
+ try (Response response = target(OBJECT_DOMAINS).request().get()) {
+ assertEquals(200, response.getStatus());
+ assertArrayEquals(
+ new String[] {"Tax"}, response.readEntity(NameListResponse.class).getNames());
+ }
+ try (Response response = target(OBJECT_DOMAINS).queryParam("details", true).request().get()) {
+ assertEquals(200, response.getStatus());
+ DomainListResponse result = response.readEntity(DomainListResponse.class);
+ result.validate();
+ DomainDTO dto = result.getDomains()[0];
+ assertEquals("Tax", dto.getName());
+ assertEquals("Tax domain", dto.getComment());
+ assertEquals(Map.of("key", "value"), dto.getProperties());
+ assertEquals(Domain.Status.DRAFT, dto.getStatus());
+ assertEquals("Finance", dto.getParent());
+ assertEquals("department", dto.getBackingTag().getName());
+ assertEquals("tax", dto.getBackingTag().getValue());
+ assertEquals("user", dto.getAudit().creator());
+ assertEquals(DomainRelation.Type.DIRECT, dto.getRelations()[0].getRelation());
+ }
+ verify(dispatcher, times(2))
+ .listDomainsForMetadataObject(
+ "test", MetadataObjects.parse("cat.schema.table", MetadataObject.Type.TABLE));
+ }
+
+ @Test
+ public void testQueryErrors() {
+ when(dispatcher.listMembers(eq("test"), eq("Finance"), any()))
+ .thenThrow(new NoSuchDomainException("Missing domain"));
+ try (Response response = target(MEMBERS).request().get()) {
+ assertError(response, 404, "NoSuchDomainException");
+ }
+ when(dispatcher.listDomainsForMetadataObject(eq("test"), any()))
+ .thenThrow(new NoSuchMetalakeException("Missing metalake"));
+ try (Response response = target(OBJECT_DOMAINS).request().get()) {
+ assertError(response, 404, "NoSuchMetalakeException");
+ }
+ when(dispatcher.listMembers(eq("test"), eq("Finance"), any()))
+ .thenThrow(new RuntimeException("Store unavailable"));
+ try (Response response = target(MEMBERS).request().get()) {
+ assertError(response, 500, "RuntimeException");
+ }
+ }
+
+ @Test
+ public void testProductionMemberJsonRepresentation() throws IOException {
+ DomainMember member =
+ new DomainMemberInfo(
+ MetadataObjects.parse("cat.schema.table", MetadataObject.Type.TABLE),
+ new DomainRelation[] {
+ DomainRelation.direct(),
+ DomainRelation.inherited(
+ MetadataObjects.parse("cat.schema", MetadataObject.Type.SCHEMA)),
+ DomainRelation.viaSubdomain("Finance.US")
+ });
+ when(dispatcher.listMembers(eq("test"), eq("Finance"), any()))
+ .thenReturn(new DomainMember[] {member});
+ try (Response response = target(MEMBERS).request().get()) {
+ assertEquals(200, response.getStatus());
+ JsonNode result =
+ JsonUtils.objectMapper()
+ .readTree(response.readEntity(String.class))
+ .get("members")
+ .get(0);
+ assertEquals("table", result.get("object").get("type").asText());
+ JsonNode relations = result.get("relations");
+ assertEquals("direct", relations.get(0).get("relation").asText());
+ assertFalse(relations.get(0).has("source"));
+ assertEquals("inherited", relations.get(1).get("relation").asText());
+ assertEquals("schema", relations.get(1).get("source").get("type").asText());
+ assertEquals("via_subdomain", relations.get(2).get("relation").asText());
+ assertEquals("domain", relations.get(2).get("source").get("type").asText());
+ assertEquals("Finance.US", relations.get(2).get("source").get("fullName").asText());
+ }
+ }
+
+ private static void assertError(Response response, int status, String type) {
+ assertEquals(status, response.getStatus());
+ assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType());
+ assertEquals(type, response.readEntity(ErrorResponse.class).getType());
+ }
+}
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestDomainOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestDomainOperations.java
new file mode 100644
index 0000000000..8f6319acfe
--- /dev/null
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestDomainOperations.java
@@ -0,0 +1,473 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.server.web.rest;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Map;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.domain.DomainChange;
+import org.apache.gravitino.domain.DomainDispatcher;
+import org.apache.gravitino.dto.requests.DomainBackingTagSetRequest;
+import org.apache.gravitino.dto.responses.DomainListResponse;
+import org.apache.gravitino.dto.responses.DomainResponse;
+import org.apache.gravitino.dto.responses.DropResponse;
+import org.apache.gravitino.dto.responses.ErrorConstants;
+import org.apache.gravitino.dto.responses.ErrorResponse;
+import org.apache.gravitino.dto.responses.NameListResponse;
+import org.apache.gravitino.exceptions.BackingTagAlreadyBoundException;
+import org.apache.gravitino.exceptions.DomainAlreadyExistsException;
+import org.apache.gravitino.exceptions.MetalakeNotInUseException;
+import org.apache.gravitino.exceptions.NoSuchDomainException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
+import org.apache.gravitino.exceptions.NonEmptyDomainException;
+import org.apache.gravitino.exceptions.TagAlreadyExistsException;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.rest.RESTUtils;
+import org.apache.gravitino.server.web.ObjectMapperProvider;
+import org.apache.gravitino.server.web.mapper.JsonMappingExceptionMapper;
+import org.apache.gravitino.server.web.mapper.JsonProcessingExceptionMapper;
+import org.apache.gravitino.tag.TagValue;
+import org.glassfish.jersey.client.ClientConfig;
+import org.glassfish.jersey.client.HttpUrlConnectorProvider;
+import org.glassfish.jersey.internal.inject.AbstractBinder;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.test.TestProperties;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+public class TestDomainOperations extends BaseOperationsTest {
+
+ private static final String BASE = "/metalakes/test/domains";
+ private static final String ITEM = BASE + "/Finance";
+ private final DomainDispatcher dispatcher = mock(DomainDispatcher.class);
+
+ private static class MockServletRequestFactory extends ServletRequestFactoryBase {
+
+ @Override
+ public HttpServletRequest get() {
+ return mock(HttpServletRequest.class);
+ }
+ }
+
+ @Override
+ protected void configureClient(ClientConfig config) {
+ config.register(new ObjectMapperProvider());
+ }
+
+ @Override
+ protected Application configure() {
+ try {
+ forceSet(
+ TestProperties.CONTAINER_PORT, String.valueOf(RESTUtils.findAvailablePort(2000, 3000)));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return new ResourceConfig(
+ DomainOperations.class,
+ DomainMembershipOperations.class,
+ JsonProcessingExceptionMapper.class,
+ JsonMappingExceptionMapper.class)
+ .register(new ObjectMapperProvider())
+ .register(
+ new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(dispatcher).to(DomainDispatcher.class);
+ bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);
+ }
+ });
+ }
+
+ @Test
+ public void testListsAndGet() {
+ DomainEntity domain = domain(Domain.Status.DRAFT);
+ when(dispatcher.listDomains("test")).thenReturn(new String[] {"Finance"});
+ when(dispatcher.listDomainInfos("test")).thenReturn(new DomainEntity[] {domain});
+ when(dispatcher.listSubdomains("test", "Finance")).thenReturn(new String[] {"Tax"});
+ when(dispatcher.listSubdomainInfos("test", "Finance")).thenReturn(new DomainEntity[] {domain});
+ when(dispatcher.getDomain("test", "Finance")).thenReturn(domain);
+ for (String path : new String[] {BASE, ITEM + "/subdomains"}) {
+ try (Response response = target(path).request().get()) {
+ assertEquals(200, response.getStatus());
+ assertArrayEquals(
+ new String[] {path.equals(BASE) ? "Finance" : "Tax"},
+ response.readEntity(NameListResponse.class).getNames());
+ }
+ try (Response response = target(path).queryParam("details", true).request().get()) {
+ assertEquals(200, response.getStatus());
+ DomainListResponse result = response.readEntity(DomainListResponse.class);
+ result.validate();
+ assertEquals("Finance", result.getDomains()[0].getName());
+ }
+ }
+ try (Response response = target(ITEM).request().get()) {
+ assertDomain(response, Domain.Status.DRAFT);
+ }
+ }
+
+ @Test
+ public void testEmptyLists() {
+ when(dispatcher.listDomains("test")).thenReturn(new String[0]);
+ when(dispatcher.listDomainInfos("test")).thenReturn(new DomainEntity[0]);
+ when(dispatcher.listSubdomains("test", "Finance")).thenReturn(new String[0]);
+ when(dispatcher.listSubdomainInfos("test", "Finance")).thenReturn(new DomainEntity[0]);
+ for (String path : new String[] {BASE, ITEM + "/subdomains"}) {
+ try (Response response = target(path).request().get()) {
+ assertEquals(0, response.readEntity(NameListResponse.class).getNames().length);
+ }
+ try (Response response = target(path).queryParam("details", true).request().get()) {
+ assertEquals(0, response.readEntity(DomainListResponse.class).getDomains().length);
+ }
+ }
+ }
+
+ @Test
+ public void testCreateWithNewTag() {
+ when(dispatcher.createDomain(
+ "test",
+ "Finance",
+ "comment",
+ Map.of("key", "value"),
+ TagValue.noValue("department"),
+ true))
+ .thenReturn(domain(Domain.Status.DRAFT));
+ try (Response response =
+ send(
+ "POST",
+ BASE,
+ "{\"name\":\"Finance\",\"comment\":\"comment\",\"properties\":{\"key\":\"value\"},\"backingTag\":{\"name\":\"department\",\"create\":true}}")) {
+ assertDomain(response, Domain.Status.DRAFT);
+ }
+ verify(dispatcher)
+ .createDomain(
+ "test",
+ "Finance",
+ "comment",
+ Map.of("key", "value"),
+ TagValue.noValue("department"),
+ true);
+ }
+
+ @Test
+ public void testCreateSubdomainWithExistingValuedTag() {
+ when(dispatcher.createSubdomain(
+ "test", "Parent", "Finance", null, null, TagValue.of("department", "finance"), false))
+ .thenReturn(domain(Domain.Status.DRAFT));
+ try (Response response =
+ send(
+ "POST",
+ BASE,
+ "{\"name\":\"Finance\",\"parent\":\"Parent\",\"backingTag\":{\"name\":\"department\",\"value\":\"finance\"}}")) {
+ assertDomain(response, Domain.Status.DRAFT);
+ }
+ verify(dispatcher)
+ .createSubdomain(
+ "test", "Parent", "Finance", null, null, TagValue.of("department", "finance"), false);
+ }
+
+ @Test
+ public void testAlter() {
+ DomainChange[] changes = {
+ DomainChange.rename("New"),
+ DomainChange.updateComment(null),
+ DomainChange.setProperty("key", ""),
+ DomainChange.removeProperty("old")
+ };
+ when(dispatcher.alterDomain("test", "Finance", changes))
+ .thenReturn(domain(Domain.Status.DRAFT));
+ try (Response response =
+ send(
+ "PUT",
+ ITEM,
+ "{\"updates\":[{\"@type\":\"rename\",\"newName\":\"New\"},"
+ + "{\"@type\":\"updateComment\",\"newComment\":null},{\"@type\":\"setProperty\",\"property\":\"key\",\"value\":\"\"},"
+ + "{\"@type\":\"removeProperty\",\"property\":\"old\"}]}")) {
+ assertDomain(response, Domain.Status.DRAFT);
+ }
+ verify(dispatcher).alterDomain("test", "Finance", changes);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"DRAFT", "PUBLISHED"})
+ public void testStatus(String status) {
+ when(dispatcher.publishDomain("test", "Finance")).thenReturn(domain(Domain.Status.PUBLISHED));
+ when(dispatcher.unpublishDomain("test", "Finance")).thenReturn(domain(Domain.Status.DRAFT));
+ try (Response response = send("PATCH", ITEM, "{\"status\":\"" + status + "\"}")) {
+ assertDomain(response, Domain.Status.valueOf(status));
+ }
+ if (status.equals("PUBLISHED")) {
+ verify(dispatcher).publishDomain("test", "Finance");
+ } else {
+ verify(dispatcher).unpublishDomain("test", "Finance");
+ }
+ }
+
+ @Test
+ public void testParentAndBackingTag() {
+ when(dispatcher.attachDomain("test", "Finance", "Parent"))
+ .thenReturn(domain(Domain.Status.DRAFT));
+ when(dispatcher.detachDomain("test", "Finance")).thenReturn(domain(Domain.Status.DRAFT));
+ when(dispatcher.updateBackingTag(eq("test"), eq("Finance"), any()))
+ .thenReturn(domain(Domain.Status.DRAFT));
+ when(dispatcher.updateBackingTag("test", "Finance", null))
+ .thenReturn(domain(Domain.Status.DRAFT));
+ try (Response response = send("PUT", ITEM + "/parent", "{\"parent\":\"Parent\"}")) {
+ assertDomain(response, Domain.Status.DRAFT);
+ }
+ try (Response response = target(ITEM + "/parent").request().delete()) {
+ assertDomain(response, Domain.Status.DRAFT);
+ }
+ try (Response response =
+ send(
+ "PUT",
+ ITEM + "/backingTag",
+ "{\"backingTag\":{\"name\":\"department\",\"value\":\"finance\"}}")) {
+ assertDomain(response, Domain.Status.DRAFT);
+ }
+ try (Response response = send("PUT", ITEM + "/backingTag", "{\"backingTag\":null}")) {
+ assertDomain(response, Domain.Status.DRAFT);
+ }
+ verify(dispatcher).attachDomain("test", "Finance", "Parent");
+ verify(dispatcher).detachDomain("test", "Finance");
+ verify(dispatcher).updateBackingTag("test", "Finance", TagValue.of("department", "finance"));
+ verify(dispatcher).updateBackingTag("test", "Finance", null);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ public void testDelete(boolean deleted) {
+ when(dispatcher.deleteDomain("test", "Finance")).thenReturn(deleted);
+ try (Response response = target(ITEM).request().delete()) {
+ assertEquals(200, response.getStatus());
+ assertEquals(deleted, response.readEntity(DropResponse.class).dropped());
+ }
+ }
+
+ @Test
+ public void testNullBodies() {
+ for (String[] route :
+ new String[][] {
+ {"POST", BASE},
+ {"PUT", ITEM},
+ {"PATCH", ITEM},
+ {"PUT", ITEM + "/parent"},
+ {"PUT", ITEM + "/backingTag"}
+ }) {
+ try (Response response = send(route[0], route[1], "null")) {
+ assertNullRequestBodyRejected(response);
+ }
+ }
+ verifyNoInteractions(dispatcher);
+ }
+
+ @Test
+ public void testInvalidBodies() {
+ for (String json :
+ new String[] {
+ "{}",
+ "{\"name\":\"Finance\"}",
+ "{\"name\":\"Finance\",\"parent\":\" \",\"backingTag\":{\"name\":\"t\"}}",
+ "{\"name\":\"Finance\",\"backingTag\":{\"name\":\"t\",\"value\":\"v\",\"create\":true}}"
+ }) {
+ try (Response response = send("POST", BASE, json)) {
+ assertError(response, 400);
+ }
+ }
+ for (String json :
+ new String[] {
+ "{}",
+ "{\"updates\":[null]}",
+ "{\"updates\":[{\"@type\":\"rename\",\"newName\":\" \"}]}",
+ "{\"updates\":[{\"@type\":\"unknown\"}]}"
+ }) {
+ try (Response response = send("PUT", ITEM, json)) {
+ assertError(response, 400);
+ }
+ }
+ for (String json : new String[] {"{}", "{\"status\":\"UNKNOWN\"}"}) {
+ try (Response response = send("PATCH", ITEM, json)) {
+ assertError(response, 400);
+ }
+ }
+ try (Response response = send("PUT", ITEM + "/parent", "{\"parent\":\" \"}")) {
+ assertError(response, 400);
+ }
+ try (Response response =
+ send("PUT", ITEM + "/backingTag", "{\"backingTag\":{\"name\":\" \"}}")) {
+ assertError(response, 400);
+ }
+ verifyNoInteractions(dispatcher);
+ }
+
+ @Test
+ public void testErrors() {
+ for (RuntimeException error :
+ new RuntimeException[] {
+ new DomainAlreadyExistsException("duplicate"),
+ new TagAlreadyExistsException("duplicate"),
+ new BackingTagAlreadyBoundException("bound")
+ }) {
+ when(dispatcher.createDomain(eq("test"), eq("Finance"), isNull(), isNull(), any(), eq(false)))
+ .thenThrow(error);
+ try (Response response =
+ send("POST", BASE, "{\"name\":\"Finance\",\"backingTag\":{\"name\":\"t\"}}")) {
+ assertError(response, 409);
+ }
+ }
+ when(dispatcher.deleteDomain("test", "Finance"))
+ .thenThrow(new NonEmptyDomainException("has children"));
+ try (Response response = target(ITEM).request().delete()) {
+ assertEquals(409, response.getStatus());
+ assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType());
+ ErrorResponse error = response.readEntity(ErrorResponse.class);
+ assertEquals(ErrorConstants.NON_EMPTY_CODE, error.getCode());
+ assertEquals(NonEmptyDomainException.class.getSimpleName(), error.getType());
+ }
+ when(dispatcher.getDomain("test", "Finance")).thenThrow(new NoSuchDomainException("missing"));
+ try (Response response = target(ITEM).request().get()) {
+ assertError(response, 404);
+ }
+ when(dispatcher.updateBackingTag(eq("test"), eq("Finance"), any()))
+ .thenThrow(new NoSuchTagException("missing tag"));
+ try (Response response =
+ send("PUT", ITEM + "/backingTag", "{\"backingTag\":{\"name\":\"t\"}}")) {
+ assertError(response, 404);
+ }
+ when(dispatcher.publishDomain("test", "Finance"))
+ .thenThrow(new IllegalArgumentException("draft parent"));
+ try (Response response = send("PATCH", ITEM, "{\"status\":\"PUBLISHED\"}")) {
+ assertError(response, 400);
+ }
+ }
+
+ @Test
+ public void testInactiveMetalake() {
+ when(dispatcher.listDomains("test")).thenThrow(new MetalakeNotInUseException("disabled"));
+ try (Response response = target(BASE).request().get()) {
+ assertEquals(409, response.getStatus());
+ assertEquals("MetalakeNotInUseException", response.readEntity(ErrorResponse.class).getType());
+ }
+ }
+
+ @Test
+ public void testEncodedDomainName() {
+ when(dispatcher.getDomain("test", "Finance/US")).thenReturn(domain(Domain.Status.DRAFT));
+ try (Response response =
+ target(BASE + "/{domain}").resolveTemplate("domain", "Finance/US").request().get()) {
+ assertDomain(response, Domain.Status.DRAFT);
+ }
+ verify(dispatcher).getDomain("test", "Finance/US");
+ }
+
+ @Test
+ public void testProductionJsonRepresentation() throws IOException {
+ when(dispatcher.getDomain("test", "Finance")).thenReturn(domain(Domain.Status.DRAFT));
+ try (Response response = target(ITEM).request().get()) {
+ assertEquals(200, response.getStatus());
+ JsonNode snapshot =
+ JsonUtils.objectMapper().readTree(response.readEntity(String.class)).get("domain");
+ assertEquals("draft", snapshot.get("status").asText());
+ assertFalse(snapshot.has("relations"));
+ assertFalse(snapshot.has("comment"));
+ assertFalse(snapshot.get("audit").has("lastModifier"));
+ }
+ }
+
+ @Test
+ public void testMissingBackingTagFieldDoesNotRemoveBinding() {
+ for (String json : new String[] {"{}", "{\"backing_tag\":null}"}) {
+ try (Response response = send("PUT", ITEM + "/backingTag", json)) {
+ assertError(response, 400);
+ }
+ }
+ verifyNoInteractions(dispatcher);
+ }
+
+ @Test
+ public void testProductionSerializationPreservesExplicitRemoval() throws IOException {
+ DomainBackingTagSetRequest request = new DomainBackingTagSetRequest(null);
+ when(dispatcher.updateBackingTag("test", "Finance", null))
+ .thenReturn(domain(Domain.Status.DRAFT));
+ try (Response response =
+ send(
+ "PUT",
+ ITEM + "/backingTag",
+ ObjectMapperProvider.objectMapper().writeValueAsString(request))) {
+ assertDomain(response, Domain.Status.DRAFT);
+ }
+ verify(dispatcher).updateBackingTag("test", "Finance", null);
+ }
+
+ private Response send(String method, String path, String json) {
+ return target(path)
+ .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true)
+ .request()
+ .method(method, Entity.json(json));
+ }
+
+ private static DomainEntity domain(Domain.Status status) {
+ return DomainEntity.builder()
+ .withId(1L)
+ .withName("Finance")
+ .withNamespace(Namespace.of("test"))
+ .withProperties(Map.of())
+ .withStatus(status)
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("user").withCreateTime(Instant.now()).build())
+ .build();
+ }
+
+ private static void assertDomain(Response response, Domain.Status status) {
+ assertEquals(200, response.getStatus());
+ DomainResponse result = response.readEntity(DomainResponse.class);
+ result.validate();
+ assertEquals("Finance", result.getDomain().getName());
+ assertEquals(status, result.getDomain().getStatus());
+ assertEquals(0, result.getDomain().getRelations().length);
+ }
+
+ private static void assertError(Response response, int status) {
+ assertEquals(status, response.getStatus());
+ assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType());
+ assertTrue(response.readEntity(ErrorResponse.class).getCode() > 0);
+ }
+}