World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#12610] feat(client): Add Semantic Model Java client (#12628)
mchadesf3bd25d546b4
diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.javaindex 2771246b72..84cef9b560 100644--- a/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java@@ -24,6 +24,8 @@ import javax.annotation.Nullable;import org.apache.gravitino.Audit;import org.apache.gravitino.Auditable;import org.apache.gravitino.annotation.Evolving;+import org.apache.gravitino.policy.SupportsPolicies;+import org.apache.gravitino.tag.SupportsTags;/*** A schema-scoped analytical Semantic Model managed by Gravitino. The entity composes its immutable@@ -76,6 +78,26 @@ public interface SemanticModel extends Auditable {return Collections.emptyMap();}+ /**+ * Returns the tag operations for this Semantic Model.+ *+ * @return The {@link SupportsTags} if the Semantic Model supports tag operations.+ * @throws UnsupportedOperationException If the Semantic Model does not support tag operations.+ */+ default SupportsTags supportsTags() {+ throw new UnsupportedOperationException("Semantic Model does not support tag operations.");+ }++ /**+ * Returns the tag-derived policy lookup operations for this Semantic Model.+ *+ * @return The {@link SupportsPolicies} if the Semantic Model supports policy operations.+ * @throws UnsupportedOperationException If the Semantic Model does not support policy operations.+ */+ default SupportsPolicies supportsPolicies() {+ throw new UnsupportedOperationException("Semantic Model does not support policy operations.");+ }+/*** Returns the audit information for the Semantic Model.*diff --git a/clients/client-java/build.gradle.kts b/clients/client-java/build.gradle.ktsindex 5ddb7b79ee..704a1ec7f3 100644--- a/clients/client-java/build.gradle.kts+++ b/clients/client-java/build.gradle.kts@@ -54,6 +54,7 @@ dependencies {testImplementation(libs.nimbus.jose.jwt)testImplementation(libs.commons.lang3)testImplementation(libs.hadoop3.client)+ testImplementation(libs.jackson.dataformat.yaml)testImplementation(libs.junit.jupiter.api)testImplementation(libs.junit.jupiter.params)testImplementation(libs.minikdc)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.javaindex 84c6f2bbf2..9bc6fdd0ff 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@@ -55,9 +55,11 @@ 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.SemanticModelUpdateRequest;import org.apache.gravitino.dto.requests.TableUpdateRequest;import org.apache.gravitino.dto.requests.TagUpdateRequest;import org.apache.gravitino.dto.requests.TopicUpdateRequest;+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;import org.apache.gravitino.file.FilesetChange;import org.apache.gravitino.function.FunctionChange;import org.apache.gravitino.function.FunctionColumn;@@ -74,6 +76,7 @@ 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;+import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.tag.TagChange;class DTOConverters {@@ -643,6 +646,40 @@ class DTOConverters {}}+ static SemanticModelUpdateRequest toSemanticModelUpdateRequest(SemanticModelChange change) {+ if (change == null) {+ throw new IllegalArgumentException("Semantic Model change must not be null");+ }++ if (change instanceof SemanticModelChange.RenameSemanticModel) {+ return new SemanticModelUpdateRequest.RenameSemanticModelRequest(+ ((SemanticModelChange.RenameSemanticModel) change).getNewName());++ } else if (change instanceof SemanticModelChange.UpdateComment) {+ return new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest(+ ((SemanticModelChange.UpdateComment) change).getNewComment());++ } else if (change instanceof SemanticModelChange.SetProperty) {+ SemanticModelChange.SetProperty setProperty = (SemanticModelChange.SetProperty) change;+ return new SemanticModelUpdateRequest.SetSemanticModelPropertyRequest(+ setProperty.getProperty(), setProperty.getValue());++ } else if (change instanceof SemanticModelChange.RemoveProperty) {+ return new SemanticModelUpdateRequest.RemoveSemanticModelPropertyRequest(+ ((SemanticModelChange.RemoveProperty) change).getProperty());++ } else if (change instanceof SemanticModelChange.ReplaceDefinition) {+ SemanticModelChange.ReplaceDefinition replaceDefinition =+ (SemanticModelChange.ReplaceDefinition) change;+ return new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(+ SemanticModelDefinitionDTO.fromDefinition(replaceDefinition.getDefinition()));++ } else {+ throw new IllegalArgumentException(+ "Unknown Semantic Model change type: " + change.getClass().getSimpleName());+ }+ }+static FunctionDefinitionDTO toFunctionDefinitionDTO(FunctionDefinition definition) {return FunctionDefinitionDTO.fromFunctionDefinition(definition);}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.javaindex 7357492245..6b35b5e016 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@@ -39,6 +39,7 @@ import org.apache.gravitino.exceptions.IllegalJobTemplateOperationException;import org.apache.gravitino.exceptions.IllegalMetadataObjectException;import org.apache.gravitino.exceptions.IllegalPrivilegeException;import org.apache.gravitino.exceptions.IllegalRoleException;+import org.apache.gravitino.exceptions.IllegalSemanticModelException;import org.apache.gravitino.exceptions.IllegalStatisticNameException;import org.apache.gravitino.exceptions.InUseException;import org.apache.gravitino.exceptions.JobTemplateAlreadyExistsException;@@ -63,6 +64,7 @@ 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.NoSuchSemanticModelException;import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.exceptions.NoSuchTagException;import org.apache.gravitino.exceptions.NoSuchTopicException;@@ -80,6 +82,7 @@ import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.exceptions.RoleAlreadyExistsException;import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;+import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;import org.apache.gravitino.exceptions.TableAlreadyExistsException;import org.apache.gravitino.exceptions.TagAlreadyAssociatedException;import org.apache.gravitino.exceptions.TagAlreadyExistsException;@@ -302,6 +305,15 @@ public class ErrorHandlers {return FunctionErrorHandler.INSTANCE;}+ /**+ * Creates an error handler specific to Semantic Model operations.+ *+ * @return A Consumer representing the Semantic Model error handler.+ */+ public static Consumer<ErrorResponse> semanticModelErrorHandler() {+ return SemanticModelErrorHandler.INSTANCE;+ }+private ErrorHandlers() {}/**@@ -1497,4 +1509,71 @@ public class ErrorHandlers {}}}++ /** Error handler specific to Semantic Model operations. */+ @SuppressWarnings("FormatStringAnnotation")+ private static class SemanticModelErrorHandler extends RestErrorHandler {++ private static final SemanticModelErrorHandler INSTANCE = new SemanticModelErrorHandler();++ @Override+ public void accept(ErrorResponse errorResponse) {+ String errorMessage = formatErrorMessage(errorResponse);++ switch (errorResponse.getCode()) {+ case ErrorConstants.ILLEGAL_ARGUMENTS_CODE:+ if (IllegalSemanticModelException.class.getSimpleName().equals(errorResponse.getType())) {+ throw new IllegalSemanticModelException(errorMessage);+ }+ throw new IllegalArgumentException(errorMessage);++ case ErrorConstants.NOT_FOUND_CODE:+ if (NoSuchMetalakeException.class.getSimpleName().equals(errorResponse.getType())) {+ throw new NoSuchMetalakeException(errorMessage);+ } else if (NoSuchCatalogException.class.getSimpleName().equals(errorResponse.getType())) {+ throw new NoSuchCatalogException(errorMessage);+ } else if (NoSuchSchemaException.class.getSimpleName().equals(errorResponse.getType())) {+ throw new NoSuchSchemaException(errorMessage);+ } else if (NoSuchSemanticModelException.class+ .getSimpleName()+ .equals(errorResponse.getType())) {+ throw new NoSuchSemanticModelException(errorMessage);+ }+ throw new NotFoundException(errorMessage);++ case ErrorConstants.ALREADY_EXISTS_CODE:+ if (SemanticModelAlreadyExistsException.class+ .getSimpleName()+ .equals(errorResponse.getType())) {+ throw new SemanticModelAlreadyExistsException(errorMessage);+ }+ throw new AlreadyExistsException(errorMessage);++ case ErrorConstants.UNSUPPORTED_OPERATION_CODE:+ throw new UnsupportedOperationException(errorMessage);++ case ErrorConstants.FORBIDDEN_CODE:+ throw new ForbiddenException(errorMessage);++ case ErrorConstants.INTERNAL_ERROR_CODE:+ throw new RuntimeException(errorMessage);++ case ErrorConstants.OPTIMISTIC_LOCK_CONFLICT_CODE:+ throw new OptimisticLockException(errorMessage);++ case ErrorConstants.NOT_IN_USE_CODE:+ if (CatalogNotInUseException.class.getSimpleName().equals(errorResponse.getType())) {+ throw new CatalogNotInUseException(errorMessage);+ } else if (MetalakeNotInUseException.class+ .getSimpleName()+ .equals(errorResponse.getType())) {+ throw new MetalakeNotInUseException(errorMessage);+ }+ throw new NotInUseException(errorMessage);++ default:+ super.accept(errorResponse);+ }+ }+ }}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericSemanticModel.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericSemanticModel.javanew file mode 100644index 0000000000..e64d1483fc--- /dev/null+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericSemanticModel.java@@ -0,0 +1,200 @@+/*+ * 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.Arrays;+import java.util.Collections;+import java.util.LinkedHashMap;+import java.util.Map;+import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.gravitino.Audit;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.MetadataObjects;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.SupportsPolicies;+import org.apache.gravitino.semantic.SemanticModel;+import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.tag.SupportsTags;+import org.apache.gravitino.tag.Tag;+import org.apache.gravitino.tag.TagValue;++/** An immutable client-side Semantic Model returned by the Gravitino REST API. */+class GenericSemanticModel implements SemanticModel, SupportsTags, SupportsPolicies {++ private final String name;+ private final SemanticModelDefinition definition;+ private final Map<String, String> properties;+ private final Audit audit;+ private final MetadataObjectTagOperations objectTagOperations;+ private final MetadataObjectPolicyOperations objectPolicyOperations;++ @Nullable private final String comment;++ GenericSemanticModel(+ SemanticModel semanticModel, RESTClient restClient, Namespace semanticModelNamespace) {+ this.name = semanticModel.name();+ this.comment = semanticModel.comment();+ this.definition = semanticModel.definition();+ Map<String, String> sourceProperties = semanticModel.properties();+ this.properties =+ sourceProperties == null+ ? Collections.emptyMap()+ : Collections.unmodifiableMap(new LinkedHashMap<>(sourceProperties));+ this.audit = semanticModel.auditInfo();+ MetadataObject metadataObject =+ MetadataObjects.of(+ Arrays.asList(semanticModelNamespace.level(1), semanticModelNamespace.level(2), name),+ MetadataObject.Type.SEMANTIC_MODEL);+ this.objectTagOperations =+ new MetadataObjectTagOperations(+ semanticModelNamespace.level(0), metadataObject, restClient);+ this.objectPolicyOperations =+ new MetadataObjectPolicyOperations(+ semanticModelNamespace.level(0), metadataObject, restClient);+ }++ /** {@inheritDoc} */+ @Override+ public String name() {+ return name;+ }++ /** {@inheritDoc} */+ @Nullable+ @Override+ public String comment() {+ return comment;+ }++ /** {@inheritDoc} */+ @Override+ public SemanticModelDefinition definition() {+ return definition;+ }++ /** {@inheritDoc} */+ @Override+ public Map<String, String> properties() {+ return properties;+ }++ /** {@inheritDoc} */+ @Override+ public Audit auditInfo() {+ return audit;+ }++ /** {@inheritDoc} */+ @Override+ public SupportsTags supportsTags() {+ return this;+ }++ /** {@inheritDoc} */+ @Override+ public SupportsPolicies supportsPolicies() {+ return this;+ }++ /** {@inheritDoc} */+ @Override+ public String[] listTags() {+ return objectTagOperations.listTags();+ }++ /** {@inheritDoc} */+ @Override+ public Tag[] listTagsInfo() {+ return objectTagOperations.listTagsInfo();+ }++ /** {@inheritDoc} */+ @Override+ public Tag getTag(String name) {+ return objectTagOperations.getTag(name);+ }++ /** {@inheritDoc} */+ @Override+ public String[] associateTags(String[] tagsToAdd, String[] tagsToRemove) {+ return objectTagOperations.associateTags(tagsToAdd, tagsToRemove);+ }++ /** {@inheritDoc} */+ @Override+ public String[] associateTags(TagValue[] tagsToAdd, TagValue[] tagsToRemove) {+ return objectTagOperations.associateTags(tagsToAdd, tagsToRemove);+ }++ /** {@inheritDoc} */+ @Override+ public String[] listPolicies() {+ return objectPolicyOperations.listPolicies();+ }++ /** {@inheritDoc} */+ @Override+ public Policy[] listPolicyInfos() {+ return objectPolicyOperations.listPolicyInfos();+ }++ /** {@inheritDoc} */+ @Override+ public boolean equals(Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof GenericSemanticModel)) {+ return false;+ }+ GenericSemanticModel that = (GenericSemanticModel) other;+ return name.equals(that.name)+ && Objects.equals(comment, that.comment)+ && definition.equals(that.definition)+ && properties.equals(that.properties)+ && audit.equals(that.audit);+ }++ /** {@inheritDoc} */+ @Override+ public int hashCode() {+ return Objects.hash(name, comment, definition, properties, audit);+ }++ /** {@inheritDoc} */+ @Override+ public String toString() {+ return "GenericSemanticModel{"+ + "name='"+ + name+ + '\''+ + ", comment='"+ + comment+ + '\''+ + ", definition="+ + definition+ + ", properties="+ + properties+ + ", audit="+ + audit+ + '}';+ }+}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/HTTPClient.java b/clients/client-java/src/main/java/org/apache/gravitino/client/HTTPClient.javaindex b6a9c03785..f7ff051433 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/HTTPClient.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/HTTPClient.java@@ -332,7 +332,7 @@ public class HTTPClient implements RESTClient {Map<String, String> headers,Consumer<ErrorResponse> errorHandler) {return execute(- method, path, queryParams, requestBody, responseType, headers, errorHandler, h -> {});+ method, path, queryParams, requestBody, null, responseType, headers, errorHandler, h -> {});}/**@@ -351,6 +351,8 @@ public class HTTPClient implements RESTClient {* @param queryParams A map of query parameters (key-value pairs) to include in the request URL* (can be null).* @param requestBody The content to place in the request body (can be null).+ * @param requestContentType The media type for an already serialized request body, or {@code+ * null} to use the standard JSON or form encoding.* @param responseType The class type of the response for deserialization (Must be registered with* the ObjectMapper).* @param headers A map of request headers (key-value pairs) to include in the request (can be@@ -371,6 +373,7 @@ public class HTTPClient implements RESTClient {String path,Map<String, String> queryParams,Object requestBody,+ String requestContentType,Class<T> responseType,Map<String, String> headers,Consumer<ErrorResponse> errorHandler,@@ -388,7 +391,13 @@ public class HTTPClient implements RESTClient {URI requestUri = buildUri(path, queryParams);HttpUriRequestBase request = new HttpUriRequestBase(method.name(), requestUri);- if (requestBody instanceof Map) {+ if (requestContentType != null) {+ addRequestHeaders(request, headers, requestContentType);+ request.setEntity(+ new StringEntity(+ (String) requestBody,+ ContentType.create(requestContentType, StandardCharsets.UTF_8)));+ } else if (requestBody instanceof Map) {// encode maps as form data, application/x-www-form-urlencodedaddRequestHeaders(request, headers, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());request.setEntity(toFormEncoding((Map<?, ?>) requestBody));@@ -436,6 +445,10 @@ public class HTTPClient implements RESTClient {response.getCode());}+ if (responseType == String.class) {+ return responseType.cast(responseBody);+ }+try {return mapper.readValue(responseBody, responseType);} catch (JsonProcessingException e) {@@ -520,6 +533,24 @@ public class HTTPClient implements RESTClient {return execute(Method.GET, path, queryParams, null, responseType, headers, errorHandler);}+ /**+ * Sends an HTTP GET request and returns the response body without JSON deserialization.+ *+ * @param path The URL path to send the GET request to.+ * @param queryParams A map of query parameters to include in the request URL.+ * @param headers A map of request headers to include in the request.+ * @param errorHandler The error handler delegated for HTTP error responses.+ * @return The raw response body.+ */+ @Override+ public String getRaw(+ String path,+ Map<String, String> queryParams,+ Map<String, String> headers,+ Consumer<ErrorResponse> errorHandler) {+ return execute(Method.GET, path, queryParams, null, String.class, headers, errorHandler);+ }+/*** Sends an HTTP POST request to the specified path with the provided request body and processes* the response.@@ -545,6 +576,33 @@ public class HTTPClient implements RESTClient {return execute(Method.POST, path, null, body, responseType, headers, errorHandler);}+ /**+ * Sends an HTTP POST request with an already serialized request body.+ *+ * @param path The URL path to send the POST request to.+ * @param body The raw request body.+ * @param contentType The media type of the raw request body.+ * @param responseType The class type of the JSON response.+ * @param headers A map of request headers to include in the request.+ * @param errorHandler The error handler delegated for HTTP error responses.+ * @param <T> The class type of the response.+ * @return The response entity parsed and converted to its type T.+ */+ @Override+ public <T extends RESTResponse> T postRaw(+ String path,+ String body,+ String contentType,+ Class<T> responseType,+ Map<String, String> headers,+ Consumer<ErrorResponse> errorHandler) {+ Preconditions.checkArgument(body != null, "Raw request body must not be null");+ Preconditions.checkArgument(+ StringUtils.isNotBlank(contentType), "Raw request content type must not be blank");+ return execute(+ Method.POST, path, null, body, contentType, responseType, headers, errorHandler, h -> {});+ }+/*** Sends an HTTP POST request to the specified path with the provided request body and processes* the response with support for response headers.@@ -570,7 +628,7 @@ public class HTTPClient implements RESTClient {Consumer<ErrorResponse> errorHandler,Consumer<Map<String, String>> responseHeaders) {return execute(- Method.POST, path, null, body, responseType, headers, errorHandler, responseHeaders);+ Method.POST, path, null, body, null, responseType, headers, errorHandler, responseHeaders);}/**@@ -623,7 +681,7 @@ public class HTTPClient implements RESTClient {Consumer<ErrorResponse> errorHandler,Consumer<Map<String, String>> responseHeaders) {return execute(- Method.PUT, path, null, body, responseType, headers, errorHandler, responseHeaders);+ Method.PUT, path, null, body, null, responseType, headers, errorHandler, responseHeaders);}/**diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/RESTClient.java b/clients/client-java/src/main/java/org/apache/gravitino/client/RESTClient.javaindex 384a635823..82b9234035 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/RESTClient.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/RESTClient.java@@ -203,6 +203,24 @@ public interface RESTClient extends Closeable {Map<String, String> headers,Consumer<ErrorResponse> errorHandler);+ /**+ * Perform a GET request and return the response body without JSON deserialization.+ *+ * @param path The path to be requested.+ * @param queryParams The query parameters to be included in the request.+ * @param headers The headers to be included in the request.+ * @param errorHandler The consumer for handling error responses.+ * @return The raw response body.+ * @throws UnsupportedOperationException If raw responses are not supported by the client.+ */+ default String getRaw(+ String path,+ Map<String, String> queryParams,+ Map<String, String> headers,+ Consumer<ErrorResponse> errorHandler) {+ throw new UnsupportedOperationException("Raw GET responses are not supported");+ }+/*** Perform a POST request on the specified path with given information.*@@ -290,6 +308,29 @@ public interface RESTClient extends Closeable {Map<String, String> headers,Consumer<ErrorResponse> errorHandler);+ /**+ * Perform a POST request whose body is already serialized.+ *+ * @param path The path to be requested.+ * @param body The raw request body.+ * @param contentType The media type of the raw request body.+ * @param responseType The class representing the type of the JSON response.+ * @param headers The headers to be included in the request.+ * @param errorHandler The consumer for handling error responses.+ * @param <T> The type of the response.+ * @return The deserialized response of the POST request.+ * @throws UnsupportedOperationException If raw request bodies are not supported by the client.+ */+ default <T extends RESTResponse> T postRaw(+ String path,+ String body,+ String contentType,+ Class<T> responseType,+ Map<String, String> headers,+ Consumer<ErrorResponse> errorHandler) {+ throw new UnsupportedOperationException("Raw POST request bodies are not supported");+ }+/*** Perform a PUT request on the specified path with given information.*diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java b/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.javaindex 22fa794f69..57b6205710 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java@@ -32,6 +32,7 @@ import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;+import javax.annotation.Nullable;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.Catalog;import org.apache.gravitino.NameIdentifier;@@ -72,6 +73,12 @@ import org.apache.gravitino.rel.expressions.transforms.Transform;import org.apache.gravitino.rel.indexes.Index;import org.apache.gravitino.rest.RESTUtils;import org.apache.gravitino.secret.SupportsSecrets;+import org.apache.gravitino.semantic.OssieDocument;+import org.apache.gravitino.semantic.OssieFormat;+import org.apache.gravitino.semantic.SemanticModel;+import org.apache.gravitino.semantic.SemanticModelCatalog;+import org.apache.gravitino.semantic.SemanticModelChange;+import org.apache.gravitino.semantic.SemanticModelDefinition;/*** Relational catalog is a catalog implementation that supports relational database like metadata@@ -79,10 +86,16 @@ import org.apache.gravitino.secret.SupportsSecrets;* catalog is under the metalake.*/class RelationalCatalog extends BaseSchemaCatalog- implements TableCatalog, ViewCatalog, SupportsCredentials, SupportsSecrets {+ implements TableCatalog,+ ViewCatalog,+ SemanticModelCatalog,+ SupportsCredentials,+ SupportsSecrets {public static final String PRIVILEGES = "privileges";+ private final SemanticModelCatalogOperations semanticModelOperations;+RelationalCatalog(Namespace namespace,String name,@@ -93,6 +106,7 @@ class RelationalCatalog extends BaseSchemaCatalogAuditDTO auditDTO,RESTClient restClient) {super(namespace, name, type, provider, comment, properties, auditDTO, restClient);+ this.semanticModelOperations = new SemanticModelCatalogOperations(restClient, namespace, name);}@Override@@ -105,6 +119,58 @@ class RelationalCatalog extends BaseSchemaCatalogreturn this;}+ /** {@inheritDoc} */+ @Override+ public SemanticModelCatalog asSemanticModelCatalog() {+ return this;+ }++ /** {@inheritDoc} */+ @Override+ public NameIdentifier[] listSemanticModels(Namespace namespace) {+ return semanticModelOperations.listSemanticModels(namespace);+ }++ /** {@inheritDoc} */+ @Override+ public SemanticModel loadSemanticModel(NameIdentifier ident) {+ return semanticModelOperations.loadSemanticModel(ident);+ }++ /** {@inheritDoc} */+ @Override+ public SemanticModel createSemanticModel(+ NameIdentifier ident,+ @Nullable String comment,+ SemanticModelDefinition definition,+ Map<String, String> properties) {+ return semanticModelOperations.createSemanticModel(ident, comment, definition, properties);+ }++ /** {@inheritDoc} */+ @Override+ public SemanticModel importOssieDocument(Namespace namespace, OssieDocument document) {+ return semanticModelOperations.importOssieDocument(namespace, document);+ }++ /** {@inheritDoc} */+ @Override+ public OssieDocument exportOssieDocument(NameIdentifier ident, OssieFormat format) {+ return semanticModelOperations.exportOssieDocument(ident, format);+ }++ /** {@inheritDoc} */+ @Override+ public SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes) {+ return semanticModelOperations.alterSemanticModel(ident, changes);+ }++ /** {@inheritDoc} */+ @Override+ public boolean dropSemanticModel(NameIdentifier ident) {+ return semanticModelOperations.dropSemanticModel(ident);+ }+/*** List all the tables under the given Schema namespace.*diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/SemanticModelCatalogOperations.java b/clients/client-java/src/main/java/org/apache/gravitino/client/SemanticModelCatalogOperations.javanew file mode 100644index 0000000000..54b9c51689--- /dev/null+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/SemanticModelCatalogOperations.java@@ -0,0 +1,266 @@+/*+ * 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.google.common.annotations.VisibleForTesting;+import com.google.common.base.Preconditions;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.stream.Collectors;+import javax.annotation.Nullable;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.dto.requests.SemanticModelCreateRequest;+import org.apache.gravitino.dto.requests.SemanticModelUpdateRequest;+import org.apache.gravitino.dto.requests.SemanticModelUpdatesRequest;+import org.apache.gravitino.dto.responses.DropResponse;+import org.apache.gravitino.dto.responses.EntityListResponse;+import org.apache.gravitino.dto.responses.SemanticModelResponse;+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;+import org.apache.gravitino.exceptions.IllegalSemanticModelException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.exceptions.NoSuchSemanticModelException;+import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;+import org.apache.gravitino.rest.RESTUtils;+import org.apache.gravitino.semantic.OssieDocument;+import org.apache.gravitino.semantic.OssieFormat;+import org.apache.gravitino.semantic.SemanticModel;+import org.apache.gravitino.semantic.SemanticModelCatalog;+import org.apache.gravitino.semantic.SemanticModelChange;+import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.hc.core5.http.HttpHeaders;++/** Implements schema-scoped Semantic Model operations through the Gravitino REST API. */+class SemanticModelCatalogOperations implements SemanticModelCatalog {++ private static final String OSSIE_JSON_MEDIA_TYPE = "application/json";+ private static final String OSSIE_YAML_MEDIA_TYPE = "application/yaml";++ private final RESTClient restClient;+ private final Namespace catalogNamespace;+ private final String catalogName;++ SemanticModelCatalogOperations(+ RESTClient restClient, Namespace catalogNamespace, String catalogName) {+ this.restClient = restClient;+ this.catalogNamespace = catalogNamespace;+ this.catalogName = catalogName;+ }++ /** {@inheritDoc} */+ @Override+ public NameIdentifier[] listSemanticModels(Namespace namespace) throws NoSuchSchemaException {+ checkSemanticModelNamespace(namespace);++ Namespace fullNamespace = getSemanticModelFullNamespace(namespace);+ EntityListResponse response =+ restClient.get(+ formatSemanticModelRequestPath(fullNamespace),+ EntityListResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.semanticModelErrorHandler());+ response.validate();++ return Arrays.stream(response.identifiers())+ .map(ident -> NameIdentifier.of(ident.namespace().level(2), ident.name()))+ .toArray(NameIdentifier[]::new);+ }++ /** {@inheritDoc} */+ @Override+ public SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException {+ checkSemanticModelNameIdentifier(ident);++ Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());+ SemanticModelResponse response =+ restClient.get(+ formatSemanticModelRequestPath(fullNamespace)+ + "/"+ + RESTUtils.encodeString(ident.name()),+ SemanticModelResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.semanticModelErrorHandler());+ response.validate();++ return new GenericSemanticModel(response.getSemanticModel(), restClient, fullNamespace);+ }++ /** {@inheritDoc} */+ @Override+ public SemanticModel createSemanticModel(+ NameIdentifier ident,+ @Nullable String comment,+ SemanticModelDefinition definition,+ Map<String, String> properties)+ throws NoSuchSchemaException, SemanticModelAlreadyExistsException,+ IllegalSemanticModelException {+ checkSemanticModelNameIdentifier(ident);+ Preconditions.checkArgument(definition != null, "Semantic Model definition must not be null");++ Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());+ SemanticModelCreateRequest request =+ new SemanticModelCreateRequest(+ ident.name(),+ comment,+ SemanticModelDefinitionDTO.fromDefinition(definition),+ properties);+ request.validate();++ SemanticModelResponse response =+ restClient.post(+ formatSemanticModelRequestPath(fullNamespace),+ request,+ SemanticModelResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.semanticModelErrorHandler());+ response.validate();++ return new GenericSemanticModel(response.getSemanticModel(), restClient, fullNamespace);+ }++ /** {@inheritDoc} */+ @Override+ public SemanticModel importOssieDocument(Namespace namespace, OssieDocument document)+ throws NoSuchSchemaException, SemanticModelAlreadyExistsException,+ IllegalSemanticModelException {+ checkSemanticModelNamespace(namespace);+ Preconditions.checkArgument(document != null, "Ossie document must not be null");++ Namespace fullNamespace = getSemanticModelFullNamespace(namespace);+ SemanticModelResponse response =+ restClient.postRaw(+ formatSemanticModelRequestPath(fullNamespace) + "/ossie",+ document.content(),+ ossieMediaType(document.format()),+ SemanticModelResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.semanticModelErrorHandler());+ response.validate();++ return new GenericSemanticModel(response.getSemanticModel(), restClient, fullNamespace);+ }++ /** {@inheritDoc} */+ @Override+ public OssieDocument exportOssieDocument(NameIdentifier ident, OssieFormat format)+ throws NoSuchSemanticModelException, IllegalSemanticModelException {+ checkSemanticModelNameIdentifier(ident);+ Preconditions.checkArgument(format != null, "Ossie format must not be null");++ Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());+ String content =+ restClient.getRaw(+ formatSemanticModelRequestPath(fullNamespace)+ + "/"+ + RESTUtils.encodeString(ident.name())+ + "/ossie",+ Collections.singletonMap("format", format.name().toLowerCase(Locale.ROOT)),+ Collections.singletonMap(HttpHeaders.ACCEPT, ossieMediaType(format)),+ ErrorHandlers.semanticModelErrorHandler());++ return format == OssieFormat.JSON ? OssieDocument.json(content) : OssieDocument.yaml(content);+ }++ /** {@inheritDoc} */+ @Override+ public SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes)+ throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,+ IllegalSemanticModelException {+ checkSemanticModelNameIdentifier(ident);+ Preconditions.checkArgument(changes != null, "Semantic Model changes must not be null");++ List<SemanticModelUpdateRequest> updates =+ Arrays.stream(changes)+ .map(DTOConverters::toSemanticModelUpdateRequest)+ .collect(Collectors.toList());+ SemanticModelUpdatesRequest request = new SemanticModelUpdatesRequest(updates);+ request.validate();++ Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());+ SemanticModelResponse response =+ restClient.put(+ formatSemanticModelRequestPath(fullNamespace)+ + "/"+ + RESTUtils.encodeString(ident.name()),+ request,+ SemanticModelResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.semanticModelErrorHandler());+ response.validate();++ return new GenericSemanticModel(response.getSemanticModel(), restClient, fullNamespace);+ }++ /** {@inheritDoc} */+ @Override+ public boolean dropSemanticModel(NameIdentifier ident) {+ checkSemanticModelNameIdentifier(ident);++ Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());+ DropResponse response =+ restClient.delete(+ formatSemanticModelRequestPath(fullNamespace)+ + "/"+ + RESTUtils.encodeString(ident.name()),+ DropResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.semanticModelErrorHandler());+ response.validate();++ return response.dropped();+ }++ @VisibleForTesting+ static String formatSemanticModelRequestPath(Namespace namespace) {+ Namespace schemaNamespace = Namespace.of(namespace.level(0), namespace.level(1));+ return new StringBuilder()+ .append(BaseSchemaCatalog.formatSchemaRequestPath(schemaNamespace))+ .append("/")+ .append(RESTUtils.encodeString(namespace.level(2)))+ .append("/semantic-models")+ .toString();+ }++ @VisibleForTesting+ static void checkSemanticModelNamespace(Namespace namespace) {+ Namespace.check(+ namespace != null && namespace.length() == 1,+ "Semantic Model namespace must be non-null and have 1 level, the input namespace is %s",+ namespace);+ }++ @VisibleForTesting+ static void checkSemanticModelNameIdentifier(NameIdentifier ident) {+ NameIdentifier.check(ident != null, "NameIdentifier must not be null");+ NameIdentifier.check(+ ident.name() != null && !ident.name().isEmpty(), "NameIdentifier name must not be empty");+ checkSemanticModelNamespace(ident.namespace());+ }++ private Namespace getSemanticModelFullNamespace(Namespace semanticModelNamespace) {+ return Namespace.of(catalogNamespace.level(0), catalogName, semanticModelNamespace.level(0));+ }++ private static String ossieMediaType(OssieFormat format) {+ return format == OssieFormat.JSON ? OSSIE_JSON_MEDIA_TYPE : OSSIE_YAML_MEDIA_TYPE;+ }+}diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericSemanticModel.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericSemanticModel.javanew file mode 100644index 0000000000..e3ffff8c90--- /dev/null+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericSemanticModel.java@@ -0,0 +1,140 @@+/*+ * 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 static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.Mockito.mock;++import java.time.Instant;+import java.util.LinkedHashMap;+import java.util.Map;+import org.apache.gravitino.Audit;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.dto.AuditDTO;+import org.apache.gravitino.semantic.CustomExtension;+import org.apache.gravitino.semantic.Dataset;+import org.apache.gravitino.semantic.Field;+import org.apache.gravitino.semantic.Relationship;+import org.apache.gravitino.semantic.SemanticModel;+import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.junit.jupiter.api.Test;++public class TestGenericSemanticModel {++ @Test+ public void testNestedDefinitionAndDefensiveState() {+ Dataset absent = dataset("absent");+ Dataset explicitEmpty =+ Dataset.builder()+ .withName("explicit_empty")+ .withSource(NameIdentifier.of("source_catalog", "source_schema", "explicit_empty"))+ .withPrimaryKey(new String[0])+ .withUniqueKeys(new String[0][])+ .withFields(new Field[0])+ .withCustomExtensions(new CustomExtension[0])+ .build();+ SemanticModelDefinition definition =+ SemanticModelDefinition.builder()+ .withDatasets(new Dataset[] {absent, explicitEmpty})+ .withRelationships(new Relationship[0])+ .withCustomExtensions(new CustomExtension[0])+ .build();+ Map<String, String> properties = new LinkedHashMap<>();+ properties.put("certified", "true");+ AuditDTO audit =+ AuditDTO.builder()+ .withCreator("creator")+ .withCreateTime(Instant.parse("2026-08-11T00:00:00Z"))+ .build();+ SemanticModel source = semanticModel(definition, properties, audit);++ RESTClient restClient = mock(RESTClient.class);+ Namespace namespace = Namespace.of("metalake", "catalog", "schema");+ GenericSemanticModel semanticModel = new GenericSemanticModel(source, restClient, namespace);+ GenericSemanticModel equalModel = new GenericSemanticModel(source, restClient, namespace);+ properties.put("changed", "true");++ assertEquals("sales_model", semanticModel.name());+ assertEquals("Sales model", semanticModel.comment());+ assertSame(definition, semanticModel.definition());+ assertArrayEquals(new Dataset[] {absent, explicitEmpty}, semanticModel.definition().datasets());+ assertArrayEquals(new Relationship[0], semanticModel.definition().relationships());+ assertNull(semanticModel.definition().metrics());+ assertArrayEquals(new CustomExtension[0], semanticModel.definition().customExtensions());+ assertNull(semanticModel.definition().datasets()[0].fields());+ assertArrayEquals(new Field[0], semanticModel.definition().datasets()[1].fields());+ assertEquals(Map.of("certified", "true"), semanticModel.properties());+ assertSame(audit, semanticModel.auditInfo());+ assertSame(semanticModel, semanticModel.supportsTags());+ assertThrows(UnsupportedOperationException.class, source::supportsTags);+ assertSame(semanticModel, semanticModel.supportsPolicies());+ assertThrows(UnsupportedOperationException.class, source::supportsPolicies);++ Dataset[] returnedDatasets = semanticModel.definition().datasets();+ returnedDatasets[0] = explicitEmpty;+ assertArrayEquals(new Dataset[] {absent, explicitEmpty}, semanticModel.definition().datasets());+ assertThrows(+ UnsupportedOperationException.class, () -> semanticModel.properties().put("new", "value"));++ assertEquals(semanticModel, equalModel);+ assertEquals(semanticModel.hashCode(), equalModel.hashCode());+ }++ private static SemanticModel semanticModel(+ SemanticModelDefinition definition, Map<String, String> properties, Audit audit) {+ return new SemanticModel() {+ @Override+ public String name() {+ return "sales_model";+ }++ @Override+ public String comment() {+ return "Sales model";+ }++ @Override+ public SemanticModelDefinition definition() {+ return definition;+ }++ @Override+ public Map<String, String> properties() {+ return properties;+ }++ @Override+ public Audit auditInfo() {+ return audit;+ }+ };+ }++ private static Dataset dataset(String name) {+ return Dataset.builder()+ .withName(name)+ .withSource(NameIdentifier.of("source_catalog", "source_schema", name))+ .build();+ }+}diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestHTTPClient.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestHTTPClient.javaindex 62fb95accb..3d8515be9b 100644--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestHTTPClient.java+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestHTTPClient.java@@ -33,6 +33,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.google.common.collect.ImmutableMap;import java.io.IOException;import java.net.SocketTimeoutException;+import java.nio.charset.StandardCharsets;import java.util.Collections;import java.util.Locale;import java.util.Map;@@ -46,6 +47,7 @@ import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.rest.RESTRequest;import org.apache.gravitino.rest.RESTResponse;import org.apache.hc.client5.http.config.ConnectionConfig;+import org.apache.hc.core5.http.HttpHeaders;import org.apache.hc.core5.http.Method;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.Assertions;@@ -113,6 +115,71 @@ public class TestHTTPClient {testHttpMethodOnFailure(Method.GET, false, true);}+ @Test+ public void testRawRequestAndResponseBodies() throws Exception {+ String importPath = "raw_import";+ String yaml = "version: 0.2.0.dev0\nname: sales\n";+ Item responseBody = new Item(1L, "imported");+ ErrorHandler onError = mock(ErrorHandler.class);+ doThrow(new RuntimeException("Failure response")).when(onError).accept(any());++ mockServer+ .when(+ request("/" + importPath)+ .withMethod(Method.POST.name())+ .withHeader(HttpHeaders.CONTENT_TYPE, "application/yaml")+ .withBody(yaml.getBytes(StandardCharsets.UTF_8)))+ .respond(response().withStatusCode(200).withBody(MAPPER.writeValueAsString(responseBody)));++ Item imported =+ restClient.postRaw(+ importPath, yaml, "application/yaml", Item.class, Collections.emptyMap(), onError);+ Assertions.assertEquals(responseBody, imported);++ String exportPath = "raw_export";+ String exported = "version: 0.2.0.dev0\nname: exported\n";+ mockServer+ .when(+ request("/" + exportPath)+ .withMethod(Method.GET.name())+ .withQueryStringParameter("format", "yaml")+ .withHeader(HttpHeaders.ACCEPT, "application/yaml"))+ .respond(+ response()+ .withStatusCode(200)+ .withHeader(HttpHeaders.CONTENT_TYPE, "application/yaml")+ .withBody(exported));++ String actual =+ restClient.getRaw(+ exportPath,+ Collections.singletonMap("format", "yaml"),+ Collections.singletonMap(HttpHeaders.ACCEPT, "application/yaml"),+ onError);+ Assertions.assertEquals(exported, actual);+ verify(onError, never()).accept(any());+ }++ @Test+ public void testRawPostRejectsInvalidBodyMetadata() {+ ErrorHandler onError = mock(ErrorHandler.class);+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ restClient.postRaw(+ "raw_import",+ null,+ "application/yaml",+ Item.class,+ Collections.emptyMap(),+ onError));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ restClient.postRaw(+ "raw_import", "document", " ", Item.class, Collections.emptyMap(), onError));+ }+@Testpublic void testDeleteSuccess() throws Exception {testHttpMethodOnSuccess(Method.DELETE, false, true);diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestSemanticModelCatalog.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSemanticModelCatalog.javanew file mode 100644index 0000000000..d656398b22--- /dev/null+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSemanticModelCatalog.java@@ -0,0 +1,692 @@+/*+ * 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 static org.apache.hc.core5.http.HttpStatus.SC_BAD_REQUEST;+import static org.apache.hc.core5.http.HttpStatus.SC_CONFLICT;+import static org.apache.hc.core5.http.HttpStatus.SC_NOT_FOUND;+import static org.apache.hc.core5.http.HttpStatus.SC_OK;+import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertInstanceOf;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockserver.model.HttpRequest.request;+import static org.mockserver.model.HttpResponse.response;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.JsonNode;+import java.math.BigDecimal;+import java.nio.charset.StandardCharsets;+import java.time.Instant;+import java.util.Arrays;+import java.util.Collections;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.dto.AuditDTO;+import org.apache.gravitino.dto.CatalogDTO;+import org.apache.gravitino.dto.requests.SemanticModelCreateRequest;+import org.apache.gravitino.dto.requests.SemanticModelUpdateRequest;+import org.apache.gravitino.dto.requests.SemanticModelUpdatesRequest;+import org.apache.gravitino.dto.responses.DropResponse;+import org.apache.gravitino.dto.responses.EntityListResponse;+import org.apache.gravitino.dto.responses.ErrorResponse;+import org.apache.gravitino.dto.responses.SemanticModelResponse;+import org.apache.gravitino.dto.semantic.SemanticModelDTO;+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;+import org.apache.gravitino.exceptions.AlreadyExistsException;+import org.apache.gravitino.exceptions.CatalogNotInUseException;+import org.apache.gravitino.exceptions.ConnectionFailedException;+import org.apache.gravitino.exceptions.ForbiddenException;+import org.apache.gravitino.exceptions.IllegalSemanticModelException;+import org.apache.gravitino.exceptions.MetalakeNotInUseException;+import org.apache.gravitino.exceptions.NoSuchCatalogException;+import org.apache.gravitino.exceptions.NoSuchMetalakeException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.exceptions.NoSuchSemanticModelException;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.exceptions.NotInUseException;+import org.apache.gravitino.exceptions.OptimisticLockException;+import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;+import org.apache.gravitino.rest.RESTUtils;+import org.apache.gravitino.semantic.AIContext;+import org.apache.gravitino.semantic.AIContextObject;+import org.apache.gravitino.semantic.CustomExtension;+import org.apache.gravitino.semantic.DataType;+import org.apache.gravitino.semantic.Dataset;+import org.apache.gravitino.semantic.DialectExpression;+import org.apache.gravitino.semantic.Dialects;+import org.apache.gravitino.semantic.Dimension;+import org.apache.gravitino.semantic.Expression;+import org.apache.gravitino.semantic.Field;+import org.apache.gravitino.semantic.Metric;+import org.apache.gravitino.semantic.OssieDocument;+import org.apache.gravitino.semantic.OssieFormat;+import org.apache.gravitino.semantic.Relationship;+import org.apache.gravitino.semantic.SemanticModel;+import org.apache.gravitino.semantic.SemanticModelCatalog;+import org.apache.gravitino.semantic.SemanticModelChange;+import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.hc.core5.http.HttpHeaders;+import org.apache.hc.core5.http.Method;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.mockserver.matchers.Times;+import org.mockserver.model.HttpRequest;++public class TestSemanticModelCatalog extends TestBase {++ private static final String METALAKE_NAME = "semantic_model_metalake";+ private static final String CATALOG_NAME = "semantic_model_catalog";+ private static final String SCHEMA_NAME = "semantic_schema";+ private static final String MODEL_NAME = "sales_model";++ private static Catalog catalog;++ @BeforeAll+ public static void setUp() throws Exception {+ TestBase.setUp();+ catalog = newCatalog(Catalog.Type.RELATIONAL);+ }++ @Test+ public void testOnlyRelationalCatalogExposesSemanticModelCatalog() {+ assertSame(catalog, catalog.asSemanticModelCatalog());+ for (Catalog.Type type :+ new Catalog.Type[] {Catalog.Type.FILESET, Catalog.Type.MESSAGING, Catalog.Type.MODEL}) {+ Catalog nonRelationalCatalog = newCatalog(type);+ assertThrows(+ UnsupportedOperationException.class, nonRelationalCatalog::asSemanticModelCatalog);+ }+ }++ @Test+ public void testListSemanticModelsUsesShortClientIdentifiers() throws JsonProcessingException {+ NameIdentifier first =+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "sales_model");+ NameIdentifier second =+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "inventory_model");+ buildMockResource(+ Method.GET,+ withSlash(semanticModelPath()),+ null,+ new EntityListResponse(new NameIdentifier[] {first, second}),+ SC_OK);++ NameIdentifier[] actual =+ catalog.asSemanticModelCatalog().listSemanticModels(Namespace.of(SCHEMA_NAME));++ assertArrayEquals(+ new NameIdentifier[] {+ NameIdentifier.of(SCHEMA_NAME, "sales_model"),+ NameIdentifier.of(SCHEMA_NAME, "inventory_model")+ },+ actual);+ }++ @Test+ public void testLoadSemanticModelPreservesNestedDefinition() throws JsonProcessingException {+ SemanticModelDTO semanticModelDTO = semanticModelDTO(MODEL_NAME);+ String path = withSlash(semanticModelPath() + "/" + RESTUtils.encodeString(MODEL_NAME));+ buildMockResource(Method.GET, path, null, new SemanticModelResponse(semanticModelDTO), SC_OK);++ SemanticModel loaded =+ catalog+ .asSemanticModelCatalog()+ .loadSemanticModel(NameIdentifier.of(SCHEMA_NAME, MODEL_NAME));++ assertInstanceOf(GenericSemanticModel.class, loaded);+ assertSemanticModel(semanticModelDTO, loaded);+ assertEquals("Use certified metrics", loaded.definition().aiContext().object().instructions());+ assertEquals(+ new BigDecimal("0.95"),+ loaded.definition().aiContext().object().additionalProperties().get("confidence"));+ assertEquals(DataType.DATE_TIME_TZ, loaded.definition().datasets()[0].fields()[0].datatype());+ assertEquals(+ "TRINO",+ loaded.definition().datasets()[0].fields()[1].expression().dialects()[0].dialect());+ assertArrayEquals(new Field[0], loaded.definition().datasets()[1].fields());+ assertNull(loaded.definition().datasets()[2].fields());+ }++ @Test+ public void testCreateSemanticModelUsesDefinitionWrapper() throws JsonProcessingException {+ SemanticModelDefinition definition = definition();+ SemanticModelCreateRequest request =+ new SemanticModelCreateRequest(+ MODEL_NAME,+ "Governed sales metrics",+ SemanticModelDefinitionDTO.fromDefinition(definition),+ Map.of("certified", "true"));+ SemanticModelDTO semanticModelDTO = semanticModelDTO(MODEL_NAME);+ buildMockResource(+ Method.POST,+ withSlash(semanticModelPath()),+ request,+ new SemanticModelResponse(semanticModelDTO),+ SC_OK);++ SemanticModel created =+ catalog+ .asSemanticModelCatalog()+ .createSemanticModel(+ NameIdentifier.of(SCHEMA_NAME, MODEL_NAME),+ "Governed sales metrics",+ definition,+ Map.of("certified", "true"));++ JsonNode body = MAPPER.valueToTree(request);+ assertTrue(body.has("definition"));+ assertFalse(body.has("datasets"));+ assertTrue(body.path("definition").has("datasets"));+ assertTrue(body.path("definition").has("aiContext"));+ assertArrayEquals(+ new String[] {"source_catalog", "source_schema"},+ MAPPER.convertValue(+ body.path("definition").path("datasets").get(0).path("source").path("namespace"),+ String[].class));+ assertEquals(+ "orders",+ body.path("definition").path("datasets").get(0).path("source").path("name").asText());+ assertEquals(+ "DateTimeTz",+ body.path("definition")+ .path("datasets")+ .get(0)+ .path("fields")+ .get(0)+ .path("datatype")+ .asText());+ assertEquals(+ "TRINO",+ body.path("definition")+ .path("datasets")+ .get(0)+ .path("fields")+ .get(1)+ .path("expression")+ .path("dialects")+ .get(0)+ .path("dialect")+ .asText());+ assertTrue(body.path("definition").path("datasets").get(1).path("fields").isEmpty());+ assertFalse(body.path("definition").path("datasets").get(2).has("fields"));+ assertSemanticModel(semanticModelDTO, created);+ }++ @Test+ public void testImportOssieSemanticModelUsesRawDocument() throws JsonProcessingException {+ SemanticModelDTO responseDTO = semanticModelDTO(MODEL_NAME);+ String yaml = "version: 0.2.0.dev0\nname: sales_model\ndatasets: []\n";+ String json = "{\"version\":\"0.2.0.dev0\",\"name\":\"sales_model\",\"datasets\":[]}";++ buildOssieImportResource(+ OssieDocument.yaml(yaml), new SemanticModelResponse(responseDTO), SC_OK);+ buildOssieImportResource(+ OssieDocument.json(json), new SemanticModelResponse(responseDTO), SC_OK);++ SemanticModelCatalog semanticModels = catalog.asSemanticModelCatalog();+ assertSemanticModel(+ responseDTO,+ semanticModels.importOssieDocument(Namespace.of(SCHEMA_NAME), OssieDocument.yaml(yaml)));+ assertSemanticModel(+ responseDTO,+ semanticModels.importOssieDocument(Namespace.of(SCHEMA_NAME), OssieDocument.json(json)));+ }++ @Test+ public void testExportOssieSemanticModelReturnsRawDocument() {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, MODEL_NAME);+ String yaml = "version: 0.2.0.dev0\nname: sales_model\ndatasets: []\n";+ String json = "{\"version\":\"0.2.0.dev0\",\"name\":\"sales_model\",\"datasets\":[]}";++ buildOssieExportResource(OssieFormat.YAML, yaml, SC_OK);+ buildOssieExportResource(OssieFormat.JSON, json, SC_OK);++ SemanticModelCatalog semanticModels = catalog.asSemanticModelCatalog();+ assertEquals(+ OssieDocument.yaml(yaml), semanticModels.exportOssieDocument(ident, OssieFormat.YAML));+ assertEquals(+ OssieDocument.json(json), semanticModels.exportOssieDocument(ident, OssieFormat.JSON));+ }++ @Test+ public void testAlterSemanticModelConvertsAllChangeTypes() throws JsonProcessingException {+ SemanticModelDefinition replacement = definition();+ SemanticModelUpdatesRequest request =+ new SemanticModelUpdatesRequest(+ List.of(+ new SemanticModelUpdateRequest.RenameSemanticModelRequest("renamed_model"),+ new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest(""),+ new SemanticModelUpdateRequest.SetSemanticModelPropertyRequest(+ "owner", "analytics"),+ new SemanticModelUpdateRequest.RemoveSemanticModelPropertyRequest("deprecated"),+ new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(+ SemanticModelDefinitionDTO.fromDefinition(replacement))));+ SemanticModelDTO responseDTO = semanticModelDTO("renamed_model");+ String path = withSlash(semanticModelPath() + "/" + RESTUtils.encodeString(MODEL_NAME));+ buildMockResource(Method.PUT, path, request, new SemanticModelResponse(responseDTO), SC_OK);++ SemanticModel altered =+ catalog+ .asSemanticModelCatalog()+ .alterSemanticModel(+ NameIdentifier.of(SCHEMA_NAME, MODEL_NAME),+ SemanticModelChange.rename("renamed_model"),+ SemanticModelChange.updateComment(""),+ SemanticModelChange.setProperty("owner", "analytics"),+ SemanticModelChange.removeProperty("deprecated"),+ SemanticModelChange.replaceDefinition(replacement));++ JsonNode serializedUpdates = MAPPER.valueToTree(request).path("updates");+ assertEquals(+ List.of("rename", "updateComment", "setProperty", "removeProperty", "replaceDefinition"),+ Arrays.asList(+ serializedUpdates.get(0).path("@type").asText(),+ serializedUpdates.get(1).path("@type").asText(),+ serializedUpdates.get(2).path("@type").asText(),+ serializedUpdates.get(3).path("@type").asText(),+ serializedUpdates.get(4).path("@type").asText()));+ assertEquals("", serializedUpdates.get(1).path("newComment").asText());+ assertTrue(serializedUpdates.get(4).path("definition").has("datasets"));+ assertSemanticModel(responseDTO, altered);+ }++ @Test+ public void testDropSemanticModel() throws JsonProcessingException {+ String path = withSlash(semanticModelPath() + "/" + RESTUtils.encodeString(MODEL_NAME));+ buildMockResource(Method.DELETE, path, null, new DropResponse(true), SC_OK);+ buildMockResource(Method.DELETE, path, null, new DropResponse(false), SC_OK);++ SemanticModelCatalog semanticModels = catalog.asSemanticModelCatalog();+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, MODEL_NAME);+ assertTrue(semanticModels.dropSemanticModel(ident));+ assertFalse(semanticModels.dropSemanticModel(ident));+ }++ @Test+ public void testSemanticModelErrorMappings() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, MODEL_NAME);+ String entityPath = withSlash(semanticModelPath() + "/" + RESTUtils.encodeString(MODEL_NAME));+ ErrorResponse missing =+ ErrorResponse.notFound(+ NoSuchSemanticModelException.class.getSimpleName(), "Semantic Model not found");+ buildMockResource(Method.GET, entityPath, null, missing, SC_NOT_FOUND);+ assertThrows(+ NoSuchSemanticModelException.class,+ () -> catalog.asSemanticModelCatalog().loadSemanticModel(ident));++ for (Class<? extends NotFoundException> exceptionClass :+ List.of(+ NoSuchMetalakeException.class, NoSuchCatalogException.class, NotFoundException.class)) {+ String message = "Resource not found: " + exceptionClass.getSimpleName();+ ErrorResponse notFound = ErrorResponse.notFound(exceptionClass.getSimpleName(), message);+ buildMockResource(Method.GET, entityPath, null, notFound, SC_NOT_FOUND);+ NotFoundException exception =+ assertThrows(+ exceptionClass, () -> catalog.asSemanticModelCatalog().loadSemanticModel(ident));+ assertEquals(exceptionClass, exception.getClass());+ assertTrue(exception.getMessage().contains(message));+ }++ SemanticModelDefinition definition = definition();+ SemanticModelCreateRequest createRequest =+ new SemanticModelCreateRequest(+ MODEL_NAME,+ null,+ SemanticModelDefinitionDTO.fromDefinition(definition),+ Collections.emptyMap());+ ErrorResponse exists =+ ErrorResponse.alreadyExists(+ SemanticModelAlreadyExistsException.class.getSimpleName(),+ "Semantic Model already exists");+ buildMockResource(+ Method.POST, withSlash(semanticModelPath()), createRequest, exists, SC_CONFLICT);+ assertThrows(+ SemanticModelAlreadyExistsException.class,+ () ->+ catalog+ .asSemanticModelCatalog()+ .createSemanticModel(ident, null, definition, Collections.emptyMap()));++ String alreadyExistsMessage = "Resource already exists";+ ErrorResponse genericExists =+ ErrorResponse.alreadyExists(+ AlreadyExistsException.class.getSimpleName(), alreadyExistsMessage);+ buildMockResource(+ Method.POST, withSlash(semanticModelPath()), createRequest, genericExists, SC_CONFLICT);+ AlreadyExistsException alreadyExistsException =+ assertThrows(+ AlreadyExistsException.class,+ () ->+ catalog+ .asSemanticModelCatalog()+ .createSemanticModel(ident, null, definition, Collections.emptyMap()));+ assertEquals(AlreadyExistsException.class, alreadyExistsException.getClass());+ assertTrue(alreadyExistsException.getMessage().contains(alreadyExistsMessage));++ ErrorResponse invalid =+ ErrorResponse.illegalArguments(+ IllegalSemanticModelException.class.getSimpleName(), "Illegal Semantic Model", null);+ buildMockResource(+ Method.POST, withSlash(semanticModelPath()), createRequest, invalid, SC_BAD_REQUEST);+ assertThrows(+ IllegalSemanticModelException.class,+ () ->+ catalog+ .asSemanticModelCatalog()+ .createSemanticModel(ident, null, definition, Collections.emptyMap()));++ OssieDocument invalidDocument = OssieDocument.yaml("invalid: document\n");+ buildOssieImportResource(invalidDocument, invalid, SC_BAD_REQUEST);+ assertThrows(+ IllegalSemanticModelException.class,+ () ->+ catalog+ .asSemanticModelCatalog()+ .importOssieDocument(Namespace.of(SCHEMA_NAME), invalidDocument));++ buildOssieExportResource(OssieFormat.YAML, MAPPER.writeValueAsString(missing), SC_NOT_FOUND);+ assertThrows(+ NoSuchSemanticModelException.class,+ () -> catalog.asSemanticModelCatalog().exportOssieDocument(ident, OssieFormat.YAML));++ ErrorResponse unavailable = ErrorResponse.connectionFailed("Source catalog unavailable");+ assertThrows(+ ConnectionFailedException.class,+ () -> ErrorHandlers.semanticModelErrorHandler().accept(unavailable));++ ErrorResponse forbidden = ErrorResponse.forbidden("Source metadata is not visible", null);+ assertThrows(+ ForbiddenException.class,+ () -> ErrorHandlers.semanticModelErrorHandler().accept(forbidden));++ ErrorResponse unsupported =+ ErrorResponse.unsupportedOperation("Catalog is not relational", null);+ assertThrows(+ UnsupportedOperationException.class,+ () -> ErrorHandlers.semanticModelErrorHandler().accept(unsupported));++ ErrorResponse conflict =+ ErrorResponse.optimisticLockConflict(+ OptimisticLockException.class.getSimpleName(),+ "Concurrent Semantic Model update",+ null);+ assertThrows(+ OptimisticLockException.class,+ () -> ErrorHandlers.semanticModelErrorHandler().accept(conflict));++ for (Class<? extends NotInUseException> exceptionClass :+ List.of(+ CatalogNotInUseException.class,+ MetalakeNotInUseException.class,+ NotInUseException.class)) {+ String message = "Resource not in use: " + exceptionClass.getSimpleName();+ ErrorResponse notInUse =+ ErrorResponse.notInUse(exceptionClass.getSimpleName(), message, null);+ buildMockResource(Method.GET, entityPath, null, notInUse, SC_CONFLICT);+ NotInUseException exception =+ assertThrows(+ exceptionClass, () -> catalog.asSemanticModelCatalog().loadSemanticModel(ident));+ assertEquals(exceptionClass, exception.getClass());+ assertTrue(exception.getMessage().contains(message));+ }+ }++ @Test+ public void testNamespacePathAndBatchValidation() throws JsonProcessingException {+ assertEquals(+ "api/metalakes/semantic_model_metalake/catalogs/semantic_model_catalog/schemas/"+ + "semantic_schema/semantic-models",+ semanticModelPath());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ catalog+ .asSemanticModelCatalog()+ .listSemanticModels(Namespace.of(CATALOG_NAME, SCHEMA_NAME)));+ assertThrows(+ IllegalArgumentException.class,+ () ->+ catalog+ .asSemanticModelCatalog()+ .loadSemanticModel(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME, MODEL_NAME)));+ assertThrows(+ IllegalArgumentException.class,+ () ->+ catalog.asSemanticModelCatalog().importOssieDocument(Namespace.of(SCHEMA_NAME), null));+ assertThrows(+ IllegalArgumentException.class,+ () ->+ catalog+ .asSemanticModelCatalog()+ .exportOssieDocument(NameIdentifier.of(SCHEMA_NAME, MODEL_NAME), null));++ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, MODEL_NAME);+ assertThrows(+ IllegalArgumentException.class,+ () -> catalog.asSemanticModelCatalog().alterSemanticModel(ident));+ assertThrows(+ IllegalArgumentException.class,+ () ->+ catalog+ .asSemanticModelCatalog()+ .alterSemanticModel(ident, (SemanticModelChange[]) null));++ ErrorResponse missingSchema =+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "Schema not found");+ buildMockResource(+ Method.GET, withSlash(semanticModelPath()), null, missingSchema, SC_NOT_FOUND);+ assertThrows(+ NoSuchSchemaException.class,+ () -> catalog.asSemanticModelCatalog().listSemanticModels(Namespace.of(SCHEMA_NAME)));+ }++ @Test+ public void testUnknownSemanticModelChangeIsRejected() {+ SemanticModelChange unknown = new SemanticModelChange() {};+ assertThrows(+ IllegalArgumentException.class, () -> DTOConverters.toSemanticModelUpdateRequest(unknown));+ assertThrows(+ IllegalArgumentException.class, () -> DTOConverters.toSemanticModelUpdateRequest(null));+ }++ private static Catalog newCatalog(Catalog.Type type) {+ CatalogDTO catalogDTO =+ CatalogDTO.builder()+ .withName(CATALOG_NAME)+ .withType(type)+ .withProvider("test")+ .withComment("comment")+ .withProperties(Collections.emptyMap())+ .withAudit(audit())+ .build();+ return DTOConverters.toCatalog(METALAKE_NAME, catalogDTO, client.restClient());+ }++ private static String semanticModelPath() {+ return SemanticModelCatalogOperations.formatSemanticModelRequestPath(+ Namespace.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME));+ }++ private static void buildOssieImportResource(+ OssieDocument document, Object responseBody, int statusCode) throws JsonProcessingException {+ String mediaType =+ document.format() == OssieFormat.JSON ? "application/json" : "application/yaml";+ HttpRequest expectedRequest =+ request(withSlash(semanticModelPath() + "/ossie"))+ .withMethod(Method.POST.name())+ .withHeader(HttpHeaders.CONTENT_TYPE, mediaType);+ expectedRequest =+ document.format() == OssieFormat.JSON+ ? expectedRequest.withBody(document.content())+ : expectedRequest.withBody(document.content().getBytes(StandardCharsets.UTF_8));+ mockServer+ .when(expectedRequest, Times.exactly(1))+ .respond(+ response()+ .withStatusCode(statusCode)+ .withBody(MAPPER.writeValueAsString(responseBody)));+ }++ private static void buildOssieExportResource(+ OssieFormat format, String responseBody, int statusCode) {+ String mediaType = format == OssieFormat.JSON ? "application/json" : "application/yaml";+ mockServer+ .when(+ request(+ withSlash(+ semanticModelPath() + "/" + RESTUtils.encodeString(MODEL_NAME) + "/ossie"))+ .withMethod(Method.GET.name())+ .withQueryStringParameter("format", format.name().toLowerCase(Locale.ROOT))+ .withHeader(HttpHeaders.ACCEPT, mediaType),+ Times.exactly(1))+ .respond(+ response()+ .withStatusCode(statusCode)+ .withHeader(HttpHeaders.CONTENT_TYPE, mediaType)+ .withBody(responseBody));+ }++ private static SemanticModelDTO semanticModelDTO(String name) {+ return SemanticModelDTO.builder()+ .withName(name)+ .withComment("Governed sales metrics")+ .withDefinition(SemanticModelDefinitionDTO.fromDefinition(definition()))+ .withProperties(Map.of("certified", "true"))+ .withAudit(audit())+ .build();+ }++ private static SemanticModelDefinition definition() {+ Map<String, Object> additionalProperties = new LinkedHashMap<>();+ additionalProperties.put("confidence", new BigDecimal("0.95"));+ additionalProperties.put("hints", List.of("month", "region"));+ AIContextObject modelContext =+ AIContextObject.builder()+ .withInstructions("Use certified metrics")+ .withSynonyms(new String[] {"sales", "revenue"})+ .withExamples(new String[] {"Revenue by month"})+ .withAdditionalProperties(additionalProperties)+ .build();+ CustomExtension extension =+ CustomExtension.builder().withVendorName("example").withData("{\"tier\":\"gold\"}").build();+ Field orderTime =+ Field.builder()+ .withName("order_time")+ .withExpression(expression(Dialects.ANSI_SQL, "order_time"))+ .withDimension(Dimension.builder().withIsTime(true).build())+ .withLabel("Order time")+ .withDescription("Time the order was placed")+ .withDatatype(DataType.DATE_TIME_TZ)+ .withAIContext(AIContext.of("Use the business timezone"))+ .withCustomExtensions(new CustomExtension[0])+ .build();+ Field orderAmount =+ Field.builder()+ .withName("order_amount")+ .withExpression(expression("TRINO", "order_amount"))+ .withDatatype(DataType.DECIMAL)+ .withCustomExtensions(new CustomExtension[] {extension})+ .build();+ Dataset orders =+ Dataset.builder()+ .withName("orders")+ .withSource(NameIdentifier.of("source_catalog", "source_schema", "orders"))+ .withPrimaryKey(new String[] {"order_id"})+ .withUniqueKeys(new String[0][])+ .withDescription("Governed order facts")+ .withAIContext(AIContext.of("Use completed orders"))+ .withFields(new Field[] {orderTime, orderAmount})+ .withCustomExtensions(new CustomExtension[0])+ .build();+ Dataset customers =+ Dataset.builder()+ .withName("customers")+ .withSource(NameIdentifier.of("source_catalog", "source_schema", "customers"))+ .withUniqueKeys(new String[][] {{"email"}})+ .withFields(new Field[0])+ .build();+ Dataset regions =+ Dataset.builder()+ .withName("regions")+ .withSource(NameIdentifier.of("source_catalog", "source_schema", "regions"))+ .build();+ Relationship relationship =+ Relationship.builder()+ .withName("orders_to_customers")+ .withFrom("orders")+ .withTo("customers")+ .withFromColumns(new String[] {"customer_id"})+ .withToColumns(new String[] {"id"})+ .withAIContext(AIContext.of("Join orders to customer attributes"))+ .withCustomExtensions(new CustomExtension[] {extension})+ .build();+ Metric revenue =+ Metric.builder()+ .withName("revenue")+ .withExpression(expression(Dialects.ANSI_SQL, "SUM(orders.order_amount)"))+ .withDescription("Certified revenue")+ .withDatatype(DataType.DECIMAL)+ .withAIContext(AIContext.of(modelContext))+ .withCustomExtensions(new CustomExtension[] {extension})+ .build();+ return SemanticModelDefinition.builder()+ .withAIContext(AIContext.of(modelContext))+ .withDatasets(new Dataset[] {orders, customers, regions})+ .withRelationships(new Relationship[] {relationship})+ .withMetrics(new Metric[] {revenue})+ .withCustomExtensions(new CustomExtension[] {extension})+ .build();+ }++ private static Expression expression(String dialect, String value) {+ return Expression.builder()+ .withDialects(+ new DialectExpression[] {+ DialectExpression.builder().withDialect(dialect).withExpression(value).build()+ })+ .build();+ }++ private static AuditDTO audit() {+ return AuditDTO.builder()+ .withCreator("creator")+ .withCreateTime(Instant.parse("2026-08-11T00:00:00Z"))+ .withLastModifier("modifier")+ .withLastModifiedTime(Instant.parse("2026-08-12T00:00:00Z"))+ .build();+ }++ private static void assertSemanticModel(SemanticModel expected, SemanticModel actual) {+ assertEquals(expected.name(), actual.name());+ assertEquals(expected.comment(), actual.comment());+ assertEquals(expected.definition(), actual.definition());+ assertEquals(expected.properties(), actual.properties());+ assertEquals(expected.auditInfo(), actual.auditInfo());+ }+}diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportPolicies.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportPolicies.javaindex dbd2f9c2fe..a2033f306f 100644--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportPolicies.java+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportPolicies.java@@ -27,10 +27,12 @@ import com.fasterxml.jackson.core.JsonProcessingException;import com.google.common.collect.ImmutableMap;import java.util.Collections;import java.util.Locale;+import java.util.Optional;import java.util.Set;import org.apache.gravitino.Catalog;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.MetadataObjects;+import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.Schema;import org.apache.gravitino.dto.AuditDTO;@@ -44,6 +46,8 @@ import org.apache.gravitino.dto.rel.TableDTO;import org.apache.gravitino.dto.responses.ErrorResponse;import org.apache.gravitino.dto.responses.NameListResponse;import org.apache.gravitino.dto.responses.PolicyListResponse;+import org.apache.gravitino.dto.semantic.SemanticModelDTO;+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;import org.apache.gravitino.exceptions.NotFoundException;import org.apache.gravitino.file.Fileset;import org.apache.gravitino.messaging.Topic;@@ -51,6 +55,9 @@ import org.apache.gravitino.policy.Policy;import org.apache.gravitino.policy.SupportsPolicies;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.semantic.Dataset;+import org.apache.gravitino.semantic.SemanticModel;+import org.apache.gravitino.semantic.SemanticModelDefinition;import org.apache.hc.core5.http.Method;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;@@ -74,6 +81,8 @@ public class TestSupportPolicies extends TestBase {private static Topic genericTopic;+ private static SemanticModel genericSemanticModel;+private final Set<MetadataObject.Type> supportedObjectTypes =Collections.singleton(MetadataObject.Type.FILESET);private final PolicyContentDTO.CustomContentDTO contentDTO =@@ -172,6 +181,27 @@ public class TestSupportPolicies extends TestBase {.build(),client.restClient(),Namespace.of(METALAKE_NAME, "catalog1", "schema1"));++ genericSemanticModel =+ new GenericSemanticModel(+ SemanticModelDTO.builder()+ .withName("semantic_model1")+ .withDefinition(+ SemanticModelDefinitionDTO.fromDefinition(+ SemanticModelDefinition.builder()+ .withDatasets(+ new Dataset[] {+ Dataset.builder()+ .withName("orders")+ .withSource(+ NameIdentifier.of("catalog1", "schema1", "orders"))+ .build()+ })+ .build()))+ .withAudit(AuditDTO.builder().withCreator("test").build())+ .build(),+ client.restClient(),+ Namespace.of(METALAKE_NAME, "catalog1", "schema1"));}@Test@@ -217,6 +247,15 @@ public class TestSupportPolicies extends TestBase {MetadataObjects.of("catalog1.schema1", genericTopic.name(), MetadataObject.Type.TOPIC));}+ /** Verifies policy name lookup and error mapping for Semantic Models. */+ @Test+ public void testListPoliciesForSemanticModel() throws JsonProcessingException {+ testListPolicies(+ genericSemanticModel.supportsPolicies(),+ MetadataObjects.of(+ "catalog1.schema1", genericSemanticModel.name(), MetadataObject.Type.SEMANTIC_MODEL));+ }+@Testpublic void testListPoliciesInfoForCatalog() throws JsonProcessingException {testListPoliciesInfo(@@ -260,6 +299,15 @@ public class TestSupportPolicies extends TestBase {MetadataObjects.of("catalog1.schema1", genericTopic.name(), MetadataObject.Type.TOPIC));}+ /** Verifies policy details, inheritance flags, and error mapping for Semantic Models. */+ @Test+ public void testListPoliciesInfoForSemanticModel() throws JsonProcessingException {+ testListPoliciesInfo(+ genericSemanticModel.supportsPolicies(),+ MetadataObjects.of(+ "catalog1.schema1", genericSemanticModel.name(), MetadataObject.Type.SEMANTIC_MODEL));+ }+private void testListPolicies(SupportsPolicies supportsPolicies, MetadataObject metadataObject)throws JsonProcessingException {String path =@@ -318,6 +366,7 @@ public class TestSupportPolicies extends TestBase {.withName("policy1").withPolicyType("custom").withContent(contentDTO)+ .withInherited(Optional.of(false)).withAudit(AuditDTO.builder().withCreator("test").build()).build();PolicyDTO policy2 =@@ -325,20 +374,25 @@ public class TestSupportPolicies extends TestBase {.withName("policy2").withPolicyType("custom").withContent(contentDTO)+ .withInherited(Optional.of(true)).withAudit(AuditDTO.builder().withCreator("test").build()).build();PolicyDTO[] policies = new PolicyDTO[] {policy1, policy2};PolicyListResponse resp = new PolicyListResponse(policies);- buildMockResource(Method.GET, path, null, resp, SC_OK);+ buildMockResource(+ Method.GET, path, Collections.singletonMap("details", "true"), null, resp, SC_OK);Policy[] actualPolicies = supportsPolicies.listPolicyInfos();Assertions.assertEquals(2, actualPolicies.length);Assertions.assertEquals("policy1", actualPolicies[0].name());Assertions.assertEquals("policy2", actualPolicies[1].name());+ Assertions.assertFalse(actualPolicies[0].inherited().orElseThrow());+ Assertions.assertTrue(actualPolicies[1].inherited().orElseThrow());// Return empty listPolicyListResponse resp1 = new PolicyListResponse(new PolicyDTO[0]);- buildMockResource(Method.GET, path, null, resp1, SC_OK);+ buildMockResource(+ Method.GET, path, Collections.singletonMap("details", "true"), null, resp1, SC_OK);Policy[] actualPolicies1 = supportsPolicies.listPolicyInfos();Assertions.assertArrayEquals(new Policy[0], actualPolicies1);@@ -346,16 +400,30 @@ public class TestSupportPolicies extends TestBase {// Test throw NotFoundExceptionErrorResponse errorResp =ErrorResponse.notFound(NotFoundException.class.getSimpleName(), "mock error");- buildMockResource(Method.GET, path, null, errorResp, SC_NOT_FOUND);-- Throwable ex = Assertions.assertThrows(NotFoundException.class, supportsPolicies::listPolicies);+ buildMockResource(+ Method.GET,+ path,+ Collections.singletonMap("details", "true"),+ null,+ errorResp,+ SC_NOT_FOUND);++ Throwable ex =+ Assertions.assertThrows(NotFoundException.class, supportsPolicies::listPolicyInfos);Assertions.assertTrue(ex.getMessage().contains("mock error"));// Test throw internal errorErrorResponse errorResp1 = ErrorResponse.internalError("mock error");- buildMockResource(Method.GET, path, null, errorResp1, SC_INTERNAL_SERVER_ERROR);-- Throwable ex1 = Assertions.assertThrows(RuntimeException.class, supportsPolicies::listPolicies);+ buildMockResource(+ Method.GET,+ path,+ Collections.singletonMap("details", "true"),+ null,+ errorResp1,+ SC_INTERNAL_SERVER_ERROR);++ Throwable ex1 =+ Assertions.assertThrows(RuntimeException.class, supportsPolicies::listPolicyInfos);Assertions.assertTrue(ex1.getMessage().contains("mock error"));}}diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportTags.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportTags.javaindex 6f73848ed5..446fd2bf61 100644--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportTags.java+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportTags.java@@ -30,6 +30,7 @@ import java.util.Locale;import org.apache.gravitino.Catalog;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.MetadataObjects;+import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.Schema;import org.apache.gravitino.dto.AuditDTO;@@ -48,6 +49,8 @@ import org.apache.gravitino.dto.responses.ErrorResponse;import org.apache.gravitino.dto.responses.NameListResponse;import org.apache.gravitino.dto.responses.TagListResponse;import org.apache.gravitino.dto.responses.TagResponse;+import org.apache.gravitino.dto.semantic.SemanticModelDTO;+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;import org.apache.gravitino.dto.tag.TagDTO;import org.apache.gravitino.exceptions.NoSuchTagException;import org.apache.gravitino.exceptions.NotFoundException;@@ -60,6 +63,9 @@ import org.apache.gravitino.rel.Dialects;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.View;import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.semantic.Dataset;+import org.apache.gravitino.semantic.SemanticModel;+import org.apache.gravitino.semantic.SemanticModelDefinition;import org.apache.gravitino.tag.SupportsTags;import org.apache.gravitino.tag.Tag;import org.apache.gravitino.tag.TagValue;@@ -95,6 +101,8 @@ public class TestSupportTags extends TestBase {private static Function genericFunction;+ private static SemanticModel genericSemanticModel;+@BeforeAllpublic static void setUp() throws Exception {TestBase.setUp();@@ -223,6 +231,79 @@ public class TestSupportTags extends TestBase {.build(),client.restClient(),Namespace.of(METALAKE_NAME, "catalog1", "schema1"));++ genericSemanticModel =+ new GenericSemanticModel(+ SemanticModelDTO.builder()+ .withName("semantic_model1")+ .withDefinition(+ SemanticModelDefinitionDTO.fromDefinition(+ SemanticModelDefinition.builder()+ .withDatasets(+ new Dataset[] {+ Dataset.builder()+ .withName("orders")+ .withSource(+ NameIdentifier.of("catalog1", "schema1", "orders"))+ .build()+ })+ .build()))+ .withAudit(AuditDTO.builder().withCreator("test").build())+ .build(),+ client.restClient(),+ Namespace.of(METALAKE_NAME, "catalog1", "schema1"));+ }++ /**+ * Verifies Semantic Model tag name listing and error mapping.+ *+ * @throws JsonProcessingException if a mock response cannot be serialized+ */+ @Test+ public void testListTagsForSemanticModel() throws JsonProcessingException {+ testListTags(+ genericSemanticModel.supportsTags(),+ MetadataObjects.of(+ "catalog1.schema1", genericSemanticModel.name(), MetadataObject.Type.SEMANTIC_MODEL));+ }++ /**+ * Verifies Semantic Model detailed tag listing and error mapping.+ *+ * @throws JsonProcessingException if a mock response cannot be serialized+ */+ @Test+ public void testListTagsInfoForSemanticModel() throws JsonProcessingException {+ testListTagsInfo(+ genericSemanticModel.supportsTags(),+ MetadataObjects.of(+ "catalog1.schema1", genericSemanticModel.name(), MetadataObject.Type.SEMANTIC_MODEL));+ }++ /**+ * Verifies fetching a Semantic Model tag and mapping missing-tag errors.+ *+ * @throws JsonProcessingException if a mock response cannot be serialized+ */+ @Test+ public void testGetTagForSemanticModel() throws JsonProcessingException {+ testGetTag(+ genericSemanticModel.supportsTags(),+ MetadataObjects.of(+ "catalog1.schema1", genericSemanticModel.name(), MetadataObject.Type.SEMANTIC_MODEL));+ }++ /**+ * Verifies both Semantic Model tag association overloads, including value media types.+ *+ * @throws JsonProcessingException if a mock response cannot be serialized+ */+ @Test+ public void testAssociateTagsForSemanticModel() throws JsonProcessingException {+ testAssociateTags(+ genericSemanticModel.supportsTags(),+ MetadataObjects.of(+ "catalog1.schema1", genericSemanticModel.name(), MetadataObject.Type.SEMANTIC_MODEL));}@Testdiff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/SemanticModelIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/SemanticModelIT.javanew file mode 100644index 0000000000..e39bb0c428--- /dev/null+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/SemanticModelIT.java@@ -0,0 +1,1358 @@+/*+ * 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.integration.test;++import static org.apache.gravitino.semantic.CustomExtension.GRAVITINO_PROPERTIES_VENDOR;+import static org.apache.gravitino.semantic.OssieVersion.DEFAULT_VERSION;+import static org.apache.gravitino.semantic.SemanticModel.PROPERTY_OSSIE_VERSION;+import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.DeserializationFeature;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;+import java.math.BigDecimal;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.time.Duration;+import java.util.Arrays;+import java.util.Collections;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.stream.Collectors;+import java.util.stream.Stream;+import javax.annotation.Nullable;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.MetadataObjects;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.client.GravitinoMetalake;+import org.apache.gravitino.exceptions.IllegalSemanticModelException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.exceptions.NoSuchSemanticModelException;+import org.apache.gravitino.exceptions.NoSuchTagException;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;+import org.apache.gravitino.integration.test.util.BaseIT;+import org.apache.gravitino.integration.test.util.GravitinoITUtils;+import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.PolicyContents;+import org.apache.gravitino.policy.SupportsPolicies;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.TableCatalog;+import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.semantic.AIContext;+import org.apache.gravitino.semantic.AIContextObject;+import org.apache.gravitino.semantic.CustomExtension;+import org.apache.gravitino.semantic.DataType;+import org.apache.gravitino.semantic.Dataset;+import org.apache.gravitino.semantic.DialectExpression;+import org.apache.gravitino.semantic.Dialects;+import org.apache.gravitino.semantic.Dimension;+import org.apache.gravitino.semantic.Expression;+import org.apache.gravitino.semantic.Field;+import org.apache.gravitino.semantic.Metric;+import org.apache.gravitino.semantic.OssieDocument;+import org.apache.gravitino.semantic.OssieFormat;+import org.apache.gravitino.semantic.Relationship;+import org.apache.gravitino.semantic.SemanticModel;+import org.apache.gravitino.semantic.SemanticModelCatalog;+import org.apache.gravitino.semantic.SemanticModelChange;+import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.tag.SupportsTags;+import org.apache.gravitino.tag.Tag;+import org.apache.gravitino.tag.TagValue;+import org.apache.gravitino.tag.TagValueConstraint;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.Arguments;+import org.junit.jupiter.params.provider.EnumSource;+import org.junit.jupiter.params.provider.MethodSource;+import org.junit.jupiter.params.provider.NullSource;+import org.junit.jupiter.params.provider.ValueSource;++/** Exercises the Semantic Model Java client against a real embedded Gravitino server. */+public class SemanticModelIT extends BaseIT {++ private static final ObjectMapper JSON_MAPPER =+ new ObjectMapper().enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);+ private static final ObjectMapper YAML_MAPPER =+ new ObjectMapper(new YAMLFactory()).enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);+ private static final String METALAKE_NAME =+ GravitinoITUtils.genRandomName("semantic_model_it_metalake");+ private static final String CATALOG_NAME = "semantic_model_it_catalog";+ private static final String SCHEMA_NAME = "semantic_model_it_schema";+ private static final String ORDERS_TABLE = "orders";+ private static final String CUSTOMERS_TABLE = "customers";+ private static final String MODEL_NAME = "sales_model";+ private static final String RENAMED_MODEL_NAME = "certified_sales_model";+ private static final String OSSIE_MODEL_NAME = "ossie_sales_model";+ private static final String INVALID_MODEL_NAME = "invalid_source_model";++ private final HttpClient httpClient = HttpClient.newHttpClient();++ private GravitinoMetalake metalake;+ private Catalog catalog;+ private SemanticModelCatalog semanticModelCatalog;++ @BeforeAll+ public void setUp() {+ metalake = client.createMetalake(METALAKE_NAME, "metalake comment", Collections.emptyMap());++ Map<String, String> catalogProperties = new LinkedHashMap<>();+ catalogProperties.put("catalog-backend", "jdbc");+ catalogProperties.put("warehouse", System.getProperty("java.io.tmpdir") + "/" + METALAKE_NAME);+ catalogProperties.put("uri", "jdbc:h2:mem:" + METALAKE_NAME + ";DB_CLOSE_DELAY=-1;MODE=MYSQL");+ catalogProperties.put("jdbc-driver", "org.h2.Driver");+ catalogProperties.put("jdbc-initialize", "true");+ catalog =+ metalake.createCatalog(+ CATALOG_NAME,+ Catalog.Type.RELATIONAL,+ "lakehouse-iceberg",+ "catalog comment",+ catalogProperties);+ catalog.asSchemas().createSchema(SCHEMA_NAME, "schema comment", Collections.emptyMap());++ TableCatalog tables = catalog.asTableCatalog();+ tables.createTable(+ NameIdentifier.of(SCHEMA_NAME, ORDERS_TABLE),+ new Column[] {+ Column.of("order_id", Types.LongType.get()),+ Column.of("customer_id", Types.LongType.get()),+ Column.of("order_time", Types.StringType.get()),+ Column.of("order_amount", Types.StringType.get())+ },+ "orders source",+ Collections.emptyMap());+ tables.createTable(+ NameIdentifier.of(SCHEMA_NAME, CUSTOMERS_TABLE),+ new Column[] {+ Column.of("id", Types.LongType.get()), Column.of("email", Types.StringType.get())+ },+ "customers source",+ Collections.emptyMap());++ semanticModelCatalog = catalog.asSemanticModelCatalog();+ }++ /**+ * Removes models, policies, and tags left by a test so failures do not affect subsequent tests.+ */+ @AfterEach+ public void cleanUpSemanticModels() {+ for (NameIdentifier ident :+ semanticModelCatalog.listSemanticModels(Namespace.of(SCHEMA_NAME))) {+ semanticModelCatalog.dropSemanticModel(ident);+ }+ for (String policy : metalake.listPolicies()) {+ metalake.deletePolicy(policy);+ }+ for (String tag : metalake.listTags()) {+ metalake.deleteTag(tag);+ }+ }++ @AfterAll+ public void tearDown() {+ if (metalake != null) {+ metalake.dropCatalog(CATALOG_NAME, true);+ client.dropMetalake(METALAKE_NAME, true);+ }+ }++ @Test+ public void testSemanticModelLifecycleRoundTrip() {+ NameIdentifier modelIdent = NameIdentifier.of(SCHEMA_NAME, MODEL_NAME);+ SemanticModelDefinition definition = initialDefinition();+ Map<String, String> properties =+ new LinkedHashMap<>(Map.of("certified", "true", "deprecated", "true"));++ assertArrayEquals(+ new NameIdentifier[0], semanticModelCatalog.listSemanticModels(Namespace.of(SCHEMA_NAME)));++ SemanticModel created =+ semanticModelCatalog.createSemanticModel(+ modelIdent, "Governed sales metrics", definition, properties);+ Map<String, String> expectedProperties = new LinkedHashMap<>(properties);+ expectedProperties.put(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION);+ assertSemanticModel(+ MODEL_NAME, "Governed sales metrics", definition, expectedProperties, created);+ assertNotNull(created.auditInfo());+ assertNotNull(created.auditInfo().creator());+ assertNotNull(created.auditInfo().createTime());+ assertEquals("Use certified metrics", created.definition().aiContext().object().instructions());+ assertEquals(+ new BigDecimal("0.95"),+ created.definition().aiContext().object().additionalProperties().get("confidence"));+ assertEquals(DataType.DATE_TIME_TZ, created.definition().datasets()[0].fields()[0].datatype());+ assertEquals(+ "TRINO",+ created.definition().datasets()[0].fields()[1].expression().dialects()[0].dialect());+ assertArrayEquals(new Field[0], created.definition().datasets()[1].fields());++ assertThrows(+ SemanticModelAlreadyExistsException.class,+ () ->+ semanticModelCatalog.createSemanticModel(+ modelIdent, "duplicate", definition, Collections.emptyMap()));+ assertArrayEquals(+ new NameIdentifier[] {modelIdent},+ semanticModelCatalog.listSemanticModels(Namespace.of(SCHEMA_NAME)));++ SemanticModel loaded = semanticModelCatalog.loadSemanticModel(modelIdent);+ assertSemanticModel(+ MODEL_NAME, "Governed sales metrics", definition, expectedProperties, loaded);++ SemanticModelDefinition replacement = replacementDefinition();+ SemanticModel altered =+ semanticModelCatalog.alterSemanticModel(+ modelIdent,+ SemanticModelChange.rename(RENAMED_MODEL_NAME),+ SemanticModelChange.updateComment(""),+ SemanticModelChange.setProperty("owner", "analytics"),+ SemanticModelChange.removeProperty("deprecated"),+ SemanticModelChange.replaceDefinition(replacement));+ Map<String, String> alteredProperties =+ Map.of("certified", "true", "owner", "analytics", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION);+ assertSemanticModel(RENAMED_MODEL_NAME, "", replacement, alteredProperties, altered);+ assertNull(altered.definition().datasets()[0].fields());+ assertArrayEquals(new Field[0], altered.definition().datasets()[1].fields());+ assertArrayEquals(new Relationship[0], altered.definition().relationships());+ assertArrayEquals(new Metric[0], altered.definition().metrics());+ assertArrayEquals(new CustomExtension[0], altered.definition().customExtensions());++ assertThrows(+ NoSuchSemanticModelException.class,+ () -> semanticModelCatalog.loadSemanticModel(modelIdent));+ NameIdentifier renamedIdent = NameIdentifier.of(SCHEMA_NAME, RENAMED_MODEL_NAME);+ SemanticModel reloaded = semanticModelCatalog.loadSemanticModel(renamedIdent);+ assertSemanticModel(RENAMED_MODEL_NAME, "", replacement, alteredProperties, reloaded);++ assertTrue(semanticModelCatalog.dropSemanticModel(renamedIdent));+ assertFalse(semanticModelCatalog.dropSemanticModel(renamedIdent));+ assertArrayEquals(+ new NameIdentifier[0], semanticModelCatalog.listSemanticModels(Namespace.of(SCHEMA_NAME)));+ assertThrows(+ NoSuchSemanticModelException.class,+ () -> semanticModelCatalog.loadSemanticModel(renamedIdent));+ }++ @Test+ public void testCreateSemanticModelRejectsInvalidSourceIdentifier() {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, INVALID_MODEL_NAME);+ Dataset invalidSource =+ Dataset.builder()+ .withName("orders")+ .withSource(NameIdentifier.of(SCHEMA_NAME, ORDERS_TABLE))+ .build();+ SemanticModelDefinition definition =+ SemanticModelDefinition.builder().withDatasets(new Dataset[] {invalidSource}).build();++ IllegalSemanticModelException exception =+ assertThrows(+ IllegalSemanticModelException.class,+ () ->+ semanticModelCatalog.createSemanticModel(+ ident, null, definition, Collections.emptyMap()));+ assertTrue(exception.getMessage().contains("Source must contain catalog.schema.name"));+ assertThrows(+ NoSuchSemanticModelException.class, () -> semanticModelCatalog.loadSemanticModel(ident));+ }++ /**+ * Verifies that a rejected create leaves no model behind.+ *+ * @param scenario the invalid-source scenario+ * @param definition the invalid definition+ * @param expectedMessage the server validation message+ */+ @ParameterizedTest(name = "{0}")+ @MethodSource("invalidSourceDefinitions")+ public void testCreateSemanticModelRejectsInvalidSource(+ String scenario, SemanticModelDefinition definition, String expectedMessage) {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, INVALID_MODEL_NAME);++ IllegalSemanticModelException exception =+ assertThrows(+ IllegalSemanticModelException.class,+ () ->+ semanticModelCatalog.createSemanticModel(+ ident, null, definition, Collections.emptyMap()));+ assertTrue(exception.getMessage().contains(expectedMessage), scenario);+ assertFalse(semanticModelCatalog.semanticModelExists(ident));+ }++ /**+ * Verifies that an invalid replacement prevents every change in the request from being persisted.+ *+ * @param scenario the invalid-source scenario+ * @param definition the invalid definition+ * @param expectedMessage the server validation message+ */+ @ParameterizedTest(name = "{0}")+ @MethodSource("invalidSourceDefinitions")+ public void testReplaceDefinitionRejectsInvalidSourceAtomically(+ String scenario, SemanticModelDefinition definition, String expectedMessage) {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, MODEL_NAME);+ SemanticModel created =+ semanticModelCatalog.createSemanticModel(+ ident, "Original model", initialDefinition(), Map.of("owner", "analytics"));++ // Every replacement must be validated, even if a later replacement is valid.+ IllegalSemanticModelException exception =+ assertThrows(+ IllegalSemanticModelException.class,+ () ->+ semanticModelCatalog.alterSemanticModel(+ ident,+ SemanticModelChange.updateComment("Must not be persisted"),+ SemanticModelChange.setProperty("owner", "another-team"),+ SemanticModelChange.replaceDefinition(definition),+ SemanticModelChange.replaceDefinition(replacementDefinition())));+ assertTrue(exception.getMessage().contains(expectedMessage), scenario);+ assertSemanticModel(+ created.name(),+ created.comment(),+ created.definition(),+ created.properties(),+ semanticModelCatalog.loadSemanticModel(ident));+ }++ /**+ * Verifies that YAML and JSON imports propagate source validation failures without persisting.+ *+ * @param scenario the invalid-source scenario and document format+ * @param document the document with an invalid source+ * @param expectedMessage the server validation message+ */+ @ParameterizedTest(name = "{0}")+ @MethodSource("invalidOssieSourceDocuments")+ public void testOssieImportRejectsInvalidSource(+ String scenario, OssieDocument document, String expectedMessage) {+ IllegalSemanticModelException exception =+ assertThrows(+ IllegalSemanticModelException.class,+ () -> semanticModelCatalog.importOssieDocument(Namespace.of(SCHEMA_NAME), document));+ assertTrue(exception.getMessage().contains(expectedMessage), scenario);+ assertFalse(+ semanticModelCatalog.semanticModelExists(+ NameIdentifier.of(SCHEMA_NAME, INVALID_MODEL_NAME)));+ }++ /**+ * Verifies full native definitions and properties survive export, import, and cross-format+ * export.+ *+ * @param format the initial export format+ * @throws Exception if a document cannot be parsed+ */+ @ParameterizedTest+ @EnumSource(OssieFormat.class)+ public void testOssieImportExportRoundTrip(OssieFormat format) throws Exception {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, OSSIE_MODEL_NAME);+ Map<String, String> properties =+ Map.of(+ "owner",+ "analytics",+ "label",+ "Revenue — 收入",+ "empty",+ "",+ PROPERTY_OSSIE_VERSION,+ "future-version");+ SemanticModel original =+ semanticModelCatalog.createSemanticModel(+ ident, "Revenue — 收入\nCertified metrics", initialDefinition(), properties);+ OssieDocument exported = semanticModelCatalog.exportOssieDocument(ident, format);+ assertEquals(format, exported.format());+ JsonNode root = parseOssieDocument(exported);+ assertEquals(OSSIE_MODEL_NAME, root.path("name").textValue());+ assertEquals(original.comment(), root.path("description").textValue());+ assertFalse(root.has("semanticModel"));+ assertFalse(root.has("definition"));+ assertFalse(root.has("properties"));+ assertFalse(root.has("audit"));+ assertEquals("order_id", root.at("/datasets/0/primary_key/0").textValue());+ assertTrue(root.at("/datasets/0/unique_keys").isEmpty());+ assertEquals("email", root.at("/datasets/1/unique_keys/0/0").textValue());+ assertEquals("DateTimeTz", root.at("/datasets/0/fields/0/datatype").textValue());+ assertTrue(root.at("/datasets/0/fields/0/dimension/is_time").booleanValue());+ assertEquals(+ "TRINO", root.at("/datasets/0/fields/1/expression/dialects/0/dialect").textValue());+ assertEquals("customer_id", root.at("/relationships/0/from_columns/0").textValue());+ assertEquals("id", root.at("/relationships/0/to_columns/0").textValue());+ assertEquals("Decimal", root.at("/metrics/0/datatype").textValue());+ assertEquals(new BigDecimal("0.95"), root.at("/ai_context/confidence").decimalValue());+ assertOssieProperties(root, properties);+ assertTrue(semanticModelCatalog.dropSemanticModel(ident));+ SemanticModel reimported =+ semanticModelCatalog.importOssieDocument(Namespace.of(SCHEMA_NAME), exported);+ assertSemanticModel(+ original.name(), original.comment(), original.definition(), properties, reimported);+ assertSemanticModel(+ original.name(),+ original.comment(),+ original.definition(),+ properties,+ semanticModelCatalog.loadSemanticModel(ident));+ OssieFormat otherFormat = format == OssieFormat.JSON ? OssieFormat.YAML : OssieFormat.JSON;+ OssieDocument other = semanticModelCatalog.exportOssieDocument(ident, otherFormat);+ assertEquals(otherFormat, other.format());+ assertEquals(root, parseOssieDocument(other));+ }++ /**+ * Imports an independently constructed document without using the production converter.+ *+ * @param format the import format+ * @throws Exception if a document cannot be serialized or parsed+ */+ @ParameterizedTest+ @EnumSource(OssieFormat.class)+ public void testOssieStandaloneDocumentImport(OssieFormat format) throws Exception {+ ObjectNode document = ossieModelDocument();+ Map<String, String> properties =+ Map.of(+ "owner",+ "analytics",+ "label",+ "Revenue — 收入",+ "empty",+ "",+ PROPERTY_OSSIE_VERSION,+ "future-version");+ document.put("version", "future-version");+ document.put("description", "Revenue — 收入\nCertified metrics");+ document+ .putObject("ai_context")+ .put("instructions", "Use certified metrics")+ .put("confidence", new BigDecimal("0.1234567890123456789"))+ .putArray("hints")+ .addNull()+ .add("month");+ ObjectNode dataset = (ObjectNode) document.path("datasets").get(0);+ dataset.put("source", "`" + CATALOG_NAME + "`.`" + SCHEMA_NAME + "`.`" + ORDERS_TABLE + "`");+ dataset.putArray("primary_key").add("order_id");+ dataset+ .putArray("custom_extensions")+ .addObject()+ .put("vendor_name", GRAVITINO_PROPERTIES_VENDOR)+ .put("data", "opaque dataset payload");+ document+ .putArray("custom_extensions")+ .addObject()+ .put("vendor_name", "GRAVITINO")+ .put("data", "opaque payload, not JSON");+ addPropertiesExtension(document, JSON_MAPPER.writeValueAsString(properties));++ SemanticModel imported =+ semanticModelCatalog.importOssieDocument(+ Namespace.of(SCHEMA_NAME), ossieDocument(document, format));+ assertEquals(properties, imported.properties());+ assertEquals(document.path("description").textValue(), imported.comment());+ assertEquals(+ NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME, ORDERS_TABLE),+ imported.definition().datasets()[0].source());+ assertEquals(+ new BigDecimal("0.1234567890123456789"),+ imported.definition().aiContext().object().additionalProperties().get("confidence"));+ assertArrayEquals(+ new CustomExtension[] {+ CustomExtension.builder()+ .withVendorName("GRAVITINO")+ .withData("opaque payload, not JSON")+ .build()+ },+ imported.definition().customExtensions());+ assertEquals(+ "opaque dataset payload", imported.definition().datasets()[0].customExtensions()[0].data());++ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, imported.name());+ OssieDocument exported = semanticModelCatalog.exportOssieDocument(ident, format);+ JsonNode root = parseOssieDocument(exported);+ assertOssieProperties(root, properties);+ assertEquals("opaque payload, not JSON", root.at("/custom_extensions/0/data").textValue());+ assertEquals(+ GRAVITINO_PROPERTIES_VENDOR,+ root.at("/datasets/0/custom_extensions/0/vendor_name").textValue());+ assertTrue(semanticModelCatalog.dropSemanticModel(ident));+ assertSemanticModel(+ imported.name(),+ imported.comment(),+ imported.definition(),+ properties,+ semanticModelCatalog.importOssieDocument(Namespace.of(SCHEMA_NAME), exported));+ }++ /**+ * Verifies that importing an existing name never overwrites the stored model.+ *+ * @param format the import format+ * @throws Exception if a document cannot be serialized+ */+ @ParameterizedTest+ @EnumSource(OssieFormat.class)+ public void testOssieImportIsCreateOnly(OssieFormat format) throws Exception {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, OSSIE_MODEL_NAME);+ SemanticModel original =+ semanticModelCatalog.createSemanticModel(+ ident, "Original model", initialDefinition(), Map.of("owner", "analytics"));+ ObjectNode document = ossieModelDocument();+ document.put("description", "Must not replace the original model");+ addPropertiesExtension(document, "{\"owner\":\"another-team\"}");+ OssieDocument replacement = ossieDocument(document, format);+ assertThrows(+ SemanticModelAlreadyExistsException.class,+ () -> semanticModelCatalog.importOssieDocument(Namespace.of(SCHEMA_NAME), replacement));+ assertSemanticModel(+ original.name(),+ original.comment(),+ original.definition(),+ original.properties(),+ semanticModelCatalog.loadSemanticModel(ident));+ assertArrayEquals(+ new NameIdentifier[] {ident},+ semanticModelCatalog.listSemanticModels(Namespace.of(SCHEMA_NAME)));+ }++ /**+ * Verifies typed missing-model and missing-schema errors through the public interchange API.+ *+ * @param format the document format+ * @throws Exception if a document cannot be serialized+ */+ @ParameterizedTest+ @EnumSource(OssieFormat.class)+ public void testOssieMissingModelAndSchemaErrors(OssieFormat format) throws Exception {+ assertThrows(+ NoSuchSemanticModelException.class,+ () ->+ semanticModelCatalog.exportOssieDocument(+ NameIdentifier.of(SCHEMA_NAME, "missing_model"), format));+ OssieDocument document = ossieDocument(ossieModelDocument(), format);+ assertThrows(+ NoSuchSchemaException.class,+ () -> semanticModelCatalog.importOssieDocument(Namespace.of("missing_schema"), document));+ assertArrayEquals(+ new NameIdentifier[0], semanticModelCatalog.listSemanticModels(Namespace.of(SCHEMA_NAME)));+ }++ /**+ * Verifies malformed and unsupported documents are rejected without persisting any model.+ *+ * @param scenario the invalid document scenario+ * @param document the document to reject+ * @param expectedMessage the expected validation diagnostic+ */+ @ParameterizedTest(name = "{0}")+ @MethodSource("invalidOssieDocuments")+ public void testOssieImportRejectsInvalidDocument(+ String scenario, OssieDocument document, String expectedMessage) {+ IllegalSemanticModelException error =+ assertThrows(+ IllegalSemanticModelException.class,+ () -> semanticModelCatalog.importOssieDocument(Namespace.of(SCHEMA_NAME), document));+ assertTrue(error.getMessage().contains(expectedMessage), scenario + ": " + error.getMessage());+ assertArrayEquals(+ new NameIdentifier[0], semanticModelCatalog.listSemanticModels(Namespace.of(SCHEMA_NAME)));+ }++ /**+ * Verifies native create and replacement cannot inject the reserved root properties extension.+ */+ @Test+ public void testReservedOssiePropertiesExtensionIsRejectedAtomically() {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, OSSIE_MODEL_NAME);+ SemanticModelDefinition reserved =+ SemanticModelDefinition.builder()+ .withDatasets(initialDefinition().datasets())+ .withCustomExtensions(+ new CustomExtension[] {+ CustomExtension.builder()+ .withVendorName(GRAVITINO_PROPERTIES_VENDOR)+ .withData("{\"owner\":\"another-team\"}")+ .build()+ })+ .build();+ assertThrows(+ IllegalSemanticModelException.class,+ () -> semanticModelCatalog.createSemanticModel(ident, null, reserved, Map.of()));+ assertFalse(semanticModelCatalog.semanticModelExists(ident));+ SemanticModel original =+ semanticModelCatalog.createSemanticModel(+ ident, "Original model", initialDefinition(), Map.of("owner", "analytics"));+ assertThrows(+ IllegalSemanticModelException.class,+ () ->+ semanticModelCatalog.alterSemanticModel(+ ident,+ SemanticModelChange.updateComment("Must not persist"),+ SemanticModelChange.setProperty("owner", "another-team"),+ SemanticModelChange.replaceDefinition(reserved)));+ assertSemanticModel(+ original.name(),+ original.comment(),+ original.definition(),+ original.properties(),+ semanticModelCatalog.loadSemanticModel(ident));+ }++ /**+ * Verifies version property validation, ordered changes, and the export fallback after removal.+ *+ * @throws Exception if an exported document cannot be parsed+ */+ @Test+ public void testOssieVersionPropertyLifecycle() throws Exception {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, OSSIE_MODEL_NAME);+ assertThrows(+ IllegalArgumentException.class,+ () ->+ semanticModelCatalog.createSemanticModel(+ ident, null, initialDefinition(), Map.of(PROPERTY_OSSIE_VERSION, " ")));+ assertFalse(semanticModelCatalog.semanticModelExists(ident));+ SemanticModel original =+ semanticModelCatalog.createSemanticModel(+ ident, "Original model", initialDefinition(), Map.of());+ assertEquals(DEFAULT_VERSION, original.properties().get(PROPERTY_OSSIE_VERSION));+ assertThrows(+ IllegalArgumentException.class,+ () ->+ semanticModelCatalog.alterSemanticModel(+ ident,+ SemanticModelChange.updateComment("Must not persist"),+ SemanticModelChange.setProperty(PROPERTY_OSSIE_VERSION, " ")));+ assertSemanticModel(+ original.name(),+ original.comment(),+ original.definition(),+ original.properties(),+ semanticModelCatalog.loadSemanticModel(ident));++ SemanticModel removed =+ semanticModelCatalog.alterSemanticModel(+ ident,+ SemanticModelChange.setProperty(PROPERTY_OSSIE_VERSION, "future-version"),+ SemanticModelChange.removeProperty(PROPERTY_OSSIE_VERSION));+ assertFalse(removed.properties().containsKey(PROPERTY_OSSIE_VERSION));+ assertOssieProperties(+ parseOssieDocument(semanticModelCatalog.exportOssieDocument(ident, OssieFormat.JSON)),+ Map.of());+ SemanticModel updated =+ semanticModelCatalog.alterSemanticModel(+ ident,+ SemanticModelChange.removeProperty(PROPERTY_OSSIE_VERSION),+ SemanticModelChange.setProperty(PROPERTY_OSSIE_VERSION, "future-version"));+ assertEquals("future-version", updated.properties().get(PROPERTY_OSSIE_VERSION));+ assertOssieProperties(+ parseOssieDocument(semanticModelCatalog.exportOssieDocument(ident, OssieFormat.YAML)),+ updated.properties());+ }++ /**+ * Verifies YAML aliases and the documented default format through actual HTTP routing.+ *+ * @param contentType the import media type, or null to omit the header+ * @throws Exception if the HTTP request fails+ */+ @ParameterizedTest+ @NullSource+ @ValueSource(+ strings = {+ "application/yaml",+ "application/x-yaml",+ "text/yaml",+ "application/yaml; charset=UTF-8"+ })+ public void testOssieImportMediaTypes(@Nullable String contentType) throws Exception {+ String yaml = ossieDocument(ossieModelDocument(), OssieFormat.YAML).content();+ HttpResponse<String> response = requestOssie("/ossie", contentType, yaml);+ assertEquals(200, response.statusCode(), response.body());+ assertEquals(+ OSSIE_MODEL_NAME,+ JSON_MAPPER.readTree(response.body()).at("/semanticModel/name").textValue());+ assertTrue(+ semanticModelCatalog.semanticModelExists(NameIdentifier.of(SCHEMA_NAME, OSSIE_MODEL_NAME)));+ }++ /**+ * Verifies unsupported media types are rejected before importing a valid document.+ *+ * @param contentType the unsupported import media type+ * @throws Exception if the HTTP request fails+ */+ @ParameterizedTest+ @ValueSource(strings = {"text/plain", "application/x-www-form-urlencoded"})+ public void testOssieImportRejectsUnsupportedMediaTypes(String contentType) throws Exception {+ HttpResponse<String> response =+ requestOssie(+ "/ossie", contentType, ossieDocument(ossieModelDocument(), OssieFormat.YAML).content());+ assertEquals(415, response.statusCode(), response.body());+ assertArrayEquals(+ new NameIdentifier[0], semanticModelCatalog.listSemanticModels(Namespace.of(SCHEMA_NAME)));+ }++ /**+ * Verifies raw export bodies, default format, and media type and download headers.+ *+ * @param format the format query parameter, or null to omit it+ * @throws Exception if the HTTP request or document parsing fails+ */+ @ParameterizedTest+ @NullSource+ @ValueSource(strings = {"yaml", "json"})+ public void testOssieExportHttpRepresentation(@Nullable String format) throws Exception {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, OSSIE_MODEL_NAME);+ semanticModelCatalog.createSemanticModel(+ ident, "Exported model", initialDefinition(), Map.of());+ String query = format == null ? "" : "?format=" + format;+ HttpResponse<String> response =+ requestOssie("/" + OSSIE_MODEL_NAME + "/ossie" + query, null, null);+ assertEquals(200, response.statusCode(), response.body());+ String expectedFormat = format == null ? "yaml" : format;+ assertEquals(+ "application/" + expectedFormat,+ response.headers().firstValue("Content-Type").orElseThrow().split(";")[0]);+ assertEquals(+ "attachment; filename=\"" + OSSIE_MODEL_NAME + ".ossie." + expectedFormat + "\"",+ response.headers().firstValue("Content-Disposition").orElseThrow());+ JsonNode root =+ "json".equals(format)+ ? JSON_MAPPER.readTree(response.body())+ : YAML_MAPPER.readTree(response.body());+ assertEquals(OSSIE_MODEL_NAME, root.path("name").textValue());+ assertFalse(root.has("semanticModel"));+ assertOssieProperties(root, Map.of());+ HttpResponse<String> invalid =+ requestOssie("/" + OSSIE_MODEL_NAME + "/ossie?format=xml", null, null);+ assertEquals(400, invalid.statusCode(), invalid.body());+ assertTrue(+ JSON_MAPPER+ .readTree(invalid.body())+ .path("message")+ .textValue()+ .contains("Unsupported Ossie format"));+ }++ /** Verifies direct and inherited tags, detail retrieval, reverse lookup, and removal. */+ @Test+ public void testSemanticModelTagLifecycle() {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, MODEL_NAME);+ SemanticModel model =+ semanticModelCatalog.createSemanticModel(+ ident, null, initialDefinition(), Collections.emptyMap());+ Tag catalogTag = createTag("catalog_tag");+ Tag schemaTag = createTag("schema_tag");+ Tag modelTag = createTag("model_tag");+ SupportsTags schemaTags = catalog.asSchemas().loadSchema(SCHEMA_NAME).supportsTags();++ assertArrayEquals(new String[0], model.supportsTags().listTags());+ assertArrayEquals(new Tag[0], model.supportsTags().listTagsInfo());+ catalog.supportsTags().associateTags(new String[] {catalogTag.name()}, null);+ schemaTags.associateTags(new String[] {schemaTag.name()}, null);+ assertArrayEquals(+ new String[] {modelTag.name()},+ model.supportsTags().associateTags(new String[] {modelTag.name()}, null));++ SupportsTags tags = semanticModelCatalog.loadSemanticModel(ident).supportsTags();+ assertEquals(+ Set.of(catalogTag.name(), schemaTag.name(), modelTag.name()), Set.of(tags.listTags()));+ assertEquals(+ Map.of(catalogTag.name(), true, schemaTag.name(), true, modelTag.name(), false),+ Arrays.stream(tags.listTagsInfo())+ .collect(Collectors.toMap(Tag::name, tag -> tag.inherited().orElseThrow())));+ assertEquals(catalogTag, tags.getTag(catalogTag.name()));+ assertEquals(schemaTag, tags.getTag(schemaTag.name()));+ assertEquals(modelTag, tags.getTag(modelTag.name()));+ assertTagAssignment(tags, catalogTag.name(), true);+ assertTagAssignment(tags, schemaTag.name(), true);+ assertTagAssignment(tags, modelTag.name(), false);+ assertMetadataObjects(modelTag.associatedObjects().objects(), semanticModelObject(MODEL_NAME));+ assertMetadataObjects(+ catalogTag.associatedObjects().objects(),+ MetadataObjects.of(null, CATALOG_NAME, MetadataObject.Type.CATALOG));+ assertMetadataObjects(+ schemaTag.associatedObjects().objects(),+ MetadataObjects.of(CATALOG_NAME, SCHEMA_NAME, MetadataObject.Type.SCHEMA));++ // Removing an inherited tag from the child must not detach it from its ancestor.+ tags.associateTags(null, new String[] {catalogTag.name()});+ assertTagAssignment(tags, catalogTag.name(), true);+ assertArrayEquals(new String[0], tags.associateTags(null, new String[] {modelTag.name()}));+ assertThrows(NoSuchTagException.class, () -> tags.getTag(modelTag.name()));+ assertArrayEquals(new MetadataObject[0], modelTag.associatedObjects().objects());+ assertEquals(Set.of(catalogTag.name(), schemaTag.name()), Set.of(tags.listTags()));++ schemaTags.associateTags(null, new String[] {schemaTag.name()});+ catalog.supportsTags().associateTags(null, new String[] {catalogTag.name()});+ assertArrayEquals(new String[0], tags.listTags());+ assertArrayEquals(new Tag[0], tags.listTagsInfo());+ }++ /** Verifies tag-derived policy lookup, inheritance, disabled policies, and tag removal. */+ @Test+ public void testSemanticModelPolicyLifecycle() {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, MODEL_NAME);+ SemanticModel model =+ semanticModelCatalog.createSemanticModel(+ ident, null, initialDefinition(), Collections.emptyMap());+ Tag catalogTag = createTag("catalog_policy_tag");+ Tag schemaTag = createTag("schema_policy_tag");+ Tag modelTag = createTag("model_policy_tag");+ Policy catalogPolicy = createPolicy("catalog_policy");+ Policy schemaPolicy = createPolicy("schema_policy");+ Policy modelPolicy = createPolicy("model_policy");+ metalake.addPolicyForTag(catalogTag.name(), catalogPolicy.name());+ metalake.addPolicyForTag(schemaTag.name(), schemaPolicy.name());+ metalake.addPolicyForTag(modelTag.name(), modelPolicy.name());++ assertArrayEquals(new String[0], model.supportsPolicies().listPolicies());+ assertArrayEquals(new Policy[0], model.supportsPolicies().listPolicyInfos());+ SupportsTags schemaTags = catalog.asSchemas().loadSchema(SCHEMA_NAME).supportsTags();+ catalog.supportsTags().associateTags(new String[] {catalogTag.name()}, null);+ schemaTags.associateTags(new String[] {schemaTag.name()}, null);+ model.supportsTags().associateTags(new String[] {modelTag.name()}, null);++ SupportsPolicies policies = semanticModelCatalog.loadSemanticModel(ident).supportsPolicies();+ assertEquals(+ Set.of(catalogPolicy.name(), schemaPolicy.name(), modelPolicy.name()),+ Set.of(policies.listPolicies()));+ assertEquals(+ Map.of(catalogPolicy.name(), true, schemaPolicy.name(), true, modelPolicy.name(), false),+ Arrays.stream(policies.listPolicyInfos())+ .collect(Collectors.toMap(Policy::name, policy -> policy.inherited().orElseThrow())));++ metalake.disablePolicy(modelPolicy.name());+ assertEquals(+ Set.of(catalogPolicy.name(), schemaPolicy.name()), Set.of(policies.listPolicies()));+ assertEquals(+ Set.of(catalogPolicy.name(), schemaPolicy.name()),+ Arrays.stream(policies.listPolicyInfos()).map(Policy::name).collect(Collectors.toSet()));+ metalake.enablePolicy(modelPolicy.name());+ assertEquals(+ Set.of(catalogPolicy.name(), schemaPolicy.name(), modelPolicy.name()),+ Set.of(policies.listPolicies()));++ model.supportsTags().associateTags(null, new String[] {modelTag.name()});+ assertEquals(+ Set.of(catalogPolicy.name(), schemaPolicy.name()), Set.of(policies.listPolicies()));+ schemaTags.associateTags(null, new String[] {schemaTag.name()});+ catalog.supportsTags().associateTags(null, new String[] {catalogTag.name()});+ assertArrayEquals(new String[0], policies.listPolicies());+ assertArrayEquals(new Policy[0], policies.listPolicyInfos());+ }++ /** Verifies tag values, ancestor precedence, direct overrides, and value-filtered lookup. */+ @Test+ public void testSemanticModelTagValues() {+ SemanticModel model =+ semanticModelCatalog.createSemanticModel(+ NameIdentifier.of(SCHEMA_NAME, MODEL_NAME),+ null,+ initialDefinition(),+ Collections.emptyMap());+ Tag tag =+ metalake.createTag(+ "data_domain",+ null,+ Collections.emptyMap(),+ TagValueConstraint.ofAllowedValues("finance", "risk"));+ TagValue[] finance = {TagValue.of(tag.name(), "finance")};+ TagValue[] risk = {TagValue.of(tag.name(), "risk")};+ SupportsTags tags = model.supportsTags();+ SupportsTags schemaTags = catalog.asSchemas().loadSchema(SCHEMA_NAME).supportsTags();++ catalog.supportsTags().associateTags(finance, null);+ assertTagAssignment(tags, tag.name(), true, "finance");+ schemaTags.associateTags(risk, null);+ assertTagAssignment(tags, tag.name(), true, "risk");+ assertArrayEquals(new String[] {tag.name()}, tags.associateTags(finance, null));+ assertTagAssignment(tags, tag.name(), false, "finance");+ assertEquals(tag.valueConstraint(), tags.getTag(tag.name()).valueConstraint());+ tags.associateTags(risk, null);+ tags.associateTags(risk, null);+ assertTagAssignment(tags, tag.name(), false, "finance", "risk");+ assertMetadataObjects(+ tag.associatedObjects().objects("finance"),+ MetadataObjects.of(null, CATALOG_NAME, MetadataObject.Type.CATALOG),+ semanticModelObject(MODEL_NAME));+ assertArrayEquals(new MetadataObject[0], tag.associatedObjects().objects("unknown"));++ tags.associateTags(null, finance);+ assertTagAssignment(tags, tag.name(), false, "risk");+ assertArrayEquals(new String[0], tags.associateTags(null, risk));+ assertTagAssignment(tags, tag.name(), true, "risk");+ assertMetadataObjects(+ tag.associatedObjects().objects("risk"),+ MetadataObjects.of(CATALOG_NAME, SCHEMA_NAME, MetadataObject.Type.SCHEMA));+ schemaTags.associateTags(null, risk);+ assertTagAssignment(tags, tag.name(), true, "finance");+ catalog.supportsTags().associateTags(null, finance);+ assertArrayEquals(new String[0], tags.listTags());+ assertArrayEquals(new MetadataObject[0], tag.associatedObjects().objects());+ }++ /**+ * Verifies that tags follow a rename but cannot leak into a recreated model with the same name.+ */+ @Test+ public void testSemanticModelTagsAcrossRenameAndDrop() {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, MODEL_NAME);+ SemanticModel model =+ semanticModelCatalog.createSemanticModel(+ ident, null, initialDefinition(), Collections.emptyMap());+ Tag tag = createTag("renamed_model_tag");+ model.supportsTags().associateTags(new String[] {tag.name()}, null);++ SemanticModel renamed =+ semanticModelCatalog.alterSemanticModel(+ ident, SemanticModelChange.rename(RENAMED_MODEL_NAME));+ assertArrayEquals(new String[] {tag.name()}, renamed.supportsTags().listTags());+ assertTagAssignment(renamed.supportsTags(), tag.name(), false);+ assertMetadataObjects(+ tag.associatedObjects().objects(), semanticModelObject(RENAMED_MODEL_NAME));+ NotFoundException missing =+ assertThrows(NotFoundException.class, () -> model.supportsTags().listTags());+ assertTrue(missing.getMessage().contains(semanticModelObject(MODEL_NAME).fullName()));++ NameIdentifier renamedIdent = NameIdentifier.of(SCHEMA_NAME, RENAMED_MODEL_NAME);+ assertTrue(semanticModelCatalog.dropSemanticModel(renamedIdent));+ SupportsTags droppedTags = renamed.supportsTags();+ assertThrows(NotFoundException.class, droppedTags::listTags);+ assertThrows(NotFoundException.class, droppedTags::listTagsInfo);+ assertThrows(NotFoundException.class, () -> droppedTags.getTag(tag.name()));+ assertThrows(+ NotFoundException.class, () -> droppedTags.associateTags(new String[] {tag.name()}, null));+ assertThrows(+ NotFoundException.class,+ () -> droppedTags.associateTags(new TagValue[] {TagValue.of(tag.name(), "value")}, null));+ assertArrayEquals(new MetadataObject[0], tag.associatedObjects().objects());++ SemanticModel recreated =+ semanticModelCatalog.createSemanticModel(+ renamedIdent, null, initialDefinition(), Collections.emptyMap());+ assertArrayEquals(new String[0], recreated.supportsTags().listTags());+ assertArrayEquals(new MetadataObject[0], tag.associatedObjects().objects());+ }++ /**+ * Verifies that imported models expose tag operations with the correct model identity.+ *+ * @param format the Ossie import format+ */+ @ParameterizedTest+ @EnumSource(OssieFormat.class)+ public void testImportedSemanticModelSupportsTags(OssieFormat format) {+ SemanticModel imported =+ semanticModelCatalog.importOssieDocument(+ Namespace.of(SCHEMA_NAME), ossieSourceDocument(ORDERS_TABLE, null, format));+ Tag tag = createTag("imported_model_tag");+ assertArrayEquals(+ new String[] {tag.name()},+ imported.supportsTags().associateTags(new String[] {tag.name()}, null));+ assertTagAssignment(imported.supportsTags(), tag.name(), false);+ assertMetadataObjects(tag.associatedObjects().objects(), semanticModelObject(imported.name()));+ assertArrayEquals(+ new String[] {tag.name()},+ semanticModelCatalog+ .loadSemanticModel(NameIdentifier.of(SCHEMA_NAME, imported.name()))+ .supportsTags()+ .listTags());+ }++ private static ObjectNode ossieModelDocument() {+ ObjectNode root = JSON_MAPPER.createObjectNode();+ root.put("version", DEFAULT_VERSION);+ root.put("name", OSSIE_MODEL_NAME);+ root.putArray("datasets")+ .addObject()+ .put("name", "orders")+ .put("source", CATALOG_NAME + "." + SCHEMA_NAME + "." + ORDERS_TABLE);+ return root;+ }++ private static OssieDocument ossieDocument(JsonNode root, OssieFormat format)+ throws JsonProcessingException {+ return format == OssieFormat.JSON+ ? OssieDocument.json(JSON_MAPPER.writeValueAsString(root))+ : OssieDocument.yaml(YAML_MAPPER.writeValueAsString(root));+ }++ private static JsonNode parseOssieDocument(OssieDocument document)+ throws JsonProcessingException {+ return (document.format() == OssieFormat.JSON ? JSON_MAPPER : YAML_MAPPER)+ .readTree(document.content());+ }++ private static void addPropertiesExtension(ObjectNode root, String data) {+ root.withArray("custom_extensions")+ .addObject()+ .put("vendor_name", GRAVITINO_PROPERTIES_VENDOR)+ .put("data", data);+ }++ private static void assertOssieProperties(JsonNode root, Map<String, String> properties)+ throws JsonProcessingException {+ assertEquals(+ properties.getOrDefault(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION),+ root.path("version").textValue());+ Map<String, String> expected = new LinkedHashMap<>(properties);+ expected.remove(PROPERTY_OSSIE_VERSION);+ int count = 0;+ for (JsonNode extension : root.path("custom_extensions")) {+ if (GRAVITINO_PROPERTIES_VENDOR.equals(extension.path("vendor_name").textValue())) {+ count++;+ assertTrue(extension.path("data").isTextual());+ JsonNode actual = JSON_MAPPER.readTree(extension.path("data").textValue());+ assertEquals(JSON_MAPPER.valueToTree(expected), actual);+ assertFalse(actual.has(PROPERTY_OSSIE_VERSION));+ }+ }+ assertEquals(expected.isEmpty() ? 0 : 1, count);+ }++ private HttpResponse<String> requestOssie(+ String suffix, @Nullable String contentType, @Nullable String body) throws Exception {+ HttpRequest.Builder request =+ HttpRequest.newBuilder()+ .uri(+ URI.create(+ String.format(+ "%s/api/metalakes/%s/catalogs/%s/schemas/%s/semantic-models%s",+ serverUri, METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, suffix)))+ .timeout(Duration.ofSeconds(30));+ if (contentType != null) {+ request.header("Content-Type", contentType);+ }+ if (body == null) {+ request.GET();+ } else {+ request.POST(HttpRequest.BodyPublishers.ofString(body));+ }+ return httpClient.send(request.build(), HttpResponse.BodyHandlers.ofString());+ }++ private static Stream<Arguments> invalidOssieDocuments() throws JsonProcessingException {+ Stream.Builder<Arguments> cases = Stream.builder();+ for (OssieFormat format : OssieFormat.values()) {+ ObjectNode missingVersion = ossieModelDocument();+ missingVersion.remove("version");+ cases.add(+ Arguments.of(+ "missing version " + format, ossieDocument(missingVersion, format), "$.version"));+ ObjectNode wrongType = ossieModelDocument();+ wrongType.putObject("datasets");+ cases.add(+ Arguments.of(+ "wrong dataset type " + format, ossieDocument(wrongType, format), "$.datasets"));+ ObjectNode unknown = ossieModelDocument().put("unsupported", true);+ cases.add(+ Arguments.of("unknown field " + format, ossieDocument(unknown, format), "$.unsupported"));+ ObjectNode nullDescription = ossieModelDocument().putNull("description");+ cases.add(+ Arguments.of(+ "null description " + format,+ ossieDocument(nullDescription, format),+ "$.description"));+ ObjectNode conflict = ossieModelDocument();+ addPropertiesExtension(conflict, "{\"ossie-version\":\"different-version\"}");+ cases.add(+ Arguments.of(+ "conflicting version " + format,+ ossieDocument(conflict, format),+ "conflicts with $.version"));+ ObjectNode invalidProperties = ossieModelDocument();+ addPropertiesExtension(invalidProperties, "{\"owner\":1}");+ cases.add(+ Arguments.of(+ "non-string property " + format,+ ossieDocument(invalidProperties, format),+ "property 'owner' must be a string"));+ ObjectNode duplicateProperties = ossieModelDocument();+ addPropertiesExtension(duplicateProperties, "{}");+ addPropertiesExtension(duplicateProperties, "{}");+ cases.add(+ Arguments.of(+ "duplicate properties extension " + format,+ ossieDocument(duplicateProperties, format),+ "multiple GRAVITINO_PROPERTIES extensions"));+ ObjectNode duplicateProperty = ossieModelDocument();+ addPropertiesExtension(duplicateProperty, "{\"owner\":\"first\",\"owner\":\"second\"}");+ cases.add(+ Arguments.of(+ "duplicate property key " + format,+ ossieDocument(duplicateProperty, format),+ "Duplicate field 'owner'"));++ String content = ossieDocument(ossieModelDocument(), format).content();+ OssieDocument duplicate =+ format == OssieFormat.JSON+ ? OssieDocument.json("{\"name\":\"duplicate\"," + content.substring(1))+ : OssieDocument.yaml(content + "\nname: duplicate\n");+ cases.add(+ Arguments.of("duplicate root field " + format, duplicate, "Duplicate field 'name'"));+ OssieDocument trailing =+ format == OssieFormat.JSON+ ? OssieDocument.json(content + " {}")+ : OssieDocument.yaml(content + "\n---\n{}\n");+ cases.add(Arguments.of("trailing document " + format, trailing, "Trailing token"));+ }+ cases.add(+ Arguments.of(+ "YAML declared as JSON",+ OssieDocument.json(ossieDocument(ossieModelDocument(), OssieFormat.YAML).content()),+ "Cannot parse Apache Ossie JSON"));+ return cases.build();+ }++ private Tag createTag(String prefix) {+ return metalake.createTag(+ GravitinoITUtils.genRandomName(prefix), "Semantic Model tag", Collections.emptyMap());+ }++ private Policy createPolicy(String prefix) {+ return metalake.createPolicy(+ GravitinoITUtils.genRandomName(prefix),+ "custom",+ "Semantic Model policy",+ true,+ PolicyContents.custom(+ Collections.emptyMap(),+ Set.of(MetadataObject.Type.SEMANTIC_MODEL),+ Collections.emptyMap()));+ }++ private static MetadataObject semanticModelObject(String name) {+ return MetadataObjects.of(+ CATALOG_NAME + "." + SCHEMA_NAME, name, MetadataObject.Type.SEMANTIC_MODEL);+ }++ private static void assertTagAssignment(+ SupportsTags tags, String name, boolean inherited, String... values) {+ Tag tag = tags.getTag(name);+ assertEquals(inherited, tag.inherited().orElseThrow());+ assertEquals(Set.of(values), Set.of(tag.assignment().orElseThrow().values()));+ }++ private static void assertMetadataObjects(MetadataObject[] actual, MetadataObject... expected) {+ assertEquals(expected.length, actual.length);+ assertEquals(+ Set.of(expected),+ Arrays.stream(actual)+ .map(object -> MetadataObjects.parse(object.fullName(), object.type()))+ .collect(Collectors.toSet()));+ }++ private static Stream<Arguments> invalidSourceDefinitions() {+ Dataset missingSource =+ Dataset.builder()+ .withName("orders")+ .withSource(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME, "missing_table"))+ .build();+ Dataset missingColumn =+ Dataset.builder()+ .withName("orders")+ .withSource(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME, ORDERS_TABLE))+ .withPrimaryKey(new String[] {"missing_column"})+ .build();+ return Stream.of(+ Arguments.of(+ "missing source",+ SemanticModelDefinition.builder().withDatasets(new Dataset[] {missingSource}).build(),+ "missing_table does not exist"),+ Arguments.of(+ "missing column",+ SemanticModelDefinition.builder().withDatasets(new Dataset[] {missingColumn}).build(),+ "Dataset orders source has no column missing_column"));+ }++ private static Stream<Arguments> invalidOssieSourceDocuments() {+ return Stream.of(OssieFormat.values())+ .flatMap(+ format ->+ Stream.of(+ Arguments.of(+ "missing source " + format,+ ossieSourceDocument("missing_table", null, format),+ "missing_table does not exist"),+ Arguments.of(+ "missing column " + format,+ ossieSourceDocument(ORDERS_TABLE, "missing_column", format),+ "Dataset orders source has no column missing_column")));+ }++ private static OssieDocument ossieSourceDocument(+ String table, @Nullable String primaryKey, OssieFormat format) {+ String source = CATALOG_NAME + "." + SCHEMA_NAME + "." + table;+ if (format == OssieFormat.JSON) {+ return OssieDocument.json(+ String.format(+ "{\"version\":\"%s\",\"name\":\"%s\","+ + "\"datasets\":[{\"name\":\"orders\",\"source\":\"%s\"%s}]}",+ DEFAULT_VERSION,+ INVALID_MODEL_NAME,+ source,+ primaryKey == null ? "" : ",\"primary_key\":[\"" + primaryKey + "\"]"));+ }+ return OssieDocument.yaml(+ String.format(+ "version: %s%nname: %s%ndatasets:%n - name: orders%n source: %s%n%s",+ DEFAULT_VERSION,+ INVALID_MODEL_NAME,+ source,+ primaryKey == null ? "" : " primary_key: [" + primaryKey + "]\n"));+ }++ private static SemanticModelDefinition initialDefinition() {+ Map<String, Object> additionalProperties = new LinkedHashMap<>();+ additionalProperties.put("confidence", new BigDecimal("0.95"));+ additionalProperties.put("hints", List.of("month", "region"));+ AIContextObject modelContext =+ AIContextObject.builder()+ .withInstructions("Use certified metrics")+ .withSynonyms(new String[] {"sales", "revenue"})+ .withExamples(new String[] {"Revenue by month"})+ .withAdditionalProperties(additionalProperties)+ .build();+ CustomExtension extension =+ CustomExtension.builder().withVendorName("example").withData("{\"tier\":\"gold\"}").build();+ Field orderTime =+ Field.builder()+ .withName("order_time")+ .withExpression(expression(Dialects.ANSI_SQL, "order_time"))+ .withDimension(Dimension.builder().withIsTime(true).build())+ .withLabel("Order time")+ .withDescription("Time the order was placed")+ .withDatatype(DataType.DATE_TIME_TZ)+ .withAIContext(AIContext.of("Use the business timezone"))+ .withCustomExtensions(new CustomExtension[0])+ .build();+ Field orderAmount =+ Field.builder()+ .withName("order_amount")+ .withExpression(expression("TRINO", "order_amount"))+ .withDatatype(DataType.DECIMAL)+ .withCustomExtensions(new CustomExtension[] {extension})+ .build();+ Dataset orders =+ Dataset.builder()+ .withName("orders")+ .withSource(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME, ORDERS_TABLE))+ .withPrimaryKey(new String[] {"order_id"})+ .withUniqueKeys(new String[0][])+ .withDescription("Governed order facts")+ .withAIContext(AIContext.of("Use completed orders"))+ .withFields(new Field[] {orderTime, orderAmount})+ .withCustomExtensions(new CustomExtension[0])+ .build();+ Dataset customers =+ Dataset.builder()+ .withName("customers")+ .withSource(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME, CUSTOMERS_TABLE))+ .withUniqueKeys(new String[][] {{"email"}})+ .withFields(new Field[0])+ .build();+ Relationship relationship =+ Relationship.builder()+ .withName("orders_to_customers")+ .withFrom("orders")+ .withTo("customers")+ .withFromColumns(new String[] {"customer_id"})+ .withToColumns(new String[] {"id"})+ .withAIContext(AIContext.of("Join orders to customer attributes"))+ .withCustomExtensions(new CustomExtension[] {extension})+ .build();+ Metric revenue =+ Metric.builder()+ .withName("revenue")+ .withExpression(expression(Dialects.ANSI_SQL, "SUM(orders.order_amount)"))+ .withDescription("Certified revenue")+ .withDatatype(DataType.DECIMAL)+ .withAIContext(AIContext.of(modelContext))+ .withCustomExtensions(new CustomExtension[] {extension})+ .build();+ return SemanticModelDefinition.builder()+ .withAIContext(AIContext.of(modelContext))+ .withDatasets(new Dataset[] {orders, customers})+ .withRelationships(new Relationship[] {relationship})+ .withMetrics(new Metric[] {revenue})+ .withCustomExtensions(new CustomExtension[] {extension})+ .build();+ }++ private static SemanticModelDefinition replacementDefinition() {+ Dataset orders =+ Dataset.builder()+ .withName("orders")+ .withSource(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME, ORDERS_TABLE))+ .withPrimaryKey(new String[] {"order_id"})+ .build();+ Dataset customers =+ Dataset.builder()+ .withName("customers")+ .withSource(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME, CUSTOMERS_TABLE))+ .withFields(new Field[0])+ .build();+ return SemanticModelDefinition.builder()+ .withAIContext(AIContext.of("Use the replacement definition"))+ .withDatasets(new Dataset[] {orders, customers})+ .withRelationships(new Relationship[0])+ .withMetrics(new Metric[0])+ .withCustomExtensions(new CustomExtension[0])+ .build();+ }++ private static Expression expression(String dialect, String value) {+ return Expression.builder()+ .withDialects(+ new DialectExpression[] {+ DialectExpression.builder().withDialect(dialect).withExpression(value).build()+ })+ .build();+ }++ private static void assertSemanticModel(+ String name,+ String comment,+ SemanticModelDefinition definition,+ Map<String, String> properties,+ SemanticModel actual) {+ assertEquals(name, actual.name());+ assertEquals(comment, actual.comment());+ assertEquals(definition, actual.definition());+ assertEquals(properties, actual.properties());+ }+}diff --git a/docs/open-api/policies.yaml b/docs/open-api/policies.yamlindex c8089274f0..6440c2a290 100644--- a/docs/open-api/policies.yaml+++ b/docs/open-api/policies.yaml@@ -594,7 +594,7 @@ components:minItems: 1items:type: string- enum: [ "CATALOG", "SCHEMA", "TABLE", "FILESET", "TOPIC", "MODEL", "VIEW", "FUNCTION" ]+ enum: [ "CATALOG", "SCHEMA", "TABLE", "FILESET", "TOPIC", "MODEL", "SEMANTIC_MODEL", "VIEW", "FUNCTION" ]properties:type: objectdescription: A map of string-to-string properties for the policy content.diff --git a/docs/policies.md b/docs/policies.mdindex f39c8b2578..71f5b67654 100644--- a/docs/policies.md+++ b/docs/policies.md@@ -77,8 +77,9 @@ the new selector. Removing an association leaves the policy, tag, and tag assignDeleting a policy removes its associations.Object policy lookup covers `CATALOG`, `SCHEMA`, `TABLE`, `VIEW`, `COLUMN`, `FILESET`, `TOPIC`,-`MODEL`, `MODEL_VERSION`, and `FUNCTION`. A model version cannot carry a tag directly, but it can-inherit tags from its model and higher ancestors, so their policies appear in model version lookups.+`MODEL`, `MODEL_VERSION`, `SEMANTIC_MODEL`, and `FUNCTION`. A model version cannot carry a tag directly,+but it can inherit tags from its model and higher ancestors, so their policies appear in model+version lookups.This also includes columns, which did not support direct policy associations.A tag assigned to a catalog or schema can therefore make its policies appear in descendant columnlookups. Because lookup does not filter by `supportedObjectTypes`, a policy whose content lists