yuqi1129 commented on code in PR #7842:
URL: https://github.com/apache/gravitino/pull/7842#discussion_r2262379663


##########
common/src/main/java/org/apache/gravitino/dto/requests/PoliciesAssociateRequest.java:
##########
@@ -0,0 +1,84 @@
+/*
+ * 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.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.rest.RESTRequest;
+
+/** Represents a request to associate policies. */
+@Getter
+@EqualsAndHashCode
+@ToString
+public class PoliciesAssociateRequest implements RESTRequest {
+
+  @JsonProperty("policiesToAdd")
+  private final String[] policiesToAdd;
+
+  @JsonProperty("policiesToRemove")
+  private final String[] policiesToRemove;
+
+  /**
+   * Creates a new PoliciesAssociateRequest.
+   *
+   * @param policiesToAdd The policies to add.
+   * @param policiesToRemove The policies to remove.
+   */
+  public PoliciesAssociateRequest(String[] policiesToAdd, String[] 
policiesToRemove) {
+    this.policiesToAdd = policiesToAdd;
+    this.policiesToRemove = policiesToRemove;
+  }
+
+  /** This is the constructor that is used by Jackson deserializer */
+  private PoliciesAssociateRequest() {
+    this(null, null);
+  }
+
+  /**
+   * Validates the request.
+   *
+   * @throws IllegalArgumentException If the request is invalid, this 
exception is thrown.
+   */
+  @Override
+  public void validate() throws IllegalArgumentException {
+    Preconditions.checkArgument(
+        policiesToAdd != null || policiesToRemove != null,
+        "policiesToAdd and policiesToRemove cannot both be null");
+
+    if (policiesToAdd != null) {
+      for (String Policy : policiesToAdd) {
+        Preconditions.checkArgument(
+            StringUtils.isNotBlank(Policy),
+            "policiesToAdd must not contain null or empty Policy names");

Review Comment:
   `Policy` should not be capitalized unless it's a technical term.



##########
server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * 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.HashSet;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Set;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+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.commons.lang3.ArrayUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.dto.policy.PolicyDTO;
+import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;
+import org.apache.gravitino.dto.responses.NameListResponse;
+import org.apache.gravitino.dto.responses.PolicyListResponse;
+import org.apache.gravitino.dto.responses.PolicyResponse;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.exceptions.NoSuchPolicyException;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyDispatcher;
+import org.apache.gravitino.server.web.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Path("/metalakes/{metalake}/objects/{type}/{fullName}/policies")
+public class MetadataObjectPolicyOperations {
+  private static final Logger LOG = 
LoggerFactory.getLogger(MetadataObjectPolicyOperations.class);
+
+  private final PolicyDispatcher policyDispatcher;
+
+  @Context private HttpServletRequest httpRequest;
+
+  @Inject
+  public MetadataObjectPolicyOperations(PolicyDispatcher policyDispatcher) {
+    this.policyDispatcher = policyDispatcher;
+  }
+
+  @GET
+  @Path("{policy}")
+  @Produces("application/vnd.gravitino.v1+json")
+  @Timed(name = "get-object-policy." + MetricNames.HTTP_PROCESS_DURATION, 
absolute = true)
+  @ResponseMetered(name = "get-object-policy", absolute = true)
+  public Response getPolicyForObject(
+      @PathParam("metalake") String metalake,
+      @PathParam("type") String type,
+      @PathParam("fullName") String fullName,
+      @PathParam("policy") String policyName) {
+    LOG.info(
+        "Received get policy {} request for object type: {}, full name: {} 
under metalake: {}",
+        policyName,
+        type,
+        fullName,
+        metalake);
+
+    try {
+      return Utils.doAs(
+          httpRequest,
+          () -> {
+            MetadataObject object =
+                MetadataObjects.parse(
+                    fullName, 
MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
+            Optional<Policy> policy = getPolicyForObject(metalake, object, 
policyName);
+
+            if (policy.isPresent()) {
+              LOG.info(
+                  "Get policy: {} for object type: {}, full name: {} under 
metalake: {}",
+                  policyName,
+                  type,
+                  fullName,
+                  metalake);
+              return Utils.ok(
+                  new PolicyResponse(DTOConverters.toDTO(policy.get(), 
Optional.of(false))));
+            }
+
+            // ensure the policy exists and is inheritable
+            Policy targetPolicy = policyDispatcher.getPolicy(metalake, 
policyName);
+            if (!targetPolicy.inheritable()
+                || 
!targetPolicy.supportedObjectTypes().contains(object.type())) {
+              return logNotFoundPolicy(metalake, policyName, type, fullName);

Review Comment:
   The name `logNotFoundPolicy` is not very proper, based on the code, it can 
be `getResponseAndLogNotFoundPolicy`, you can simplify it as you like. 



##########
server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * 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.HashSet;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Set;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+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.commons.lang3.ArrayUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.dto.policy.PolicyDTO;
+import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;
+import org.apache.gravitino.dto.responses.NameListResponse;
+import org.apache.gravitino.dto.responses.PolicyListResponse;
+import org.apache.gravitino.dto.responses.PolicyResponse;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.exceptions.NoSuchPolicyException;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyDispatcher;
+import org.apache.gravitino.server.web.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Path("/metalakes/{metalake}/objects/{type}/{fullName}/policies")
+public class MetadataObjectPolicyOperations {
+  private static final Logger LOG = 
LoggerFactory.getLogger(MetadataObjectPolicyOperations.class);
+
+  private final PolicyDispatcher policyDispatcher;
+
+  @Context private HttpServletRequest httpRequest;
+
+  @Inject
+  public MetadataObjectPolicyOperations(PolicyDispatcher policyDispatcher) {
+    this.policyDispatcher = policyDispatcher;
+  }
+
+  @GET
+  @Path("{policy}")
+  @Produces("application/vnd.gravitino.v1+json")
+  @Timed(name = "get-object-policy." + MetricNames.HTTP_PROCESS_DURATION, 
absolute = true)
+  @ResponseMetered(name = "get-object-policy", absolute = true)
+  public Response getPolicyForObject(
+      @PathParam("metalake") String metalake,
+      @PathParam("type") String type,
+      @PathParam("fullName") String fullName,
+      @PathParam("policy") String policyName) {
+    LOG.info(
+        "Received get policy {} request for object type: {}, full name: {} 
under metalake: {}",
+        policyName,
+        type,
+        fullName,
+        metalake);
+
+    try {
+      return Utils.doAs(
+          httpRequest,
+          () -> {
+            MetadataObject object =
+                MetadataObjects.parse(
+                    fullName, 
MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
+            Optional<Policy> policy = getPolicyForObject(metalake, object, 
policyName);
+
+            if (policy.isPresent()) {
+              LOG.info(
+                  "Get policy: {} for object type: {}, full name: {} under 
metalake: {}",
+                  policyName,
+                  type,
+                  fullName,
+                  metalake);
+              return Utils.ok(
+                  new PolicyResponse(DTOConverters.toDTO(policy.get(), 
Optional.of(false))));
+            }
+
+            // ensure the policy exists and is inheritable
+            Policy targetPolicy = policyDispatcher.getPolicy(metalake, 
policyName);

Review Comment:
   What if `targetPolicy` does not exist here? Does it throw an exception 
directly?



##########
server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * 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.HashSet;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Set;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+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.commons.lang3.ArrayUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.dto.policy.PolicyDTO;
+import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;
+import org.apache.gravitino.dto.responses.NameListResponse;
+import org.apache.gravitino.dto.responses.PolicyListResponse;
+import org.apache.gravitino.dto.responses.PolicyResponse;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.exceptions.NoSuchPolicyException;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyDispatcher;
+import org.apache.gravitino.server.web.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Path("/metalakes/{metalake}/objects/{type}/{fullName}/policies")
+public class MetadataObjectPolicyOperations {
+  private static final Logger LOG = 
LoggerFactory.getLogger(MetadataObjectPolicyOperations.class);
+
+  private final PolicyDispatcher policyDispatcher;
+
+  @Context private HttpServletRequest httpRequest;
+
+  @Inject
+  public MetadataObjectPolicyOperations(PolicyDispatcher policyDispatcher) {
+    this.policyDispatcher = policyDispatcher;
+  }
+
+  @GET
+  @Path("{policy}")
+  @Produces("application/vnd.gravitino.v1+json")
+  @Timed(name = "get-object-policy." + MetricNames.HTTP_PROCESS_DURATION, 
absolute = true)
+  @ResponseMetered(name = "get-object-policy", absolute = true)
+  public Response getPolicyForObject(
+      @PathParam("metalake") String metalake,
+      @PathParam("type") String type,
+      @PathParam("fullName") String fullName,
+      @PathParam("policy") String policyName) {
+    LOG.info(
+        "Received get policy {} request for object type: {}, full name: {} 
under metalake: {}",
+        policyName,
+        type,
+        fullName,
+        metalake);
+
+    try {
+      return Utils.doAs(
+          httpRequest,
+          () -> {
+            MetadataObject object =
+                MetadataObjects.parse(
+                    fullName, 
MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
+            Optional<Policy> policy = getPolicyForObject(metalake, object, 
policyName);
+
+            if (policy.isPresent()) {
+              LOG.info(
+                  "Get policy: {} for object type: {}, full name: {} under 
metalake: {}",
+                  policyName,
+                  type,
+                  fullName,
+                  metalake);
+              return Utils.ok(
+                  new PolicyResponse(DTOConverters.toDTO(policy.get(), 
Optional.of(false))));
+            }
+
+            // ensure the policy exists and is inheritable
+            Policy targetPolicy = policyDispatcher.getPolicy(metalake, 
policyName);
+            if (!targetPolicy.inheritable()
+                || 
!targetPolicy.supportedObjectTypes().contains(object.type())) {
+              return logNotFoundPolicy(metalake, policyName, type, fullName);
+            }
+
+            if (hasConflictExclusivePolicy(metalake, object, targetPolicy)) {
+              return logNotFoundPolicy(metalake, policyName, type, fullName);
+            }
+
+            MetadataObject parentObject = MetadataObjects.parent(object);
+            while (parentObject != null) {
+              if 
(!targetPolicy.supportedObjectTypes().contains(parentObject.type())) {
+                // If the parent object type is not supported by the target 
policy, we skip it.
+                parentObject = MetadataObjects.parent(parentObject);
+                continue;
+              }
+
+              Policy[] parentPolicies =
+                  policyDispatcher.listPolicyInfosForMetadataObject(metalake, 
parentObject);
+              if (hasConflictExclusivePolicy(parentPolicies, targetPolicy)) {
+                // If another same type exclusive policy is found, it means 
the target policy will
+                // be replaced by the same type policy
+                return logNotFoundPolicy(metalake, policyName, type, fullName);
+              }
+
+              Optional<Policy> inheritedPolicy =
+                  ArrayUtils.isEmpty(parentPolicies)
+                      ? Optional.empty()
+                      : Arrays.stream(parentPolicies)
+                          .filter(p -> p.name().equals(policyName))
+                          .findFirst();
+              if (inheritedPolicy.isPresent()) {
+                // If the policy is found in parent object, we convert it to 
DTO and return.
+                LOG.info(
+                    "Found policy: {} for object type: {}, full name: {} under 
metalake: {}",
+                    policyName,
+                    type,
+                    fullName,
+                    metalake);
+                return Utils.ok(
+                    new PolicyResponse(
+                        DTOConverters.toDTO(inheritedPolicy.get(), 
Optional.of(true))));
+              }
+
+              parentObject = MetadataObjects.parent(parentObject);
+            }
+
+            return logNotFoundPolicy(metalake, policyName, type, fullName);
+          });
+
+    } catch (Exception e) {
+      return ExceptionHandlers.handlePolicyException(OperationType.GET, 
policyName, fullName, e);
+    }
+  }
+
+  @GET
+  @Produces("application/vnd.gravitino.v1+json")
+  @Timed(name = "list-object-policies." + MetricNames.HTTP_PROCESS_DURATION, 
absolute = true)
+  @ResponseMetered(name = "list-object-policies", absolute = true)
+  public Response listPoliciesForMetadataObject(
+      @PathParam("metalake") String metalake,
+      @PathParam("type") String type,
+      @PathParam("fullName") String fullName,
+      @QueryParam("details") @DefaultValue("false") boolean verbose) {
+    LOG.info(
+        "Received list policy {} request for object type: {}, full name: {} 
under metalake: {}",
+        verbose ? "infos" : "names",
+        type,
+        fullName,
+        metalake);
+
+    try {
+      return Utils.doAs(
+          httpRequest,
+          () -> {
+            MetadataObject object =
+                MetadataObjects.parse(
+                    fullName, 
MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
+
+            Set<PolicyDTO> policies = new HashSet<>();
+            Set<String> exclusivePolicyTypes = new HashSet<>();
+            Policy[] nonInheritedPolicies =
+                policyDispatcher.listPolicyInfosForMetadataObject(metalake, 
object);
+            for (Policy policy : nonInheritedPolicies) {
+              if (policy.exclusive()) {

Review Comment:
   Do we check the property `exclusive`  in the association operation? Why do 
we need to check it again?



##########
server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * 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.HashSet;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Set;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+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.commons.lang3.ArrayUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.dto.policy.PolicyDTO;
+import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;
+import org.apache.gravitino.dto.responses.NameListResponse;
+import org.apache.gravitino.dto.responses.PolicyListResponse;
+import org.apache.gravitino.dto.responses.PolicyResponse;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.exceptions.NoSuchPolicyException;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyDispatcher;
+import org.apache.gravitino.server.web.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Path("/metalakes/{metalake}/objects/{type}/{fullName}/policies")
+public class MetadataObjectPolicyOperations {
+  private static final Logger LOG = 
LoggerFactory.getLogger(MetadataObjectPolicyOperations.class);
+
+  private final PolicyDispatcher policyDispatcher;
+
+  @Context private HttpServletRequest httpRequest;
+
+  @Inject
+  public MetadataObjectPolicyOperations(PolicyDispatcher policyDispatcher) {
+    this.policyDispatcher = policyDispatcher;
+  }
+
+  @GET
+  @Path("{policy}")
+  @Produces("application/vnd.gravitino.v1+json")
+  @Timed(name = "get-object-policy." + MetricNames.HTTP_PROCESS_DURATION, 
absolute = true)
+  @ResponseMetered(name = "get-object-policy", absolute = true)
+  public Response getPolicyForObject(
+      @PathParam("metalake") String metalake,
+      @PathParam("type") String type,
+      @PathParam("fullName") String fullName,
+      @PathParam("policy") String policyName) {
+    LOG.info(
+        "Received get policy {} request for object type: {}, full name: {} 
under metalake: {}",
+        policyName,
+        type,
+        fullName,
+        metalake);
+
+    try {
+      return Utils.doAs(
+          httpRequest,
+          () -> {
+            MetadataObject object =
+                MetadataObjects.parse(
+                    fullName, 
MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
+            Optional<Policy> policy = getPolicyForObject(metalake, object, 
policyName);
+
+            if (policy.isPresent()) {
+              LOG.info(
+                  "Get policy: {} for object type: {}, full name: {} under 
metalake: {}",
+                  policyName,
+                  type,
+                  fullName,
+                  metalake);
+              return Utils.ok(
+                  new PolicyResponse(DTOConverters.toDTO(policy.get(), 
Optional.of(false))));
+            }
+
+            // ensure the policy exists and is inheritable
+            Policy targetPolicy = policyDispatcher.getPolicy(metalake, 
policyName);
+            if (!targetPolicy.inheritable()
+                || 
!targetPolicy.supportedObjectTypes().contains(object.type())) {
+              return logNotFoundPolicy(metalake, policyName, type, fullName);
+            }
+
+            if (hasConflictExclusivePolicy(metalake, object, targetPolicy)) {
+              return logNotFoundPolicy(metalake, policyName, type, fullName);
+            }
+
+            MetadataObject parentObject = MetadataObjects.parent(object);
+            while (parentObject != null) {
+              if 
(!targetPolicy.supportedObjectTypes().contains(parentObject.type())) {
+                // If the parent object type is not supported by the target 
policy, we skip it.
+                parentObject = MetadataObjects.parent(parentObject);
+                continue;
+              }
+
+              Policy[] parentPolicies =
+                  policyDispatcher.listPolicyInfosForMetadataObject(metalake, 
parentObject);
+              if (hasConflictExclusivePolicy(parentPolicies, targetPolicy)) {
+                // If another same type exclusive policy is found, it means 
the target policy will
+                // be replaced by the same type policy
+                return logNotFoundPolicy(metalake, policyName, type, fullName);
+              }
+
+              Optional<Policy> inheritedPolicy =
+                  ArrayUtils.isEmpty(parentPolicies)
+                      ? Optional.empty()
+                      : Arrays.stream(parentPolicies)
+                          .filter(p -> p.name().equals(policyName))
+                          .findFirst();
+              if (inheritedPolicy.isPresent()) {
+                // If the policy is found in parent object, we convert it to 
DTO and return.
+                LOG.info(
+                    "Found policy: {} for object type: {}, full name: {} under 
metalake: {}",
+                    policyName,
+                    type,
+                    fullName,
+                    metalake);
+                return Utils.ok(
+                    new PolicyResponse(
+                        DTOConverters.toDTO(inheritedPolicy.get(), 
Optional.of(true))));
+              }
+
+              parentObject = MetadataObjects.parent(parentObject);
+            }
+
+            return logNotFoundPolicy(metalake, policyName, type, fullName);
+          });
+
+    } catch (Exception e) {
+      return ExceptionHandlers.handlePolicyException(OperationType.GET, 
policyName, fullName, e);
+    }
+  }
+
+  @GET
+  @Produces("application/vnd.gravitino.v1+json")
+  @Timed(name = "list-object-policies." + MetricNames.HTTP_PROCESS_DURATION, 
absolute = true)
+  @ResponseMetered(name = "list-object-policies", absolute = true)
+  public Response listPoliciesForMetadataObject(
+      @PathParam("metalake") String metalake,
+      @PathParam("type") String type,
+      @PathParam("fullName") String fullName,
+      @QueryParam("details") @DefaultValue("false") boolean verbose) {
+    LOG.info(
+        "Received list policy {} request for object type: {}, full name: {} 
under metalake: {}",
+        verbose ? "infos" : "names",
+        type,
+        fullName,
+        metalake);
+
+    try {
+      return Utils.doAs(
+          httpRequest,
+          () -> {
+            MetadataObject object =
+                MetadataObjects.parse(
+                    fullName, 
MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
+
+            Set<PolicyDTO> policies = new HashSet<>();
+            Set<String> exclusivePolicyTypes = new HashSet<>();
+            Policy[] nonInheritedPolicies =
+                policyDispatcher.listPolicyInfosForMetadataObject(metalake, 
object);
+            for (Policy policy : nonInheritedPolicies) {
+              if (policy.exclusive()) {
+                exclusivePolicyTypes.add(policy.policyType());
+              }
+              policies.add(DTOConverters.toDTO(policy, Optional.of(false)));
+            }
+
+            MetadataObject parentObject = MetadataObjects.parent(object);
+            while (parentObject != null) {
+              Policy[] inheritedPolicies =
+                  policyDispatcher.listPolicyInfosForMetadataObject(metalake, 
parentObject);
+              for (Policy policy : inheritedPolicies) {
+                if (!policy.supportedObjectTypes().contains(object.type())
+                    || !policy.inheritable()) {
+                  // If the policy is not inheritable or does not support the 
object type,
+                  // we skip it.
+                  continue;
+                }
+                if (policy.exclusive()) {
+                  if (exclusivePolicyTypes.contains(policy.policyType())) {
+                    // If the policy is exclusive and already exists in the 
child object, we skip
+                    // it.
+                    continue;
+                  }
+                  exclusivePolicyTypes.add(policy.policyType());
+                }
+                policies.add(DTOConverters.toDTO(policy, Optional.of(true)));
+              }
+              parentObject = MetadataObjects.parent(parentObject);
+            }
+
+            if (verbose) {
+              LOG.info(
+                  "List {} policies info for object type: {}, full name: {} 
under metalake: {}",
+                  policies.size(),
+                  type,
+                  fullName,
+                  metalake);
+              return Utils.ok(new PolicyListResponse(policies.toArray(new 
PolicyDTO[0])));
+
+            } else {
+              String[] policyNames = 
policies.stream().map(PolicyDTO::name).toArray(String[]::new);
+
+              LOG.info(
+                  "List {} policies for object type: {}, full name: {} under 
metalake: {}",
+                  policyNames.length,
+                  type,
+                  fullName,
+                  metalake);
+              return Utils.ok(new NameListResponse(policyNames));
+            }
+          });
+
+    } catch (Exception e) {
+      return ExceptionHandlers.handlePolicyException(OperationType.LIST, "", 
fullName, e);
+    }
+  }
+
+  @POST
+  @Produces("application/vnd.gravitino.v1+json")
+  @Timed(name = "associate-object-policies." + 
MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+  @ResponseMetered(name = "associate-object-policies", absolute = true)
+  public Response associatePoliciesForObject(
+      @PathParam("metalake") String metalake,
+      @PathParam("type") String type,
+      @PathParam("fullName") String fullName,
+      PoliciesAssociateRequest request) {
+    LOG.info(
+        "Received associate policies request for object type: {}, full name: 
{} under metalake: {}",
+        type,
+        fullName,
+        metalake);
+
+    try {
+      return Utils.doAs(
+          httpRequest,
+          () -> {
+            request.validate();
+            MetadataObject object =
+                MetadataObjects.parse(
+                    fullName, 
MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
+            String[] policyNames =
+                policyDispatcher.associatePoliciesForMetadataObject(
+                    metalake, object, request.getPoliciesToAdd(), 
request.getPoliciesToRemove());
+            policyNames = policyNames == null ? new String[0] : policyNames;
+
+            LOG.info(
+                "Associated policies: {} for object type: {}, full name: {} 
under metalake: {}",
+                Arrays.toString(policyNames),
+                type,
+                fullName,
+                metalake);
+            return Utils.ok(new NameListResponse(policyNames));
+          });
+
+    } catch (Exception e) {
+      return ExceptionHandlers.handlePolicyException(OperationType.ASSOCIATE, 
"", fullName, e);
+    }
+  }
+
+  private boolean hasConflictExclusivePolicy(
+      String metalake, MetadataObject object, Policy targetPolicy) {
+    if (!targetPolicy.exclusive()) {
+      return false;
+    }
+
+    Policy[] policies = 
policyDispatcher.listPolicyInfosForMetadataObject(metalake, object);
+    return Arrays.stream(policies)
+        .anyMatch(
+            p ->
+                p.exclusive()
+                    && 
p.policyType().equalsIgnoreCase(targetPolicy.policyType())
+                    && !p.name().equals(targetPolicy.name()));
+  }
+
+  private boolean hasConflictExclusivePolicy(Policy[] policies, Policy 
targetPolicy) {
+    if (!targetPolicy.exclusive() || ArrayUtils.isEmpty(policies)) {
+      return false;
+    }
+    return Arrays.stream(policies)
+        .anyMatch(
+            p ->
+                p.exclusive()
+                    && 
p.policyType().equalsIgnoreCase(targetPolicy.policyType())
+                    && !p.name().equals(targetPolicy.name()));
+  }
+
+  private Response logNotFoundPolicy(
+      String metalakeName, String policyName, String objectType, String 
fullName) {
+    LOG.warn(
+        "Policy {} not found for object type: {}, full name: {} under 
metalake: {}",
+        policyName,
+        objectType,
+        fullName,
+        metalakeName);
+    return Utils.notFound(
+        NoSuchPolicyException.class.getSimpleName(),
+        "Policy not found: "
+            + policyName
+            + " for object type: "
+            + objectType
+            + ", full name: "
+            + fullName
+            + " under metalake: "
+            + metalakeName);
+  }
+
+  private Optional<Policy> getPolicyForObject(
+      String metalake, MetadataObject object, String policyName) {
+    try {
+      return Optional.ofNullable(

Review Comment:
   Since it will throw a `NoSuchPolicyException`, why do you use `Optional` 
here?



##########
server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * 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.HashSet;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Set;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+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.commons.lang3.ArrayUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.dto.policy.PolicyDTO;
+import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;
+import org.apache.gravitino.dto.responses.NameListResponse;
+import org.apache.gravitino.dto.responses.PolicyListResponse;
+import org.apache.gravitino.dto.responses.PolicyResponse;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.exceptions.NoSuchPolicyException;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyDispatcher;
+import org.apache.gravitino.server.web.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Path("/metalakes/{metalake}/objects/{type}/{fullName}/policies")
+public class MetadataObjectPolicyOperations {
+  private static final Logger LOG = 
LoggerFactory.getLogger(MetadataObjectPolicyOperations.class);
+
+  private final PolicyDispatcher policyDispatcher;
+
+  @Context private HttpServletRequest httpRequest;
+
+  @Inject
+  public MetadataObjectPolicyOperations(PolicyDispatcher policyDispatcher) {
+    this.policyDispatcher = policyDispatcher;
+  }
+
+  @GET
+  @Path("{policy}")
+  @Produces("application/vnd.gravitino.v1+json")
+  @Timed(name = "get-object-policy." + MetricNames.HTTP_PROCESS_DURATION, 
absolute = true)
+  @ResponseMetered(name = "get-object-policy", absolute = true)
+  public Response getPolicyForObject(
+      @PathParam("metalake") String metalake,
+      @PathParam("type") String type,
+      @PathParam("fullName") String fullName,
+      @PathParam("policy") String policyName) {
+    LOG.info(
+        "Received get policy {} request for object type: {}, full name: {} 
under metalake: {}",
+        policyName,
+        type,
+        fullName,
+        metalake);
+
+    try {
+      return Utils.doAs(
+          httpRequest,
+          () -> {
+            MetadataObject object =
+                MetadataObjects.parse(
+                    fullName, 
MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
+            Optional<Policy> policy = getPolicyForObject(metalake, object, 
policyName);
+
+            if (policy.isPresent()) {
+              LOG.info(
+                  "Get policy: {} for object type: {}, full name: {} under 
metalake: {}",
+                  policyName,
+                  type,
+                  fullName,
+                  metalake);
+              return Utils.ok(
+                  new PolicyResponse(DTOConverters.toDTO(policy.get(), 
Optional.of(false))));
+            }
+
+            // ensure the policy exists and is inheritable
+            Policy targetPolicy = policyDispatcher.getPolicy(metalake, 
policyName);
+            if (!targetPolicy.inheritable()
+                || 
!targetPolicy.supportedObjectTypes().contains(object.type())) {
+              return logNotFoundPolicy(metalake, policyName, type, fullName);
+            }
+
+            if (hasConflictExclusivePolicy(metalake, object, targetPolicy)) {
+              return logNotFoundPolicy(metalake, policyName, type, fullName);
+            }
+
+            MetadataObject parentObject = MetadataObjects.parent(object);
+            while (parentObject != null) {
+              if 
(!targetPolicy.supportedObjectTypes().contains(parentObject.type())) {
+                // If the parent object type is not supported by the target 
policy, we skip it.
+                parentObject = MetadataObjects.parent(parentObject);
+                continue;
+              }
+
+              Policy[] parentPolicies =
+                  policyDispatcher.listPolicyInfosForMetadataObject(metalake, 
parentObject);
+              if (hasConflictExclusivePolicy(parentPolicies, targetPolicy)) {
+                // If another same type exclusive policy is found, it means 
the target policy will
+                // be replaced by the same type policy
+                return logNotFoundPolicy(metalake, policyName, type, fullName);
+              }
+
+              Optional<Policy> inheritedPolicy =
+                  ArrayUtils.isEmpty(parentPolicies)
+                      ? Optional.empty()
+                      : Arrays.stream(parentPolicies)
+                          .filter(p -> p.name().equals(policyName))
+                          .findFirst();
+              if (inheritedPolicy.isPresent()) {
+                // If the policy is found in parent object, we convert it to 
DTO and return.
+                LOG.info(
+                    "Found policy: {} for object type: {}, full name: {} under 
metalake: {}",
+                    policyName,
+                    type,
+                    fullName,
+                    metalake);
+                return Utils.ok(
+                    new PolicyResponse(
+                        DTOConverters.toDTO(inheritedPolicy.get(), 
Optional.of(true))));
+              }
+
+              parentObject = MetadataObjects.parent(parentObject);
+            }
+
+            return logNotFoundPolicy(metalake, policyName, type, fullName);
+          });
+
+    } catch (Exception e) {
+      return ExceptionHandlers.handlePolicyException(OperationType.GET, 
policyName, fullName, e);
+    }
+  }
+
+  @GET
+  @Produces("application/vnd.gravitino.v1+json")
+  @Timed(name = "list-object-policies." + MetricNames.HTTP_PROCESS_DURATION, 
absolute = true)
+  @ResponseMetered(name = "list-object-policies", absolute = true)
+  public Response listPoliciesForMetadataObject(
+      @PathParam("metalake") String metalake,
+      @PathParam("type") String type,
+      @PathParam("fullName") String fullName,
+      @QueryParam("details") @DefaultValue("false") boolean verbose) {
+    LOG.info(
+        "Received list policy {} request for object type: {}, full name: {} 
under metalake: {}",
+        verbose ? "infos" : "names",
+        type,
+        fullName,
+        metalake);
+
+    try {
+      return Utils.doAs(
+          httpRequest,
+          () -> {
+            MetadataObject object =
+                MetadataObjects.parse(
+                    fullName, 
MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
+
+            Set<PolicyDTO> policies = new HashSet<>();
+            Set<String> exclusivePolicyTypes = new HashSet<>();
+            Policy[] nonInheritedPolicies =
+                policyDispatcher.listPolicyInfosForMetadataObject(metalake, 
object);
+            for (Policy policy : nonInheritedPolicies) {
+              if (policy.exclusive()) {
+                exclusivePolicyTypes.add(policy.policyType());
+              }
+              policies.add(DTOConverters.toDTO(policy, Optional.of(false)));
+            }
+
+            MetadataObject parentObject = MetadataObjects.parent(object);
+            while (parentObject != null) {
+              Policy[] inheritedPolicies =
+                  policyDispatcher.listPolicyInfosForMetadataObject(metalake, 
parentObject);
+              for (Policy policy : inheritedPolicies) {
+                if (!policy.supportedObjectTypes().contains(object.type())
+                    || !policy.inheritable()) {
+                  // If the policy is not inheritable or does not support the 
object type,
+                  // we skip it.
+                  continue;
+                }
+                if (policy.exclusive()) {

Review Comment:
   ditto



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to