Skip to content

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

[#7146] feat(policy): java client supports policy operations (part-1) (#8117)

mchadesc5270dc829e5
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.java b/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.java
index 9721dabba2..e848466a89 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.client;
+import static org.apache.gravitino.dto.util.DTOConverters.toDTO;
import static org.apache.gravitino.dto.util.DTOConverters.toFunctionArg;
import java.util.Collection;
@@ -43,6 +44,7 @@ import org.apache.gravitino.dto.requests.FilesetUpdateRequest;
import org.apache.gravitino.dto.requests.MetalakeUpdateRequest;
import org.apache.gravitino.dto.requests.ModelUpdateRequest;
import org.apache.gravitino.dto.requests.ModelVersionUpdateRequest;
+import org.apache.gravitino.dto.requests.PolicyUpdateRequest;
import org.apache.gravitino.dto.requests.SchemaUpdateRequest;
import org.apache.gravitino.dto.requests.TableUpdateRequest;
import org.apache.gravitino.dto.requests.TagUpdateRequest;
@@ -54,6 +56,7 @@ import org.apache.gravitino.job.SparkJobTemplate;
import org.apache.gravitino.messaging.TopicChange;
import org.apache.gravitino.model.ModelChange;
import org.apache.gravitino.model.ModelVersionChange;
+import org.apache.gravitino.policy.PolicyChange;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.TableChange;
import org.apache.gravitino.rel.expressions.Expression;
@@ -366,6 +369,27 @@ class DTOConverters {
}
}
+ static PolicyUpdateRequest toPolicyUpdateRequest(PolicyChange change) {
+ if (change instanceof PolicyChange.RenamePolicy) {
+ return new PolicyUpdateRequest.RenamePolicyRequest(
+ ((PolicyChange.RenamePolicy) change).getNewName());
+
+ } else if (change instanceof PolicyChange.UpdatePolicyComment) {
+ return new PolicyUpdateRequest.UpdatePolicyCommentRequest(
+ ((PolicyChange.UpdatePolicyComment) change).getNewComment());
+
+ } else if (change instanceof PolicyChange.UpdateContent) {
+ PolicyChange.UpdateContent updateContent = (PolicyChange.UpdateContent) change;
+ String policyType = updateContent.getPolicyType();
+ return new PolicyUpdateRequest.UpdatePolicyContentRequest(
+ policyType, toDTO(updateContent.getContent()));
+
+ } else {
+ throw new IllegalArgumentException(
+ "Unknown change type: " + change.getClass().getSimpleName());
+ }
+ }
+
static ModelUpdateRequest toModelUpdateRequest(ModelChange change) {
if (change instanceof ModelChange.RenameModel) {
return new ModelUpdateRequest.RenameModelRequest(
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
index 787a654754..9cf57cd15f 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
@@ -55,6 +55,7 @@ import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.exceptions.NoSuchModelException;
import org.apache.gravitino.exceptions.NoSuchModelVersionException;
import org.apache.gravitino.exceptions.NoSuchPartitionException;
+import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NoSuchRoleException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NoSuchTableException;
@@ -67,6 +68,8 @@ import org.apache.gravitino.exceptions.NonEmptySchemaException;
import org.apache.gravitino.exceptions.NotFoundException;
import org.apache.gravitino.exceptions.NotInUseException;
import org.apache.gravitino.exceptions.PartitionAlreadyExistsException;
+import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
+import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;
import org.apache.gravitino.exceptions.RESTException;
import org.apache.gravitino.exceptions.RoleAlreadyExistsException;
import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
@@ -209,6 +212,15 @@ public class ErrorHandlers {
return TagErrorHandler.INSTANCE;
}
+ /**
+ * Creates an error handler specific to policy operations.
+ *
+ * @return A Consumer representing the policy error handler.
+ */
+ public static Consumer<ErrorResponse> policyErrorHandler() {
+ return PolicyErrorHandler.INSTANCE;
+ }
+
/**
* Creates an error handler specific to credential operations.
*
@@ -980,6 +992,52 @@ public class ErrorHandlers {
}
}
+ /** Error handler specific to policy operations. */
+ @SuppressWarnings("FormatStringAnnotation")
+ private static class PolicyErrorHandler extends RestErrorHandler {
+
+ private static final PolicyErrorHandler INSTANCE = new PolicyErrorHandler();
+
+ @Override
+ public void accept(ErrorResponse errorResponse) {
+ String errorMessage = formatErrorMessage(errorResponse);
+
+ switch (errorResponse.getCode()) {
+ case ErrorConstants.ILLEGAL_ARGUMENTS_CODE:
+ throw new IllegalArgumentException(errorMessage);
+
+ case ErrorConstants.NOT_FOUND_CODE:
+ if (errorResponse.getType().equals(NoSuchMetalakeException.class.getSimpleName())) {
+ throw new NoSuchMetalakeException(errorMessage);
+ } else if (errorResponse.getType().equals(NoSuchPolicyException.class.getSimpleName())) {
+ throw new NoSuchPolicyException(errorMessage);
+ } else {
+ throw new NotFoundException(errorMessage);
+ }
+
+ case ErrorConstants.ALREADY_EXISTS_CODE:
+ if (errorResponse.getType().equals(PolicyAlreadyExistsException.class.getSimpleName())) {
+ throw new PolicyAlreadyExistsException(errorMessage);
+ } else if (errorResponse
+ .getType()
+ .equals(PolicyAlreadyAssociatedException.class.getSimpleName())) {
+ throw new PolicyAlreadyAssociatedException(errorMessage);
+ } else {
+ throw new AlreadyExistsException(errorMessage);
+ }
+
+ case ErrorConstants.NOT_IN_USE_CODE:
+ throw new MetalakeNotInUseException(errorMessage);
+
+ case ErrorConstants.INTERNAL_ERROR_CODE:
+ throw new RuntimeException(errorMessage);
+
+ default:
+ super.accept(errorResponse);
+ }
+ }
+ }
+
/** Error handler specific to Owner operations. */
@SuppressWarnings("FormatStringAnnotation")
private static class OwnerErrorHandler extends RestErrorHandler {
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericPolicy.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericPolicy.java
new file mode 100644
index 0000000000..32510c30e0
--- /dev/null
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericPolicy.java
@@ -0,0 +1,118 @@
+/*
+ * 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.client;
+
+import java.util.Collections;
+import java.util.Optional;
+import org.apache.gravitino.Audit;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.dto.policy.PolicyDTO;
+import org.apache.gravitino.dto.responses.MetadataObjectListResponse;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyContent;
+import org.apache.gravitino.rest.RESTUtils;
+
+/** Represents a generic policy. */
+class GenericPolicy implements Policy, Policy.AssociatedObjects {
+
+ private final PolicyDTO policyDTO;
+
+ private final RESTClient restClient;
+
+ private final String metalake;
+
+ GenericPolicy(PolicyDTO policyDTO, RESTClient restClient, String metalake) {
+ this.policyDTO = policyDTO;
+ this.restClient = restClient;
+ this.metalake = metalake;
+ }
+
+ @Override
+ public String name() {
+ return policyDTO.name();
+ }
+
+ @Override
+ public String policyType() {
+ return policyDTO.policyType();
+ }
+
+ @Override
+ public String comment() {
+ return policyDTO.comment();
+ }
+
+ @Override
+ public boolean enabled() {
+ return policyDTO.enabled();
+ }
+
+ @Override
+ public PolicyContent content() {
+ return policyDTO.content();
+ }
+
+ @Override
+ public Optional<Boolean> inherited() {
+ return policyDTO.inherited();
+ }
+
+ @Override
+ public Audit auditInfo() {
+ return policyDTO.auditInfo();
+ }
+
+ @Override
+ public AssociatedObjects associatedObjects() {
+ return this;
+ }
+
+ @Override
+ public MetadataObject[] objects() {
+ MetadataObjectListResponse resp =
+ restClient.get(
+ String.format(
+ "api/metalakes/%s/policies/%s/objects",
+ RESTUtils.encodeString(metalake), RESTUtils.encodeString(name())),
+ MetadataObjectListResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.policyErrorHandler());
+
+ resp.validate();
+ return resp.getMetadataObjects();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (!(obj instanceof GenericPolicy)) {
+ return false;
+ }
+
+ GenericPolicy that = (GenericPolicy) obj;
+ return policyDTO.equals(that.policyDTO);
+ }
+
+ @Override
+ public int hashCode() {
+ return policyDTO.hashCode();
+ }
+}
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericTag.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericTag.java
index 19ca417b31..52bfc4db37 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericTag.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericTag.java
@@ -25,6 +25,7 @@ import org.apache.gravitino.Audit;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.dto.responses.MetadataObjectListResponse;
import org.apache.gravitino.dto.tag.TagDTO;
+import org.apache.gravitino.rest.RESTUtils;
import org.apache.gravitino.tag.Tag;
/** Represents a generic tag. */
@@ -76,7 +77,9 @@ class GenericTag implements Tag, Tag.AssociatedObjects {
public MetadataObject[] objects() {
MetadataObjectListResponse resp =
restClient.get(
- String.format("api/metalakes/%s/tags/%s/objects", metalake, name()),
+ String.format(
+ "api/metalakes/%s/tags/%s/objects",
+ RESTUtils.encodeString(metalake), RESTUtils.encodeString(name())),
MetadataObjectListResponse.class,
Collections.emptyMap(),
ErrorHandlers.tagErrorHandler());
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java
index c913ca071c..f22a334452 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java
@@ -49,17 +49,23 @@ import org.apache.gravitino.exceptions.NoSuchJobException;
import org.apache.gravitino.exceptions.NoSuchJobTemplateException;
import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NoSuchRoleException;
import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.NoSuchUserException;
import org.apache.gravitino.exceptions.NonEmptyEntityException;
import org.apache.gravitino.exceptions.NotFoundException;
+import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;
import org.apache.gravitino.exceptions.RoleAlreadyExistsException;
import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.exceptions.UserAlreadyExistsException;
import org.apache.gravitino.job.JobHandle;
import org.apache.gravitino.job.JobTemplate;
import org.apache.gravitino.job.SupportsJobs;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyChange;
+import org.apache.gravitino.policy.PolicyContent;
+import org.apache.gravitino.policy.PolicyOperations;
import org.apache.gravitino.tag.Tag;
import org.apache.gravitino.tag.TagChange;
import org.apache.gravitino.tag.TagOperations;
@@ -72,7 +78,7 @@ import org.apache.gravitino.tag.TagOperations;
* API.
*/
public class GravitinoClient extends GravitinoClientBase
- implements SupportsCatalogs, TagOperations, SupportsJobs {
+ implements SupportsCatalogs, TagOperations, SupportsJobs, PolicyOperations {
private final GravitinoMetalake metalake;
@@ -614,6 +620,49 @@ public class GravitinoClient extends GravitinoClientBase
return getMetalake().cancelJob(jobId);
}
+ @Override
+ public String[] listPolicies() throws NoSuchMetalakeException {
+ return getMetalake().listPolicies();
+ }
+
+ @Override
+ public Policy[] listPolicyInfos() throws NoSuchMetalakeException {
+ return getMetalake().listPolicyInfos();
+ }
+
+ @Override
+ public Policy getPolicy(String name) throws NoSuchPolicyException {
+ return getMetalake().getPolicy(name);
+ }
+
+ @Override
+ public Policy createPolicy(
+ String name, String type, String comment, boolean enabled, PolicyContent content)
+ throws PolicyAlreadyExistsException {
+ return getMetalake().createPolicy(name, type, comment, enabled, content);
+ }
+
+ @Override
+ public void enablePolicy(String name) throws NoSuchPolicyException {
+ getMetalake().enablePolicy(name);
+ }
+
+ @Override
+ public void disablePolicy(String name) throws NoSuchPolicyException {
+ getMetalake().disablePolicy(name);
+ }
+
+ @Override
+ public Policy alterPolicy(String name, PolicyChange... changes)
+ throws NoSuchPolicyException, IllegalArgumentException {
+ return getMetalake().alterPolicy(name, changes);
+ }
+
+ @Override
+ public boolean deletePolicy(String name) {
+ return getMetalake().deletePolicy(name);
+ }
+
/** Builder class for constructing a GravitinoClient. */
public static class ClientBuilder extends GravitinoClientBase.Builder<GravitinoClient> {
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
index efdb3fb627..bc193169be 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
@@ -18,6 +18,8 @@
*/
package org.apache.gravitino.client;
+import static org.apache.gravitino.dto.util.DTOConverters.toDTO;
+
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
@@ -55,6 +57,10 @@ import org.apache.gravitino.dto.requests.GroupAddRequest;
import org.apache.gravitino.dto.requests.JobRunRequest;
import org.apache.gravitino.dto.requests.JobTemplateRegisterRequest;
import org.apache.gravitino.dto.requests.OwnerSetRequest;
+import org.apache.gravitino.dto.requests.PolicyCreateRequest;
+import org.apache.gravitino.dto.requests.PolicySetRequest;
+import org.apache.gravitino.dto.requests.PolicyUpdateRequest;
+import org.apache.gravitino.dto.requests.PolicyUpdatesRequest;
import org.apache.gravitino.dto.requests.PrivilegeGrantRequest;
import org.apache.gravitino.dto.requests.PrivilegeRevokeRequest;
import org.apache.gravitino.dto.requests.RoleCreateRequest;
@@ -79,6 +85,8 @@ import org.apache.gravitino.dto.responses.JobTemplateListResponse;
import org.apache.gravitino.dto.responses.JobTemplateResponse;
import org.apache.gravitino.dto.responses.NameListResponse;
import org.apache.gravitino.dto.responses.OwnerResponse;
+import org.apache.gravitino.dto.responses.PolicyListResponse;
+import org.apache.gravitino.dto.responses.PolicyResponse;
import org.apache.gravitino.dto.responses.RemoveResponse;
import org.apache.gravitino.dto.responses.RoleResponse;
import org.apache.gravitino.dto.responses.SetResponse;
@@ -100,17 +108,23 @@ import org.apache.gravitino.exceptions.NoSuchJobException;
import org.apache.gravitino.exceptions.NoSuchJobTemplateException;
import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NoSuchRoleException;
import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.NoSuchUserException;
import org.apache.gravitino.exceptions.NonEmptyEntityException;
import org.apache.gravitino.exceptions.NotFoundException;
+import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;
import org.apache.gravitino.exceptions.RoleAlreadyExistsException;
import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.exceptions.UserAlreadyExistsException;
import org.apache.gravitino.job.JobHandle;
import org.apache.gravitino.job.JobTemplate;
import org.apache.gravitino.job.SupportsJobs;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyChange;
+import org.apache.gravitino.policy.PolicyContent;
+import org.apache.gravitino.policy.PolicyOperations;
import org.apache.gravitino.rest.RESTUtils;
import org.apache.gravitino.tag.Tag;
import org.apache.gravitino.tag.TagChange;
@@ -122,7 +136,7 @@ import org.apache.gravitino.tag.TagOperations;
* create, load, alter and drop a catalog with specified identifier.
*/
public class GravitinoMetalake extends MetalakeDTO
- implements SupportsCatalogs, TagOperations, SupportsRoles, SupportsJobs {
+ implements SupportsCatalogs, TagOperations, SupportsRoles, SupportsJobs, PolicyOperations {
private static final String API_METALAKES_CATALOGS_PATH = "api/metalakes/%s/catalogs/%s";
private static final String API_PERMISSION_PATH = "api/metalakes/%s/permissions/%s";
private static final String API_METALAKES_USERS_PATH = "api/metalakes/%s/users/%s";
@@ -132,6 +146,7 @@ public class GravitinoMetalake extends MetalakeDTO
private static final String API_METALAKES_TAGS_PATH = "api/metalakes/%s/tags";
private static final String API_METALAKES_JOB_TEMPLATES_PATH = "api/metalakes/%s/jobs/templates";
private static final String API_METALAKES_JOB_PATH = "api/metalakes/%s/jobs/runs";
+ private static final String API_METALAKES_POLICIES_PATH = "api/metalakes/%s/policies";
private static final String BLANK_PLACEHOLDER = "";
private final RESTClient restClient;
@@ -560,6 +575,184 @@ public class GravitinoMetalake extends MetalakeDTO
return resp.dropped();
}
+ /**
+ * List all the policies under the current metalake.
+ *
+ * @return A list of the policy names under the current metalake.
+ * @throws NoSuchMetalakeException If the metalake does not exist.
+ */
+ @Override
+ public String[] listPolicies() throws NoSuchMetalakeException {
+ NameListResponse resp =
+ restClient.get(
+ String.format(API_METALAKES_POLICIES_PATH, RESTUtils.encodeString(this.name())),
+ NameListResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.policyErrorHandler());
+ resp.validate();
+ return resp.getNames();
+ }
+
+ /**
+ * List all the policies with detailed information under the current metalake.
+ *
+ * @return A list of {@link Policy} under the current metalake.
+ * @throws NoSuchMetalakeException If the metalake does not exist.
+ */
+ @Override
+ public Policy[] listPolicyInfos() throws NoSuchMetalakeException {
+ Map<String, String> params = ImmutableMap.of("details", "true");
+ PolicyListResponse resp =
+ restClient.get(
+ String.format(API_METALAKES_POLICIES_PATH, RESTUtils.encodeString(this.name())),
+ params,
+ PolicyListResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.policyErrorHandler());
+ resp.validate();
+
+ return Arrays.stream(resp.getPolicies())
+ .map(p -> new GenericPolicy(p, restClient, this.name()))
+ .toArray(Policy[]::new);
+ }
+
+ /**
+ * Get a policy by its name under the current metalake.
+ *
+ * @param name The name of the policy.
+ * @return The policy.
+ * @throws NoSuchPolicyException If the policy does not exist.
+ */
+ @Override
+ public Policy getPolicy(String name) throws NoSuchPolicyException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(name), "policy name must not be null or empty");
+
+ PolicyResponse resp =
+ restClient.get(
+ String.format(API_METALAKES_POLICIES_PATH, RESTUtils.encodeString(this.name()))
+ + "/"
+ + RESTUtils.encodeString(name),
+ PolicyResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.policyErrorHandler());
+ resp.validate();
+
+ return new GenericPolicy(resp.getPolicy(), restClient, this.name());
+ }
+
+ /**
+ * Create a new policy under the current metalake.
+ *
+ * @param name The name of the policy.
+ * @param type The type of the policy.
+ * @param comment The comment of the policy.
+ * @param enabled Whether the policy is enabled or not.
+ * @param content The content of the policy.
+ * @return The created policy.
+ * @throws PolicyAlreadyExistsException If the policy already exists.
+ */
+ @Override
+ public Policy createPolicy(
+ String name, String type, String comment, boolean enabled, PolicyContent content)
+ throws PolicyAlreadyExistsException {
+ PolicyCreateRequest req = new PolicyCreateRequest(name, type, comment, enabled, toDTO(content));
+ req.validate();
+
+ PolicyResponse resp =
+ restClient.post(
+ String.format(API_METALAKES_POLICIES_PATH, RESTUtils.encodeString(this.name())),
+ req,
+ PolicyResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.policyErrorHandler());
+ resp.validate();
+
+ return new GenericPolicy(resp.getPolicy(), restClient, this.name());
+ }
+
+ /**
+ * Enable a policy under the current metalake. If the policy is already enabled, this method does
+ * nothing.
+ *
+ * @param name The name of the policy to enable.
+ * @throws NoSuchPolicyException If the policy does not exist.
+ */
+ @Override
+ public void enablePolicy(String name) throws NoSuchPolicyException {
+ setPolicyEnabled(name, true);
+ }
+
+ /**
+ * Disable a policy under the current metalake. If the policy is already disabled, this method
+ * does nothing.
+ *
+ * @param name The name of the policy to disable.
+ * @throws NoSuchPolicyException If the policy does not exist.
+ */
+ @Override
+ public void disablePolicy(String name) throws NoSuchPolicyException {
+ setPolicyEnabled(name, false);
+ }
+
+ /**
+ * Alter a policy under the current metalake by applying the changes.
+ *
+ * @param name The name of the policy.
+ * @param changes The changes to apply to the policy.
+ * @return The altered policy.
+ * @throws NoSuchPolicyException If the policy does not exist.
+ * @throws IllegalArgumentException If the changes cannot be applied to the policy.
+ */
+ @Override
+ public Policy alterPolicy(String name, PolicyChange... changes)
+ throws NoSuchPolicyException, IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(name), "policy name must not be null or empty");
+ List<PolicyUpdateRequest> updates =
+ Arrays.stream(changes)
+ .map(DTOConverters::toPolicyUpdateRequest)
+ .collect(Collectors.toList());
+ PolicyUpdatesRequest req = new PolicyUpdatesRequest(updates);
+ req.validate();
+
+ PolicyResponse resp =
+ restClient.put(
+ String.format(API_METALAKES_POLICIES_PATH, RESTUtils.encodeString(this.name()))
+ + "/"
+ + RESTUtils.encodeString(name),
+ req,
+ PolicyResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.policyErrorHandler());
+ resp.validate();
+
+ return new GenericPolicy(resp.getPolicy(), restClient, this.name());
+ }
+
+ /**
+ * Deletes a policy under the current metalake.
+ *
+ * @param name The name of the policy.
+ * @return True if the policy was deleted, false if the policy does not exist.
+ */
+ @Override
+ public boolean deletePolicy(String name) {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(name), "policy name must not be null or empty");
+
+ DropResponse resp =
+ restClient.delete(
+ String.format(API_METALAKES_POLICIES_PATH, RESTUtils.encodeString(this.name()))
+ + "/"
+ + RESTUtils.encodeString(name),
+ DropResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.policyErrorHandler());
+ resp.validate();
+ return resp.dropped();
+ }
+
/**
* Adds a new User.
*
@@ -1398,4 +1591,24 @@ public class GravitinoMetalake extends MetalakeDTO
public static Builder builder() {
return new Builder();
}
+
+ private void setPolicyEnabled(String policyName, boolean enabled) {
+ PolicySetRequest req = new PolicySetRequest(enabled);
+
+ ErrorResponse resp =
+ restClient.patch(
+ String.format(API_METALAKES_POLICIES_PATH, RESTUtils.encodeString(this.name()))
+ + "/"
+ + RESTUtils.encodeString(policyName),
+ req,
+ ErrorResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.policyErrorHandler());
+
+ if (resp.getCode() == 0) {
+ return;
+ }
+
+ ErrorHandlers.policyErrorHandler().accept(resp);
+ }
}
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericPolicy.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericPolicy.java
new file mode 100644
index 0000000000..b8478da7f0
--- /dev/null
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericPolicy.java
@@ -0,0 +1,156 @@
+/*
+ * 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.client;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.time.Instant;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.dto.AuditDTO;
+import org.apache.gravitino.dto.MetalakeDTO;
+import org.apache.gravitino.dto.policy.PolicyContentDTO;
+import org.apache.gravitino.dto.policy.PolicyDTO;
+import org.apache.gravitino.dto.responses.ErrorResponse;
+import org.apache.gravitino.dto.responses.MetadataObjectListResponse;
+import org.apache.gravitino.dto.responses.MetalakeResponse;
+import org.apache.gravitino.dto.tag.MetadataObjectDTO;
+import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.policy.Policy;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.Method;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class TestGenericPolicy extends TestBase {
+
+ private static final String metalakeName = "metalake1";
+
+ private static final PolicyDTO policyDTO =
+ PolicyDTO.builder()
+ .withName("policy1")
+ .withComment("comment1")
+ .withPolicyType("my_compaction")
+ .withEnabled(true)
+ .withContent(
+ PolicyContentDTO.CustomContentDTO.builder()
+ .withCustomRules(ImmutableMap.of("key1", "value1"))
+ .withSupportedObjectTypes(ImmutableSet.of(MetadataObject.Type.TABLE))
+ .withProperties(ImmutableMap.of("prop1", "value1"))
+ .build())
+ .withAudit(AuditDTO.builder().withCreator("test").withCreateTime(Instant.now()).build())
+ .build();
+
+ private static GravitinoClient gravitinoClient;
+
+ @BeforeAll
+ public static void setUp() throws Exception {
+ TestBase.setUp();
+
+ MetalakeDTO mockMetalake =
+ MetalakeDTO.builder()
+ .withName(metalakeName)
+ .withComment("comment")
+ .withAudit(
+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+ MetalakeResponse resp = new MetalakeResponse(mockMetalake);
+ buildMockResource(Method.GET, "/api/metalakes/" + metalakeName, null, resp, HttpStatus.SC_OK);
+
+ gravitinoClient =
+ GravitinoClient.builder("http://127.0.0.1:" + mockServer.getLocalPort())
+ .withMetalake(metalakeName)
+ .withVersionCheckDisabled()
+ .build();
+ }
+
+ @AfterAll
+ public static void tearDown() {
+ TestBase.tearDown();
+ gravitinoClient.close();
+ }
+
+ @Test
+ public void testAssociatedObjects() throws JsonProcessingException {
+ Policy policy = new GenericPolicy(policyDTO, gravitinoClient.restClient(), metalakeName);
+ String path = "/api/metalakes/" + metalakeName + "/policies/" + policyDTO.name() + "/objects";
+
+ MetadataObjectDTO[] objects =
+ new MetadataObjectDTO[] {
+ MetadataObjectDTO.builder()
+ .withParent(null)
+ .withName("catalog1")
+ .withType(MetadataObject.Type.CATALOG)
+ .build(),
+ MetadataObjectDTO.builder()
+ .withParent("catalog1")
+ .withName("schema1")
+ .withType(MetadataObject.Type.SCHEMA)
+ .build(),
+ MetadataObjectDTO.builder()
+ .withParent("catalog1.schema1")
+ .withName("table1")
+ .withType(MetadataObject.Type.TABLE)
+ .build(),
+ };
+
+ MetadataObjectListResponse resp = new MetadataObjectListResponse(objects);
+ buildMockResource(Method.GET, path, null, resp, HttpStatus.SC_OK);
+
+ MetadataObject[] actualObjects = policy.associatedObjects().objects();
+ Assertions.assertEquals(objects.length, actualObjects.length);
+ for (int i = 0; i < objects.length; i++) {
+ MetadataObjectDTO object = objects[i];
+ MetadataObject actualObject = actualObjects[i];
+ Assertions.assertEquals(object.parent(), actualObject.parent());
+ Assertions.assertEquals(object.name(), actualObject.name());
+ Assertions.assertEquals(object.type(), actualObject.type());
+ }
+
+ // Test return empty array
+ buildMockResource(
+ Method.GET,
+ path,
+ null,
+ new MetadataObjectListResponse(new MetadataObjectDTO[0]),
+ HttpStatus.SC_OK);
+ MetadataObject[] actualObjects1 = policy.associatedObjects().objects();
+ Assertions.assertEquals(0, actualObjects1.length);
+
+ // Test throw NoSuchMetalakeException
+ ErrorResponse errorResponse =
+ ErrorResponse.notFound(NoSuchMetalakeException.class.getSimpleName(), "mock error");
+ buildMockResource(Method.GET, path, null, errorResponse, HttpStatus.SC_NOT_FOUND);
+
+ Throwable ex =
+ Assertions.assertThrows(
+ NoSuchMetalakeException.class, () -> policy.associatedObjects().objects());
+ Assertions.assertEquals("mock error", ex.getMessage());
+
+ // Test throw internal error
+ ErrorResponse errorResponse1 = ErrorResponse.internalError("mock error");
+ buildMockResource(Method.GET, path, null, errorResponse1, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+
+ Throwable ex1 =
+ Assertions.assertThrows(RuntimeException.class, () -> policy.associatedObjects().objects());
+ Assertions.assertEquals("mock error", ex1.getMessage());
+ }
+}
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoMetalake.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoMetalake.java
index 728f0da4dc..3d4d7a564f 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoMetalake.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoMetalake.java
@@ -19,22 +19,31 @@
package org.apache.gravitino.client;
import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.stream.Collectors;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.CatalogChange;
+import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.dto.AuditDTO;
import org.apache.gravitino.dto.CatalogDTO;
import org.apache.gravitino.dto.MetalakeDTO;
+import org.apache.gravitino.dto.policy.PolicyContentDTO;
+import org.apache.gravitino.dto.policy.PolicyDTO;
import org.apache.gravitino.dto.requests.CatalogCreateRequest;
import org.apache.gravitino.dto.requests.CatalogUpdateRequest;
import org.apache.gravitino.dto.requests.CatalogUpdatesRequest;
import org.apache.gravitino.dto.requests.MetalakeCreateRequest;
+import org.apache.gravitino.dto.requests.PolicyCreateRequest;
+import org.apache.gravitino.dto.requests.PolicyUpdateRequest;
+import org.apache.gravitino.dto.requests.PolicyUpdatesRequest;
import org.apache.gravitino.dto.requests.TagCreateRequest;
import org.apache.gravitino.dto.requests.TagUpdateRequest;
import org.apache.gravitino.dto.requests.TagUpdatesRequest;
@@ -45,15 +54,22 @@ import org.apache.gravitino.dto.responses.EntityListResponse;
import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.dto.responses.MetalakeResponse;
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.responses.TagListResponse;
import org.apache.gravitino.dto.responses.TagResponse;
import org.apache.gravitino.dto.tag.TagDTO;
import org.apache.gravitino.exceptions.CatalogAlreadyExistsException;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NoSuchTagException;
+import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;
import org.apache.gravitino.exceptions.RESTException;
import org.apache.gravitino.exceptions.TagAlreadyExistsException;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyChange;
+import org.apache.gravitino.policy.PolicyContents;
import org.apache.gravitino.tag.Tag;
import org.apache.gravitino.tag.TagChange;
import org.apache.hc.core5.http.HttpStatus;
@@ -703,6 +719,408 @@ public class TestGravitinoMetalake extends TestBase {
Assertions.assertTrue(ex1.getMessage().contains("mock error"));
}
+ @Test
+ public void testListPolicies() throws JsonProcessingException {
+ String path = "/api/metalakes/" + metalakeName + "/policies";
+
+ String[] policyNames = new String[] {"policy1", "policy2"};
+ NameListResponse resp = new NameListResponse(policyNames);
+ buildMockResource(Method.GET, path, null, resp, HttpStatus.SC_OK);
+
+ String[] policies = gravitinoClient.listPolicies();
+ Assertions.assertEquals(2, policies.length);
+ Assertions.assertArrayEquals(policyNames, policies);
+
+ // Test return empty policy list
+ NameListResponse resp1 = new NameListResponse(new String[] {});
+ buildMockResource(Method.GET, path, null, resp1, HttpStatus.SC_OK);
+ String[] policies1 = gravitinoClient.listPolicies();
+ Assertions.assertEquals(0, policies1.length);
+
+ // Test throw MetalakeNotFoundException
+ ErrorResponse errorResponse =
+ ErrorResponse.notFound(NoSuchMetalakeException.class.getSimpleName(), "mock error");
+ buildMockResource(Method.GET, path, null, errorResponse, HttpStatus.SC_NOT_FOUND);
+ Throwable ex =
+ Assertions.assertThrows(NoSuchMetalakeException.class, gravitinoClient::listPolicies);
+ Assertions.assertTrue(ex.getMessage().contains("mock error"));
+
+ // Test throw internal error
+ ErrorResponse errorResp = ErrorResponse.internalError("mock error");
+ buildMockResource(Method.GET, path, null, errorResp, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ Throwable ex1 = Assertions.assertThrows(RuntimeException.class, gravitinoClient::listPolicies);
+ Assertions.assertTrue(ex1.getMessage().contains("mock error"));
+ }
+
+ @Test
+ public void testListPolicyInfos() throws JsonProcessingException {
+ String path = "/api/metalakes/" + metalakeName + "/policies";
+ Map<String, String> params = Collections.singletonMap("details", "true");
+ Set<MetadataObject.Type> supportedTypes = Collections.singleton(MetadataObject.Type.TABLE);
+
+ PolicyDTO policy1 =
+ PolicyDTO.builder()
+ .withName("policy1")
+ .withComment("comment1")
+ .withPolicyType("custom")
+ .withContent(
+ PolicyContentDTO.CustomContentDTO.builder()
+ .withSupportedObjectTypes(supportedTypes)
+ .build())
+ .withAudit(
+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+ PolicyDTO policy2 =
+ PolicyDTO.builder()
+ .withName("policy2")
+ .withComment("comment2")
+ .withPolicyType("custom")
+ .withContent(
+ PolicyContentDTO.CustomContentDTO.builder()
+ .withSupportedObjectTypes(supportedTypes)
+ .build())
+ .withAudit(
+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+
+ PolicyDTO[] policies = new PolicyDTO[] {policy1, policy2};
+ PolicyListResponse resp = new PolicyListResponse(policies);
+ buildMockResource(Method.GET, path, params, null, resp, HttpStatus.SC_OK);
+
+ Policy[] policyInfos = gravitinoClient.listPolicyInfos();
+ Assertions.assertEquals(2, policyInfos.length);
+ Assertions.assertEquals(policy1.name(), policyInfos[0].name());
+ Assertions.assertEquals(policy1.comment(), policyInfos[0].comment());
+ Assertions.assertEquals(policy1.content(), policyInfos[0].content());
+ Assertions.assertEquals(policy2.name(), policyInfos[1].name());
+ Assertions.assertEquals(policy2.comment(), policyInfos[1].comment());
+ Assertions.assertEquals(policy2.content(), policyInfos[1].content());
+
+ // Test empty policy list
+ PolicyListResponse resp1 = new PolicyListResponse(new PolicyDTO[] {});
+ buildMockResource(Method.GET, path, params, null, resp1, HttpStatus.SC_OK);
+ Policy[] policyInfos1 = gravitinoClient.listPolicyInfos();
+ Assertions.assertEquals(0, policyInfos1.length);
+
+ // Test throw NoSuchMetalakeException
+ ErrorResponse errorResponse =
+ ErrorResponse.notFound(NoSuchMetalakeException.class.getSimpleName(), "mock error");
+ buildMockResource(Method.GET, path, params, null, errorResponse, HttpStatus.SC_NOT_FOUND);
+ Throwable ex =
+ Assertions.assertThrows(NoSuchMetalakeException.class, gravitinoClient::listPolicyInfos);
+ Assertions.assertTrue(ex.getMessage().contains("mock error"));
+
+ // Test throw internal error
+ ErrorResponse errorResp = ErrorResponse.internalError("mock error");
+ buildMockResource(
+ Method.GET, path, params, null, errorResp, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ Throwable ex1 =
+ Assertions.assertThrows(RuntimeException.class, gravitinoClient::listPolicyInfos);
+ Assertions.assertTrue(ex1.getMessage().contains("mock error"));
+ }
+
+ @Test
+ public void testGetPolicy() throws JsonProcessingException {
+ String policyName = "policy1";
+ String path = "/api/metalakes/" + metalakeName + "/policies/" + policyName;
+
+ Set<MetadataObject.Type> supportedTypes = Collections.singleton(MetadataObject.Type.TABLE);
+ PolicyDTO policy1 =
+ PolicyDTO.builder()
+ .withName(policyName)
+ .withComment("comment1")
+ .withPolicyType("custom")
+ .withContent(
+ PolicyContentDTO.CustomContentDTO.builder()
+ .withSupportedObjectTypes(supportedTypes)
+ .build())
+ .withAudit(
+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+
+ PolicyResponse resp = new PolicyResponse(policy1);
+ buildMockResource(Method.GET, path, null, resp, HttpStatus.SC_OK);
+
+ Policy policy = gravitinoClient.getPolicy(policyName);
+ Assertions.assertEquals(policyName, policy.name());
+ Assertions.assertEquals(policy1.comment(), policy.comment());
+ Assertions.assertEquals(policy1.content(), policy.content());
+
+ // Test throw NoSuchMetalakeException
+ ErrorResponse errorResponse =
+ ErrorResponse.notFound(NoSuchMetalakeException.class.getSimpleName(), "mock error");
+ buildMockResource(Method.GET, path, null, errorResponse, HttpStatus.SC_NOT_FOUND);
+ Throwable ex =
+ Assertions.assertThrows(
+ NoSuchMetalakeException.class, () -> gravitinoClient.getPolicy(policyName));
+ Assertions.assertTrue(ex.getMessage().contains("mock error"));
+
+ // Test throw NoSuchPolicyException
+ ErrorResponse errorResponse1 =
+ ErrorResponse.notFound(NoSuchPolicyException.class.getSimpleName(), "mock error");
+ buildMockResource(Method.GET, path, null, errorResponse1, HttpStatus.SC_NOT_FOUND);
+ Throwable ex1 =
+ Assertions.assertThrows(
+ NoSuchPolicyException.class, () -> gravitinoClient.getPolicy(policyName));
+ Assertions.assertTrue(ex1.getMessage().contains("mock error"));
+
+ // Test throw internal error
+ ErrorResponse errorResp = ErrorResponse.internalError("mock error");
+ buildMockResource(Method.GET, path, null, errorResp, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ Throwable ex2 =
+ Assertions.assertThrows(
+ RuntimeException.class, () -> gravitinoClient.getPolicy(policyName));
+ Assertions.assertTrue(ex2.getMessage().contains("mock error"));
+ }
+
+ @Test
+ public void testCreatePolicy() throws JsonProcessingException {
+ String policyName = "policy1";
+ String path = "/api/metalakes/" + metalakeName + "/policies";
+
+ Set<MetadataObject.Type> supportedTypes = ImmutableSet.of(MetadataObject.Type.TABLE);
+ PolicyDTO policy1 =
+ PolicyDTO.builder()
+ .withName(policyName)
+ .withPolicyType("custom")
+ .withContent(
+ PolicyContentDTO.CustomContentDTO.builder()
+ .withSupportedObjectTypes(supportedTypes)
+ .build())
+ .withAudit(
+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+ PolicyResponse resp = new PolicyResponse(policy1);
+
+ PolicyCreateRequest req =
+ new PolicyCreateRequest(
+ policyName, "custom", policy1.comment(), policy1.enabled(), policy1.content());
+ buildMockResource(Method.POST, path, req, resp, HttpStatus.SC_OK);
+
+ Policy policy =
+ gravitinoClient.createPolicy(
+ policyName,
+ "custom",
+ policy1.comment(),
+ policy1.enabled(),
+ PolicyContents.custom(null, supportedTypes, null));
+ Assertions.assertEquals(policyName, policy.name());
+ Assertions.assertNull(policy.comment());
+
+ // Test with null name
+ Throwable ex =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ gravitinoClient.createPolicy(
+ null,
+ "custom",
+ policy1.comment(),
+ policy1.enabled(),
+ PolicyContents.custom(null, supportedTypes, null)));
+ Assertions.assertEquals("\"name\" is required and cannot be empty", ex.getMessage());
+
+ // Test throw NoSuchMetalakeException
+ ErrorResponse errorResponse =
+ ErrorResponse.notFound(NoSuchMetalakeException.class.getSimpleName(), "mock error");
+ buildMockResource(Method.POST, path, null, errorResponse, HttpStatus.SC_NOT_FOUND);
+ Throwable ex1 =
+ Assertions.assertThrows(
+ NoSuchMetalakeException.class,
+ () ->
+ gravitinoClient.createPolicy(
+ policyName,
+ "custom",
+ policy1.comment(),
+ policy1.enabled(),
+ PolicyContents.custom(null, supportedTypes, null)));
+ Assertions.assertTrue(ex1.getMessage().contains("mock error"));
+
+ // Test throw PolicyAlreadyExistsException
+ ErrorResponse errorResponse1 =
+ ErrorResponse.alreadyExists(
+ PolicyAlreadyExistsException.class.getSimpleName(), "mock error");
+ buildMockResource(Method.POST, path, null, errorResponse1, HttpStatus.SC_CONFLICT);
+ Throwable ex2 =
+ Assertions.assertThrows(
+ PolicyAlreadyExistsException.class,
+ () ->
+ gravitinoClient.createPolicy(
+ policyName,
+ "custom",
+ policy1.comment(),
+ policy1.enabled(),
+ PolicyContents.custom(null, supportedTypes, null)));
+ Assertions.assertTrue(ex2.getMessage().contains("mock error"));
+
+ // Test throw internal error
+ ErrorResponse errorResp = ErrorResponse.internalError("mock error");
+ buildMockResource(Method.POST, path, null, errorResp, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ Throwable ex3 =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () ->
+ gravitinoClient.createPolicy(
+ policyName,
+ "custom",
+ policy1.comment(),
+ policy1.enabled(),
+ PolicyContents.custom(null, supportedTypes, null)));
+ Assertions.assertTrue(ex3.getMessage().contains("mock error"));
+ }
+
+ @Test
+ public void testAlterPolicy() throws JsonProcessingException {
+ String policyName = "policy1";
+ String path = "/api/metalakes/" + metalakeName + "/policies/" + policyName;
+
+ Set<MetadataObject.Type> supportedTypes = ImmutableSet.of(MetadataObject.Type.TABLE);
+ PolicyDTO policy2 =
+ PolicyDTO.builder()
+ .withName("policy2")
+ .withComment("comment2")
+ .withPolicyType("custom")
+ .withContent(
+ PolicyContentDTO.CustomContentDTO.builder()
+ .withSupportedObjectTypes(supportedTypes)
+ .build())
+ .withAudit(
+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+
+ PolicyResponse resp = new PolicyResponse(policy2);
+
+ PolicyContentDTO newContent =
+ PolicyContentDTO.CustomContentDTO.builder()
+ .withCustomRules(ImmutableMap.of("rule1", "value1"))
+ .withSupportedObjectTypes(supportedTypes)
+ .build();
+ List<PolicyUpdateRequest> reqs =
+ Arrays.asList(
+ new PolicyUpdateRequest.RenamePolicyRequest("policy2"),
+ new PolicyUpdateRequest.UpdatePolicyCommentRequest("comment2"),
+ new PolicyUpdateRequest.UpdatePolicyContentRequest("custom", newContent));
+ PolicyUpdatesRequest request = new PolicyUpdatesRequest(reqs);
+ buildMockResource(Method.PUT, path, request, resp, HttpStatus.SC_OK);
+
+ Policy policy =
+ gravitinoClient.alterPolicy(
+ policyName,
+ PolicyChange.rename("policy2"),
+ PolicyChange.updateComment("comment2"),
+ PolicyChange.updateContent(
+ "custom",
+ PolicyContents.custom(ImmutableMap.of("rule1", "value1"), supportedTypes, null)));
+ Assertions.assertEquals("policy2", policy.name());
+ Assertions.assertEquals("comment2", policy.comment());
+
+ // Test throw NoSuchMetalakeException
+ ErrorResponse errorResponse =
+ ErrorResponse.notFound(NoSuchMetalakeException.class.getSimpleName(), "mock error");
+ buildMockResource(Method.PUT, path, request, errorResponse, HttpStatus.SC_NOT_FOUND);
+ Throwable ex =
+ Assertions.assertThrows(
+ NoSuchMetalakeException.class,
+ () ->
+ gravitinoClient.alterPolicy(
+ policyName,
+ PolicyChange.rename("policy2"),
+ PolicyChange.updateComment("comment2"),
+ PolicyChange.updateContent(
+ "custom",
+ PolicyContents.custom(
+ ImmutableMap.of("rule1", "value1"), supportedTypes, null))));
+ Assertions.assertTrue(ex.getMessage().contains("mock error"));
+
+ // Test throw NoSuchPolicyException
+ ErrorResponse errorResponse1 =
+ ErrorResponse.notFound(NoSuchPolicyException.class.getSimpleName(), "mock error");
+ buildMockResource(Method.PUT, path, request, errorResponse1, HttpStatus.SC_NOT_FOUND);
+ Throwable ex1 =
+ Assertions.assertThrows(
+ NoSuchPolicyException.class,
+ () ->
+ gravitinoClient.alterPolicy(
+ policyName,
+ PolicyChange.rename("policy2"),
+ PolicyChange.updateComment("comment2"),
+ PolicyChange.updateContent(
+ "custom",
+ PolicyContents.custom(
+ ImmutableMap.of("rule1", "value1"), supportedTypes, null))));
+ Assertions.assertTrue(ex1.getMessage().contains("mock error"));
+
+ // Test throw IllegalArgumentException
+ ErrorResponse errorResponse2 = ErrorResponse.illegalArguments("mock error");
+ buildMockResource(Method.PUT, path, request, errorResponse2, HttpStatus.SC_BAD_REQUEST);
+ Throwable ex2 =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ gravitinoClient.alterPolicy(
+ policyName,
+ PolicyChange.rename("policy2"),
+ PolicyChange.updateComment("comment2"),
+ PolicyChange.updateContent(
+ "custom",
+ PolicyContents.custom(
+ ImmutableMap.of("rule1", "value1"), supportedTypes, null))));
+ Assertions.assertTrue(ex2.getMessage().contains("mock error"));
+
+ // Test throw internal error
+ ErrorResponse errorResp = ErrorResponse.internalError("mock error");
+ buildMockResource(Method.PUT, path, request, errorResp, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ Throwable ex3 =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () ->
+ gravitinoClient.alterPolicy(
+ policyName,
+ PolicyChange.rename("policy2"),
+ PolicyChange.updateComment("comment2"),
+ PolicyChange.updateContent(
+ "custom",
+ PolicyContents.custom(
+ ImmutableMap.of("rule1", "value1"),
+ ImmutableSet.of(MetadataObject.Type.TABLE),
+ null))));
+ Assertions.assertTrue(ex3.getMessage().contains("mock error"));
+ }
+
+ @Test
+ public void testDeletePolicy() throws JsonProcessingException {
+ String policyName = "policy1";
+ String path = "/api/metalakes/" + metalakeName + "/policies/" + policyName;
+
+ DropResponse resp = new DropResponse(true);
+ buildMockResource(Method.DELETE, path, null, resp, HttpStatus.SC_OK);
+ boolean dropped = gravitinoClient.deletePolicy(policyName);
+ Assertions.assertTrue(dropped);
+
+ // Test return false
+ DropResponse resp1 = new DropResponse(false);
+ buildMockResource(Method.DELETE, path, null, resp1, HttpStatus.SC_OK);
+ boolean dropped1 = gravitinoClient.deletePolicy(policyName);
+ Assertions.assertFalse(dropped1);
+
+ // Test throw NoSuchMetalakeException
+ ErrorResponse errorResponse =
+ ErrorResponse.notFound(NoSuchMetalakeException.class.getSimpleName(), "mock error");
+ buildMockResource(Method.DELETE, path, null, errorResponse, HttpStatus.SC_NOT_FOUND);
+ Throwable ex =
+ Assertions.assertThrows(
+ NoSuchMetalakeException.class, () -> gravitinoClient.deletePolicy(policyName));
+ Assertions.assertTrue(ex.getMessage().contains("mock error"));
+
+ // Test internal error
+ ErrorResponse errorResp = ErrorResponse.internalError("mock error");
+ buildMockResource(Method.DELETE, path, null, errorResp, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ Throwable ex1 =
+ Assertions.assertThrows(
+ RuntimeException.class, () -> gravitinoClient.deletePolicy(policyName));
+ Assertions.assertTrue(ex1.getMessage().contains("mock error"));
+ }
+
@Test
public void testEquals() throws JsonProcessingException {
GravitinoMetalake metalake1 = createMetalake(client, "test", true);