Skip to content

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

[#13540] feat(semantic-model): Add Ossie import and export (#13571)

mchades2ebf08fa2ac7
diff --git a/api/src/main/java/org/apache/gravitino/semantic/AIContextObject.java b/api/src/main/java/org/apache/gravitino/semantic/AIContextObject.java
index 6e9c156786..c804d509e5 100644
--- a/api/src/main/java/org/apache/gravitino/semantic/AIContextObject.java
+++ b/api/src/main/java/org/apache/gravitino/semantic/AIContextObject.java
@@ -37,8 +37,6 @@ import org.apache.gravitino.annotation.Evolving;
@Evolving
public final class AIContextObject {
- static final int MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH = 100;
-
@Nullable private final String instructions;
@Nullable private final String[] synonyms;
@Nullable private final String[] examples;
@@ -206,9 +204,8 @@ public final class AIContextObject {
* <p>Values may be null, strings, booleans, JSON-compatible numbers, maps with string keys,
* lists, or Java arrays. Integral numbers are normalized to {@link BigInteger}, and decimal
* numbers are normalized to {@link BigDecimal} so their value semantics remain stable across
- * JSON round trips. Nested maps, lists, and arrays may be at most {@value
- * #MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH} levels deep. Property names must not duplicate {@code
- * instructions}, {@code synonyms}, or {@code examples}.
+ * JSON round trips. Property names must not duplicate {@code instructions}, {@code synonyms},
+ * or {@code examples}.
*
* @param additionalProperties The additional properties.
* @return This builder.
@@ -224,7 +221,7 @@ public final class AIContextObject {
* @return The immutable structured AI context.
* @throws IllegalArgumentException If a string array contains null, the additional properties
* are null, a property duplicates a standard field, or a property value is not
- * JSON-compatible or exceeds the supported nesting depth.
+ * JSON-compatible or contains a cyclic reference.
*/
public AIContextObject build() {
SemanticModelDefinition.validateNoNullElements("synonyms", synonyms);
@@ -245,16 +242,13 @@ public final class AIContextObject {
!isStandardProperty(name),
"additional property must not duplicate standard property: %s",
name);
- result.put(name, immutableJsonValue(entry.getValue(), name, visiting, 0));
+ result.put(name, immutableJsonValue(entry.getValue(), name, visiting));
}
return Collections.unmodifiableMap(result);
}
private static Object immutableJsonValue(
- @Nullable Object value,
- String path,
- IdentityHashMap<Object, Boolean> visiting,
- int containerDepth) {
+ @Nullable Object value, String path, IdentityHashMap<Object, Boolean> visiting) {
if (value == null || value instanceof String || value instanceof Boolean) {
return value;
}
@@ -262,13 +256,13 @@ public final class AIContextObject {
return canonicalizeJsonNumber((Number) value, path);
}
if (value instanceof Map) {
- return immutableJsonMap((Map<?, ?>) value, path, visiting, containerDepth + 1);
+ return immutableJsonMap((Map<?, ?>) value, path, visiting);
}
if (value instanceof List) {
- return immutableJsonList((List<?>) value, path, visiting, containerDepth + 1);
+ return immutableJsonList((List<?>) value, path, visiting);
}
if (value.getClass().isArray()) {
- return immutableJsonArray(value, path, visiting, containerDepth + 1);
+ return immutableJsonArray(value, path, visiting);
}
throw new IllegalArgumentException(
String.format(
@@ -277,8 +271,8 @@ public final class AIContextObject {
}
private static Map<String, Object> immutableJsonMap(
- Map<?, ?> value, String path, IdentityHashMap<Object, Boolean> visiting, int containerDepth) {
- enterContainer(value, path, visiting, containerDepth);
+ Map<?, ?> value, String path, IdentityHashMap<Object, Boolean> visiting) {
+ enterContainer(value, path, visiting);
try {
Map<String, Object> result = new LinkedHashMap<>();
for (Map.Entry<?, ?> entry : value.entrySet()) {
@@ -287,8 +281,7 @@ public final class AIContextObject {
"Additional property %s contains a map key that is not a string",
path);
String key = (String) entry.getKey();
- result.put(
- key, immutableJsonValue(entry.getValue(), path + "." + key, visiting, containerDepth));
+ result.put(key, immutableJsonValue(entry.getValue(), path + "." + key, visiting));
}
return Collections.unmodifiableMap(result);
} finally {
@@ -297,14 +290,12 @@ public final class AIContextObject {
}
private static List<Object> immutableJsonList(
- List<?> value, String path, IdentityHashMap<Object, Boolean> visiting, int containerDepth) {
- enterContainer(value, path, visiting, containerDepth);
+ List<?> value, String path, IdentityHashMap<Object, Boolean> visiting) {
+ enterContainer(value, path, visiting);
try {
List<Object> result = new ArrayList<>(value.size());
for (int index = 0; index < value.size(); index++) {
- result.add(
- immutableJsonValue(
- value.get(index), path + "[" + index + "]", visiting, containerDepth));
+ result.add(immutableJsonValue(value.get(index), path + "[" + index + "]", visiting));
}
return Collections.unmodifiableList(result);
} finally {
@@ -313,15 +304,13 @@ public final class AIContextObject {
}
private static List<Object> immutableJsonArray(
- Object value, String path, IdentityHashMap<Object, Boolean> visiting, int containerDepth) {
- enterContainer(value, path, visiting, containerDepth);
+ Object value, String path, IdentityHashMap<Object, Boolean> visiting) {
+ enterContainer(value, path, visiting);
try {
int length = Array.getLength(value);
List<Object> result = new ArrayList<>(length);
for (int index = 0; index < length; index++) {
- result.add(
- immutableJsonValue(
- Array.get(value, index), path + "[" + index + "]", visiting, containerDepth));
+ result.add(immutableJsonValue(Array.get(value, index), path + "[" + index + "]", visiting));
}
return Collections.unmodifiableList(result);
} finally {
@@ -370,12 +359,7 @@ public final class AIContextObject {
}
private static void enterContainer(
- Object value, String path, IdentityHashMap<Object, Boolean> visiting, int containerDepth) {
- Preconditions.checkArgument(
- containerDepth <= MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH,
- "Additional property %s exceeds maximum nesting depth of %s",
- path,
- MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH);
+ Object value, String path, IdentityHashMap<Object, Boolean> visiting) {
Preconditions.checkArgument(
!visiting.containsKey(value), "Additional property %s contains a cyclic value", path);
visiting.put(value, Boolean.TRUE);
diff --git a/api/src/main/java/org/apache/gravitino/semantic/CustomExtension.java b/api/src/main/java/org/apache/gravitino/semantic/CustomExtension.java
index 1b0b8a8e6c..828f62923b 100644
--- a/api/src/main/java/org/apache/gravitino/semantic/CustomExtension.java
+++ b/api/src/main/java/org/apache/gravitino/semantic/CustomExtension.java
@@ -27,6 +27,12 @@ import org.apache.gravitino.annotation.Evolving;
@Evolving
public final class CustomExtension {
+ /**
+ * The root-level extension vendor reserved for carrying Gravitino properties in Ossie documents.
+ * Native Semantic Model definitions must not use this vendor in their root custom extensions.
+ */
+ public static final String GRAVITINO_PROPERTIES_VENDOR = "GRAVITINO_PROPERTIES";
+
private final String vendorName;
private final String data;
diff --git a/api/src/main/java/org/apache/gravitino/semantic/OssieDocument.java b/api/src/main/java/org/apache/gravitino/semantic/OssieDocument.java
new file mode 100644
index 0000000000..195356bed2
--- /dev/null
+++ b/api/src/main/java/org/apache/gravitino/semantic/OssieDocument.java
@@ -0,0 +1,96 @@
+/*
+ * 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.semantic;
+
+import com.google.common.base.Preconditions;
+import java.util.Objects;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.annotation.Evolving;
+
+/**
+ * An immutable standalone Apache Ossie document containing serialized content and its format.
+ *
+ * <p>The content is the document text, not a file path or URL, and must not be blank. Constructing
+ * this value does not parse the content; document syntax and structure are validated when imported.
+ */
+@Evolving
+public final class OssieDocument {
+
+ private final String content;
+ private final OssieFormat format;
+
+ private OssieDocument(String content, OssieFormat format) {
+ Preconditions.checkArgument(StringUtils.isNotBlank(content), "content must not be blank");
+ this.content = content;
+ this.format = format;
+ }
+
+ /**
+ * Creates a document whose content is serialized as YAML.
+ *
+ * @param content The document text.
+ * @return The YAML document.
+ * @throws IllegalArgumentException If the content is null, empty, or whitespace-only.
+ */
+ public static OssieDocument yaml(String content) {
+ return new OssieDocument(content, OssieFormat.YAML);
+ }
+
+ /**
+ * Creates a document whose content is serialized as JSON.
+ *
+ * @param content The document text.
+ * @return The JSON document.
+ * @throws IllegalArgumentException If the content is null, empty, or whitespace-only.
+ */
+ public static OssieDocument json(String content) {
+ return new OssieDocument(content, OssieFormat.JSON);
+ }
+
+ /**
+ * Returns the serialized document content.
+ *
+ * @return The document text.
+ */
+ public String content() {
+ return content;
+ }
+
+ /**
+ * Returns the document's serialization format.
+ *
+ * @return The serialization format.
+ */
+ public OssieFormat format() {
+ return format;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ OssieDocument that = (OssieDocument) o;
+ return content.equals(that.content) && format == that.format;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(content, format);
+ }
+}
diff --git a/api/src/main/java/org/apache/gravitino/semantic/OssieFormat.java b/api/src/main/java/org/apache/gravitino/semantic/OssieFormat.java
new file mode 100644
index 0000000000..2b8a1c8c5d
--- /dev/null
+++ b/api/src/main/java/org/apache/gravitino/semantic/OssieFormat.java
@@ -0,0 +1,30 @@
+/*
+ * 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.semantic;
+
+import org.apache.gravitino.annotation.Evolving;
+
+/** The serialization format of a standalone Apache Ossie document. */
+@Evolving
+public enum OssieFormat {
+ /** YAML serialization. */
+ YAML,
+ /** JSON serialization. */
+ JSON
+}
diff --git a/api/src/main/java/org/apache/gravitino/semantic/OssieVersion.java b/api/src/main/java/org/apache/gravitino/semantic/OssieVersion.java
new file mode 100644
index 0000000000..80fc5a4245
--- /dev/null
+++ b/api/src/main/java/org/apache/gravitino/semantic/OssieVersion.java
@@ -0,0 +1,31 @@
+/*
+ * 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.semantic;
+
+import org.apache.gravitino.annotation.Evolving;
+
+/** Constants for Apache Ossie document versions. */
+@Evolving
+public final class OssieVersion {
+
+ /** The default Apache Ossie document version. */
+ public static final String DEFAULT_VERSION = "0.2.0.dev0";
+
+ private OssieVersion() {}
+}
diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java
index f0650155be..2771246b72 100644
--- a/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java
+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java
@@ -32,6 +32,18 @@ import org.apache.gravitino.annotation.Evolving;
@Evolving
public interface SemanticModel extends Auditable {
+ /**
+ * The property key for the Apache Ossie document version.
+ *
+ * <p>For native Semantic Model creation, Gravitino persists {@link OssieVersion#DEFAULT_VERSION}
+ * when this property is omitted and preserves explicitly supplied non-blank values. The persisted
+ * value is retained if the server default changes later.
+ *
+ * <p>This property can be updated or removed. If it is absent, Ossie exports use the current
+ * default version.
+ */
+ String PROPERTY_OSSIE_VERSION = "ossie-version";
+
/**
* Returns the Semantic Model name.
*
diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java
index eb1a7b19db..9a31583fb8 100644
--- a/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java
+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java
@@ -85,6 +85,55 @@ public interface SemanticModelCatalog {
throws NoSuchSchemaException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException;
+ /**
+ * Imports a standalone Apache Ossie document as a new Semantic Model in a schema.
+ *
+ * <p>The model name comes from the document. Import uses the same validation as {@link
+ * #createSemanticModel}; it does not replace an existing model. The document is parsed according
+ * to its declared format, without falling back to another format.
+ *
+ * <p>REST clients send {@link OssieDocument#content()} as the raw request body, without
+ * JSON-encoding the document string again. The {@code Content-Type} header selects the parser:
+ * {@code application/json} for JSON, or {@code application/yaml}, {@code application/x-yaml}, or
+ * {@code text/yaml} for YAML. If the header is absent, the REST endpoint defaults to YAML.
+ *
+ * <p>A root {@link CustomExtension#GRAVITINO_PROPERTIES_VENDOR} extension is consumed as model
+ * properties before creation. Its data must encode a JSON object with string values, and at most
+ * one such extension is allowed. Other custom extensions are preserved.
+ *
+ * @param namespace The destination schema namespace.
+ * @param document The standalone Ossie document and its serialization format.
+ * @return The created Semantic Model.
+ * @throws NoSuchSchemaException If the schema does not exist.
+ * @throws SemanticModelAlreadyExistsException If a model with the document's name already exists.
+ * @throws IllegalSemanticModelException If the document or Semantic Model definition is invalid.
+ * @throws UnsupportedOperationException If Ossie import is not supported.
+ */
+ default SemanticModel importOssieDocument(Namespace namespace, OssieDocument document)
+ throws NoSuchSchemaException, SemanticModelAlreadyExistsException,
+ IllegalSemanticModelException {
+ throw new UnsupportedOperationException("Ossie import is not supported");
+ }
+
+ /**
+ * Exports a Semantic Model as a standalone Apache Ossie document.
+ *
+ * <p>The {@link SemanticModel#PROPERTY_OSSIE_VERSION} property supplies the document version.
+ * Other properties, if present, are serialized as a JSON object in the data of a root {@link
+ * CustomExtension#GRAVITINO_PROPERTIES_VENDOR} extension.
+ *
+ * @param ident The Semantic Model identifier.
+ * @param format The requested serialization format.
+ * @return The serialized Ossie document and its format.
+ * @throws NoSuchSemanticModelException If the Semantic Model does not exist.
+ * @throws IllegalSemanticModelException If the model cannot be represented as an Ossie document.
+ * @throws UnsupportedOperationException If Ossie export is not supported.
+ */
+ default OssieDocument exportOssieDocument(NameIdentifier ident, OssieFormat format)
+ throws NoSuchSemanticModelException, IllegalSemanticModelException {
+ throw new UnsupportedOperationException("Ossie export is not supported");
+ }
+
/**
* Applies changes atomically to a Semantic Model.
*
diff --git a/api/src/test/java/org/apache/gravitino/semantic/TestOssieDocument.java b/api/src/test/java/org/apache/gravitino/semantic/TestOssieDocument.java
new file mode 100644
index 0000000000..0e95ac9d15
--- /dev/null
+++ b/api/src/test/java/org/apache/gravitino/semantic/TestOssieDocument.java
@@ -0,0 +1,67 @@
+/*
+ * 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.semantic;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.junit.jupiter.api.Test;
+
+public class TestOssieDocument {
+
+ @Test
+ public void testFactoriesPreserveContentAndDeclareFormat() {
+ String yaml = "version: 0.2.0.dev0\nname: sales\n";
+ OssieDocument yamlDocument = OssieDocument.yaml(yaml);
+ assertEquals(yaml, yamlDocument.content());
+ assertEquals(OssieFormat.YAML, yamlDocument.format());
+
+ String json = "{\"version\":\"0.2.0.dev0\",\"name\":\"sales\"}";
+ OssieDocument jsonDocument = OssieDocument.json(json);
+ assertEquals(json, jsonDocument.content());
+ assertEquals(OssieFormat.JSON, jsonDocument.format());
+ }
+
+ @Test
+ public void testConstructionDoesNotParseContent() {
+ assertEquals("name: [", OssieDocument.yaml("name: [").content());
+ assertEquals("not json", OssieDocument.json("not json").content());
+ }
+
+ @Test
+ public void testBlankContentIsRejected() {
+ for (String content : new String[] {null, "", " ", "\t\r\n"}) {
+ assertThrows(IllegalArgumentException.class, () -> OssieDocument.yaml(content));
+ assertThrows(IllegalArgumentException.class, () -> OssieDocument.json(content));
+ }
+ }
+
+ @Test
+ public void testEqualityIncludesContentAndFormat() {
+ OssieDocument document = OssieDocument.json("{}");
+ assertEquals(document, document);
+ assertEquals(document, OssieDocument.json("{}"));
+ assertEquals(document.hashCode(), OssieDocument.json("{}").hashCode());
+ assertNotEquals(document, OssieDocument.yaml("{}"));
+ assertNotEquals(document, OssieDocument.json("[]"));
+ assertNotEquals(document, null);
+ assertNotEquals(document, "{}");
+ }
+}
diff --git a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelCatalog.java b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelCatalog.java
index 5939490a50..490ebcf3a3 100644
--- a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelCatalog.java
+++ b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelCatalog.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.semantic;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Map;
@@ -38,6 +39,18 @@ public class TestSemanticModelCatalog {
assertFalse(catalog.semanticModelExists(NameIdentifier.of("schema", "missing")));
}
+ @Test
+ public void testOssieOperationsAreUnsupportedByDefault() {
+ SemanticModelCatalog catalog = new ExistsOnlySemanticModelCatalog();
+ assertThrows(
+ UnsupportedOperationException.class,
+ () -> catalog.importOssieDocument(Namespace.of("schema"), OssieDocument.yaml("{}")));
+ assertThrows(
+ UnsupportedOperationException.class,
+ () ->
+ catalog.exportOssieDocument(NameIdentifier.of("schema", "existing"), OssieFormat.YAML));
+ }
+
private static class ExistsOnlySemanticModelCatalog implements SemanticModelCatalog {
@Override
diff --git a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelSupportingTypes.java b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelSupportingTypes.java
index 5389f214e7..04307ebc2c 100644
--- a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelSupportingTypes.java
+++ b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelSupportingTypes.java
@@ -180,31 +180,6 @@ public class TestSemanticModelSupportingTypes {
assertEquals(equivalentContext.hashCode(), equivalentLongContext.hashCode());
}
- @Test
- public void testAIContextAdditionalPropertyBounds() {
- Object maximumDepthValue = "value";
- for (int depth = 0; depth < AIContextObject.MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH; depth++) {
- maximumDepthValue = Map.of("nested", maximumDepthValue);
- }
- AIContextObject.builder()
- .withAdditionalProperties(Map.of("maximumDepth", maximumDepthValue))
- .build();
-
- Object excessiveDepthValue = Map.of("nested", maximumDepthValue);
- assertThrows(
- IllegalArgumentException.class,
- () ->
- AIContextObject.builder()
- .withAdditionalProperties(Map.of("excessiveDepth", excessiveDepthValue))
- .build());
- assertThrows(
- IllegalArgumentException.class,
- () ->
- AIContextObject.builder()
- .withAdditionalProperties(Map.of("unsupportedNumber", new AtomicInteger(1)))
- .build());
- }
-
@Test
public void testSupportingTypeValidation() {
assertThrows(IllegalArgumentException.class, () -> DialectExpression.builder().build());
@@ -244,6 +219,12 @@ public class TestSemanticModelSupportingTypes {
AIContextObject.builder()
.withAdditionalProperties(Map.of("unsupported", new Object()))
.build());
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ AIContextObject.builder()
+ .withAdditionalProperties(Map.of("unsupportedNumber", new AtomicInteger(1)))
+ .build());
assertThrows(
IllegalArgumentException.class,
() ->
diff --git a/clients/client-python/gravitino/api/semantic/ai_context_object.py b/clients/client-python/gravitino/api/semantic/ai_context_object.py
index bee224a78a..b269b0842d 100644
--- a/clients/client-python/gravitino/api/semantic/ai_context_object.py
+++ b/clients/client-python/gravitino/api/semantic/ai_context_object.py
@@ -23,8 +23,6 @@ from typing import Any, Final, Optional
from gravitino.exceptions.base import IllegalArgumentException
from gravitino.utils.precondition import Precondition
-MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH: Final[int] = 100
-
_STANDARD_PROPERTIES: Final[frozenset] = frozenset(
{"instructions", "synonyms", "examples"}
)
@@ -121,13 +119,11 @@ def _normalize_additional_properties(
name not in _STANDARD_PROPERTIES,
f"additional property must not duplicate standard property: {name}",
)
- normalized[name] = _normalize_json_value(value, name, set(), 0)
+ normalized[name] = _normalize_json_value(value, name, set())
return normalized
-def _normalize_json_value(
- value: Any, path: str, visiting: set[int], container_depth: int
-) -> Any:
+def _normalize_json_value(value: Any, path: str, visiting: set[int]) -> Any:
if value is None or isinstance(value, (str, bool)):
return value
@@ -146,10 +142,10 @@ def _normalize_json_value(
return value
if isinstance(value, dict):
- return _normalize_json_dict(value, path, visiting, container_depth + 1)
+ return _normalize_json_dict(value, path, visiting)
if isinstance(value, (list, tuple)):
- return _normalize_json_list(value, path, visiting, container_depth + 1)
+ return _normalize_json_list(value, path, visiting)
raise IllegalArgumentException(
f"Additional property {path} has non-JSON-compatible value type: "
@@ -157,10 +153,8 @@ def _normalize_json_value(
)
-def _normalize_json_dict(
- value: dict, path: str, visiting: set[int], container_depth: int
-) -> dict[str, Any]:
- _enter_container(value, path, visiting, container_depth)
+def _normalize_json_dict(value: dict, path: str, visiting: set[int]) -> dict[str, Any]:
+ _enter_container(value, path, visiting)
try:
normalized = {}
for key, item in value.items():
@@ -168,35 +162,24 @@ def _normalize_json_dict(
isinstance(key, str),
f"Additional property {path} contains a map key that is not a string",
)
- normalized[key] = _normalize_json_value(
- item, f"{path}.{key}", visiting, container_depth
- )
+ normalized[key] = _normalize_json_value(item, f"{path}.{key}", visiting)
return normalized
finally:
visiting.discard(id(value))
-def _normalize_json_list(
- value, path: str, visiting: set[int], container_depth: int
-) -> list[Any]:
- _enter_container(value, path, visiting, container_depth)
+def _normalize_json_list(value, path: str, visiting: set[int]) -> list[Any]:
+ _enter_container(value, path, visiting)
try:
return [
- _normalize_json_value(item, f"{path}[{index}]", visiting, container_depth)
+ _normalize_json_value(item, f"{path}[{index}]", visiting)
for index, item in enumerate(value)
]
finally:
visiting.discard(id(value))
-def _enter_container(
- value: Any, path: str, visiting: set[int], container_depth: int
-) -> None:
- Precondition.check_argument(
- container_depth <= MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH,
- f"Additional property {path} exceeds maximum nesting depth of "
- f"{MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH}",
- )
+def _enter_container(value: Any, path: str, visiting: set[int]) -> None:
Precondition.check_argument(
id(value) not in visiting,
f"Additional property {path} contains a cyclic value",
diff --git a/clients/client-python/tests/unittests/api/semantic/test_semantic_model_supporting_types.py b/clients/client-python/tests/unittests/api/semantic/test_semantic_model_supporting_types.py
index 22fe689033..b26e0648a1 100644
--- a/clients/client-python/tests/unittests/api/semantic/test_semantic_model_supporting_types.py
+++ b/clients/client-python/tests/unittests/api/semantic/test_semantic_model_supporting_types.py
@@ -18,10 +18,7 @@
import unittest
from gravitino.api.semantic.ai_context import AIContext
-from gravitino.api.semantic.ai_context_object import (
- MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH,
- AIContextObject,
-)
+from gravitino.api.semantic.ai_context_object import AIContextObject
from gravitino.api.semantic.custom_extension import CustomExtension
from gravitino.api.semantic.data_type import DataType
from gravitino.api.semantic.dialect_expression import DialectExpression
@@ -250,14 +247,6 @@ class TestSemanticModelSupportingTypes(unittest.TestCase):
):
AIContextObject(additional_properties={"nested": cyclic})
- def test_ai_context_object_rejects_deeply_nested_additional_properties(self):
- value = "leaf"
- for _ in range(MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH + 1):
- value = [value]
-
- with self.assertRaisesRegex(ValueError, "exceeds maximum nesting depth of 100"):
- AIContextObject(additional_properties={"nested": value})
-
def test_ai_context_object_rejects_none_elements(self):
with self.assertRaisesRegex(ValueError, r"synonyms\[1\] must be a string"):
AIContextObject(synonyms=["sales", None])
diff --git a/core/build.gradle.kts b/core/build.gradle.kts
index a8511341f0..7d88be97a0 100644
--- a/core/build.gradle.kts
+++ b/core/build.gradle.kts
@@ -43,6 +43,8 @@ dependencies {
implementation(libs.concurrent.trees)
implementation(libs.guava)
implementation(libs.h2db)
+ implementation(libs.jackson.databind)
+ implementation(libs.jackson.dataformat.yaml)
implementation(libs.jackson.jaxrs.json.provider) // This is required by lance
implementation(libs.lance) {
exclude(group = "com.fasterxml.jackson.core", module = "*") // provided by gravitino
diff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java
index 2b35df18f2..b2c0a122d1 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java
@@ -18,7 +18,41 @@
*/
package org.apache.gravitino.catalog;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.semantic.OssieDocument;
+import org.apache.gravitino.semantic.OssieDocumentConverter;
+import org.apache.gravitino.semantic.OssieDocumentConverter.ImportedSemanticModel;
+import org.apache.gravitino.semantic.OssieFormat;
+import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelCatalog;
/** A dispatcher specialization for schema-scoped Semantic Model operations. */
-public interface SemanticModelDispatcher extends SemanticModelCatalog {}
+public interface SemanticModelDispatcher extends SemanticModelCatalog {
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Delegates to this dispatcher's native create operation so that the document follows the same
+ * normalization and validation chain as a structured create request.
+ */
+ @Override
+ default SemanticModel importOssieDocument(Namespace namespace, OssieDocument document) {
+ ImportedSemanticModel model = OssieDocumentConverter.importDocument(document);
+ return createSemanticModel(
+ NameIdentifier.of(namespace, model.name()),
+ model.comment(),
+ model.definition(),
+ model.properties());
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Loads the model through this dispatcher's native load operation before serializing it.
+ */
+ @Override
+ default OssieDocument exportOssieDocument(NameIdentifier ident, OssieFormat format) {
+ return OssieDocumentConverter.exportDocument(loadSemanticModel(ident), format);
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java
index 4608645a18..132a195830 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java
@@ -18,7 +18,12 @@
*/
package org.apache.gravitino.catalog;
+import static org.apache.gravitino.catalog.PropertiesMetadataHelpers.validatePropertyForAlter;
+import static org.apache.gravitino.catalog.PropertiesMetadataHelpers.validatePropertyForCreate;
+import static org.apache.gravitino.semantic.SemanticModel.PROPERTY_OSSIE_VERSION;
+
import com.google.common.base.Preconditions;
+import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.gravitino.Catalog;
@@ -33,12 +38,16 @@ import org.apache.gravitino.secret.SecretManager;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelPropertiesMetadata;
import org.apache.gravitino.storage.IdGenerator;
/** Dispatches always-managed Semantic Model operations to Gravitino's EntityStore. */
public class SemanticModelOperationDispatcher extends OperationDispatcher
implements SemanticModelDispatcher {
+ private static final SemanticModelPropertiesMetadata PROPERTIES_METADATA =
+ new SemanticModelPropertiesMetadata();
+
private final CatalogManager catalogManager;
private final SchemaDispatcher schemaDispatcher;
private final ManagedSemanticModelOperations managedOperations;
@@ -94,10 +103,16 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher
throws NoSuchSchemaException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException {
Preconditions.checkArgument(properties != null, "Properties must not be null");
+ validatePropertyForCreate(PROPERTIES_METADATA, properties);
+ Map<String, String> effectiveProperties = new HashMap<>(properties);
+ effectiveProperties.putIfAbsent(
+ PROPERTY_OSSIE_VERSION,
+ (String) PROPERTIES_METADATA.getDefaultValue(PROPERTY_OSSIE_VERSION));
+
checkRelationalCatalog(ident.namespace());
NameIdentifier schemaIdent = schemaIdentifier(ident);
schemaDispatcher.loadSchema(schemaIdent);
- return managedOperations.createSemanticModel(ident, comment, definition, properties);
+ return managedOperations.createSemanticModel(ident, comment, definition, effectiveProperties);
}
@Override
@@ -107,6 +122,7 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher
if (changes == null || changes.length == 0) {
throw new IllegalSemanticModelException("At least one Semantic Model change is required");
}
+ validatePropertyChanges(changes);
checkRelationalCatalog(ident.namespace());
NameIdentifier schemaIdent = schemaIdentifier(ident);
if (!schemaDispatcher.schemaExists(schemaIdent)) {
@@ -138,4 +154,20 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher
private static NameIdentifier schemaIdentifier(NameIdentifier ident) {
return NameIdentifier.of(ident.namespace().levels());
}
+
+ private static void validatePropertyChanges(SemanticModelChange[] changes) {
+ Map<String, String> upserts = new HashMap<>();
+ Map<String, String> deletes = new HashMap<>();
+ for (SemanticModelChange change : changes) {
+ if (change instanceof SemanticModelChange.SetProperty) {
+ SemanticModelChange.SetProperty setProperty = (SemanticModelChange.SetProperty) change;
+ upserts.put(setProperty.getProperty(), setProperty.getValue());
+ } else if (change instanceof SemanticModelChange.RemoveProperty) {
+ SemanticModelChange.RemoveProperty removeProperty =
+ (SemanticModelChange.RemoveProperty) change;
+ deletes.put(removeProperty.getProperty(), removeProperty.getProperty());
+ }
+ }
+ validatePropertyForAlter(PROPERTIES_METADATA, upserts, deletes);
+ }
}
diff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelValidator.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelValidator.java
index 211585b6ae..bebda80bb1 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelValidator.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelValidator.java
@@ -18,11 +18,14 @@
*/
package org.apache.gravitino.catalog;
+import static org.apache.gravitino.semantic.CustomExtension.GRAVITINO_PROPERTIES_VENDOR;
+
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.exceptions.IllegalSemanticModelException;
+import org.apache.gravitino.semantic.CustomExtension;
import org.apache.gravitino.semantic.Dataset;
import org.apache.gravitino.semantic.Field;
import org.apache.gravitino.semantic.Metric;
@@ -42,7 +45,7 @@ import org.apache.gravitino.semantic.SemanticModelDefinition;
* <p>The API value-object builders enforce value-level invariants, including required values, array
* element validity, relationship column shapes, and expression dialect uniqueness. This validator
* handles constraints that span value objects: name uniqueness, relationship endpoint resolution,
- * and Semantic Model source identifier shape.
+ * Semantic Model source identifier shape, and the reserved root properties extension vendor.
*
* <p>Validation is deterministic and performs no catalog I/O. Catalog-backed source validation,
* including existence, columns, and authorization, must be completed by the caller before this
@@ -54,7 +57,8 @@ final class SemanticModelValidator {
private SemanticModelValidator() {}
// TODO(#12594): Validate source existence, columns, and authorization in the caller before
- // invoking this definition-only validator.
+ // invoking this definition-only validator. Cover whitespace-only source segments in regression
+ // tests for create and replaceDefinition, and verify consistency with Ossie import/export.
static void validateDefinition(@Nullable SemanticModelDefinition definition) {
if (definition == null) {
throw invalid("$", "definition must not be null");
@@ -68,6 +72,20 @@ final class SemanticModelValidator {
validateRelationships(definition.relationships(), datasetNames);
validateMetrics(definition.metrics());
+ validateRootCustomExtensions(definition.customExtensions());
+ }
+
+ private static void validateRootCustomExtensions(@Nullable CustomExtension[] extensions) {
+ if (extensions == null) {
+ return;
+ }
+ for (int index = 0; index < extensions.length; index++) {
+ if (GRAVITINO_PROPERTIES_VENDOR.equals(extensions[index].vendorName())) {
+ throw invalid(
+ "customExtensions[" + index + "].vendorName",
+ "'" + GRAVITINO_PROPERTIES_VENDOR + "' is reserved for Gravitino properties");
+ }
+ }
}
private static void validateDataset(
diff --git a/core/src/main/java/org/apache/gravitino/semantic/OssieDocumentConverter.java b/core/src/main/java/org/apache/gravitino/semantic/OssieDocumentConverter.java
new file mode 100644
index 0000000000..08f80c9a66
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/semantic/OssieDocumentConverter.java
@@ -0,0 +1,991 @@
+/*
+ * 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.semantic;
+
+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 com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.StreamReadFeature;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
+import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.IllegalSemanticModelException;
+
+/** Converts between standalone Apache Ossie documents and Gravitino Semantic Models. */
+public final class OssieDocumentConverter {
+
+ private static final Set<String> ROOT_PROPERTIES =
+ Set.of(
+ "version",
+ "name",
+ "description",
+ "ai_context",
+ "datasets",
+ "relationships",
+ "metrics",
+ "custom_extensions");
+ private static final Set<String> DATASET_PROPERTIES =
+ Set.of(
+ "name",
+ "source",
+ "primary_key",
+ "unique_keys",
+ "description",
+ "ai_context",
+ "fields",
+ "custom_extensions");
+ private static final Set<String> FIELD_PROPERTIES =
+ Set.of(
+ "name",
+ "expression",
+ "dimension",
+ "label",
+ "description",
+ "datatype",
+ "ai_context",
+ "custom_extensions");
+ private static final Set<String> RELATIONSHIP_PROPERTIES =
+ Set.of("name", "from", "to", "from_columns", "to_columns", "ai_context", "custom_extensions");
+ private static final Set<String> METRIC_PROPERTIES =
+ Set.of("name", "expression", "description", "datatype", "ai_context", "custom_extensions");
+ private static final Set<String> EXPRESSION_PROPERTIES = Set.of("dialects");
+ private static final Set<String> DIALECT_EXPRESSION_PROPERTIES = Set.of("dialect", "expression");
+ private static final Set<String> DIMENSION_PROPERTIES = Set.of("is_time");
+ private static final Set<String> CUSTOM_EXTENSION_PROPERTIES = Set.of("vendor_name", "data");
+
+ private static final Set<String> AI_CONTEXT_PROPERTIES =
+ Set.of("instructions", "synonyms", "examples");
+
+ private static final ObjectMapper JSON_MAPPER = createJsonMapper();
+ private static final ObjectMapper YAML_MAPPER = createYamlMapper();
+
+ private OssieDocumentConverter() {}
+
+ /**
+ * Converts one standalone Apache Ossie YAML or JSON document into native model values.
+ *
+ * @param document The standalone Ossie document.
+ * @return The model name, comment, native definition, and properties.
+ * @throws IllegalSemanticModelException If the document cannot be parsed or represented by
+ * Gravitino.
+ */
+ public static ImportedSemanticModel importDocument(OssieDocument document) {
+ Objects.requireNonNull(document, "document must not be null");
+ ObjectNode root = parseDocument(document);
+ return toImportedModel(root);
+ }
+
+ /**
+ * Exports one Gravitino Semantic Model as a standalone Apache Ossie document.
+ *
+ * @param semanticModel The Semantic Model to export.
+ * @param format The requested serialization format.
+ * @return The serialized Ossie document.
+ * @throws IllegalSemanticModelException If the model cannot be represented as a valid Ossie
+ * document.
+ */
+ public static OssieDocument exportDocument(SemanticModel semanticModel, OssieFormat format) {
+ Objects.requireNonNull(semanticModel, "semanticModel must not be null");
+ Objects.requireNonNull(format, "format must not be null");
+
+ ObjectNode definition = writeDefinition(semanticModel.definition());
+
+ ObjectNode root = JSON_MAPPER.createObjectNode();
+ root.put("version", ossieVersion(semanticModel.properties()));
+ root.put("name", semanticModel.name());
+ if (semanticModel.comment() != null) {
+ root.put("description", semanticModel.comment());
+ }
+ definition.fields().forEachRemaining(entry -> root.set(entry.getKey(), entry.getValue()));
+ stashProperties(root, semanticModel.properties());
+
+ // Validate the generated document through the same conversion path used for imports.
+ toImportedModel(root.deepCopy());
+
+ try {
+ if (format == OssieFormat.JSON) {
+ return OssieDocument.json(
+ JSON_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(root) + "\n");
+ }
+ return OssieDocument.yaml(YAML_MAPPER.writeValueAsString(root));
+ } catch (JsonProcessingException e) {
+ throw new IllegalSemanticModelException(
+ e, "Cannot serialize Apache Ossie document: %s", e.getOriginalMessage());
+ }
+ }
+
+ /** Native model values parsed from an Ossie document, before the model is created. */
+ public static final class ImportedSemanticModel {
+
+ private final String name;
+ @Nullable private final String comment;
+ private final SemanticModelDefinition definition;
+ private final Map<String, String> properties;
+
+ private ImportedSemanticModel(
+ String name,
+ @Nullable String comment,
+ SemanticModelDefinition definition,
+ Map<String, String> properties) {
+ this.name = name;
+ this.comment = comment;
+ this.definition = definition;
+ this.properties = Map.copyOf(properties);
+ }
+
+ /**
+ * Returns the model name supplied by the document.
+ *
+ * @return The model name.
+ */
+ public String name() {
+ return name;
+ }
+
+ /**
+ * Returns the document description.
+ *
+ * @return The model comment, or {@code null} when absent.
+ */
+ @Nullable
+ public String comment() {
+ return comment;
+ }
+
+ /**
+ * Returns the parsed native definition.
+ *
+ * @return The immutable Semantic Model definition.
+ */
+ public SemanticModelDefinition definition() {
+ return definition;
+ }
+
+ /**
+ * Returns the Gravitino properties, including the Ossie version.
+ *
+ * @return The immutable properties.
+ */
+ public Map<String, String> properties() {
+ return properties;
+ }
+ }
+
+ private static ObjectMapper createJsonMapper() {
+ JsonFactory factory =
+ JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build();
+ return JsonMapper.builder(factory)
+ .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+ .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
+ .build();
+ }
+
+ private static ObjectMapper createYamlMapper() {
+ YAMLFactory factory =
+ YAMLFactory.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)
+ .build();
+ return new ObjectMapper(factory)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+ .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS);
+ }
+
+ private static ObjectNode parseDocument(OssieDocument document) {
+ String content = document.content();
+ try {
+ ObjectMapper mapper = document.format() == OssieFormat.JSON ? JSON_MAPPER : YAML_MAPPER;
+ // Reject trailing content after the standalone document.
+ JsonNode parsed =
+ mapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(content);
+ if (!(parsed instanceof ObjectNode)) {
+ throw invalid("$", "document root must be an object");
+ }
+ return (ObjectNode) parsed;
+ } catch (IOException e) {
+ throw new IllegalSemanticModelException(
+ e, "Cannot parse Apache Ossie %s: %s", document.format(), originalMessage(e));
+ }
+ }
+
+ private static ImportedSemanticModel toImportedModel(ObjectNode root) {
+ validateObject(root, "$", ROOT_PROPERTIES);
+ String name = readText(root, "name", "$");
+ String comment = readText(root, "description", "$");
+ String ossieVersion = validateVersion(root.get("version"));
+
+ Map<String, String> properties = new LinkedHashMap<>(extractProperties(root));
+ String extensionVersion = properties.get(PROPERTY_OSSIE_VERSION);
+ if (extensionVersion != null && !extensionVersion.equals(ossieVersion)) {
+ throw invalid(
+ "$.custom_extensions",
+ "Gravitino property '" + PROPERTY_OSSIE_VERSION + "' conflicts with $.version");
+ }
+ properties.put(PROPERTY_OSSIE_VERSION, ossieVersion);
+
+ try {
+ if (StringUtils.isBlank(name)) {
+ throw new IllegalArgumentException("\"name\" field is required and cannot be empty");
+ }
+ return new ImportedSemanticModel(name, comment, readDefinition(root), properties);
+ } catch (IllegalSemanticModelException e) {
+ throw e;
+ } catch (IllegalArgumentException e) {
+ throw new IllegalSemanticModelException(
+ e,
+ "Cannot convert Apache Ossie document to a Gravitino Semantic Model: %s",
+ originalMessage(e));
+ }
+ }
+
+ private static String validateVersion(@Nullable JsonNode version) {
+ if (version == null || !version.isTextual() || StringUtils.isBlank(version.textValue())) {
+ throw invalid("$.version", "must be a non-empty string");
+ }
+ return version.textValue();
+ }
+
+ private static String ossieVersion(Map<String, String> properties) {
+ String version = properties.getOrDefault(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION);
+ if (StringUtils.isBlank(version)) {
+ throw invalid(
+ "$.version",
+ "Semantic Model property '" + PROPERTY_OSSIE_VERSION + "' must not be blank");
+ }
+ return version;
+ }
+
+ private static SemanticModelDefinition readDefinition(ObjectNode root) {
+ return SemanticModelDefinition.builder()
+ .withAIContext(readAIContext(root.get("ai_context"), "$.ai_context"))
+ .withDatasets(
+ readObjectArray(
+ root.get("datasets"),
+ "$.datasets",
+ OssieDocumentConverter::readDataset,
+ Dataset[]::new))
+ .withRelationships(
+ readObjectArray(
+ root.get("relationships"),
+ "$.relationships",
+ OssieDocumentConverter::readRelationship,
+ Relationship[]::new))
+ .withMetrics(
+ readObjectArray(
+ root.get("metrics"),
+ "$.metrics",
+ OssieDocumentConverter::readMetric,
+ Metric[]::new))
+ .withCustomExtensions(
+ readCustomExtensions(root.get("custom_extensions"), "$.custom_extensions"))
+ .build();
+ }
+
+ private static Dataset readDataset(ObjectNode dataset, String path) {
+ validateObject(dataset, path, DATASET_PROPERTIES);
+ String source = readText(dataset, "source", path);
+ return Dataset.builder()
+ .withName(readText(dataset, "name", path))
+ .withSource(
+ source == null ? null : NameIdentifier.of(parseOssieSource(source, path + ".source")))
+ .withPrimaryKey(readStringArray(dataset, "primary_key", path))
+ .withUniqueKeys(readStringArrays(dataset, "unique_keys", path))
+ .withDescription(readText(dataset, "description", path))
+ .withAIContext(readAIContext(dataset.get("ai_context"), path + ".ai_context"))
+ .withFields(
+ readObjectArray(
+ dataset.get("fields"),
+ path + ".fields",
+ OssieDocumentConverter::readField,
+ Field[]::new))
+ .withCustomExtensions(
+ readCustomExtensions(dataset.get("custom_extensions"), path + ".custom_extensions"))
+ .build();
+ }
+
+ private static String[] parseOssieSource(String source, String path) {
+ List<String> parts = new ArrayList<>(3);
+ int offset = 0;
+ while (offset < source.length()) {
+ StringBuilder part = new StringBuilder();
+ if (source.charAt(offset) == '`') {
+ offset++;
+ boolean closed = false;
+ while (offset < source.length()) {
+ char current = source.charAt(offset);
+ if (current != '`') {
+ part.append(current);
+ offset++;
+ } else if (offset + 1 < source.length() && source.charAt(offset + 1) == '`') {
+ part.append('`');
+ offset += 2;
+ } else {
+ closed = true;
+ offset++;
+ break;
+ }
+ }
+ if (!closed) {
+ throw invalid(path, "contains an unterminated quoted segment");
+ }
+ if (offset < source.length() && source.charAt(offset) != '.') {
+ throw invalid(path, "quoted segments must be separated by dots");
+ }
+ } else {
+ while (offset < source.length() && source.charAt(offset) != '.') {
+ char current = source.charAt(offset);
+ if (current == '`') {
+ throw invalid(path, "backticks must quote an entire segment");
+ }
+ part.append(current);
+ offset++;
+ }
+ }
+
+ if (StringUtils.isBlank(part)) {
+ throw invalid(path, "source segments must not be blank");
+ }
+ parts.add(part.toString());
+ if (offset < source.length()) {
+ offset++;
+ if (offset == source.length()) {
+ throw invalid(path, "source segments must not be blank");
+ }
+ }
+ }
+
+ if (parts.size() != 3) {
+ throw invalid(
+ path,
+ "must be a three-part catalog.schema.entity identifier; query sources are not supported");
+ }
+ return parts.toArray(new String[0]);
+ }
+
+ private static Field readField(ObjectNode field, String path) {
+ validateObject(field, path, FIELD_PROPERTIES);
+ return Field.builder()
+ .withName(readText(field, "name", path))
+ .withExpression(readExpression(field.get("expression"), path + ".expression"))
+ .withDimension(readDimension(field.get("dimension"), path + ".dimension"))
+ .withLabel(readText(field, "label", path))
+ .withDescription(readText(field, "description", path))
+ .withDatatype(readDataType(field, path))
+ .withAIContext(readAIContext(field.get("ai_context"), path + ".ai_context"))
+ .withCustomExtensions(
+ readCustomExtensions(field.get("custom_extensions"), path + ".custom_extensions"))
+ .build();
+ }
+
+ private static Relationship readRelationship(ObjectNode relationship, String path) {
+ validateObject(relationship, path, RELATIONSHIP_PROPERTIES);
+ return Relationship.builder()
+ .withName(readText(relationship, "name", path))
+ .withFrom(readText(relationship, "from", path))
+ .withTo(readText(relationship, "to", path))
+ .withFromColumns(readStringArray(relationship, "from_columns", path))
+ .withToColumns(readStringArray(relationship, "to_columns", path))
+ .withAIContext(readAIContext(relationship.get("ai_context"), path + ".ai_context"))
+ .withCustomExtensions(
+ readCustomExtensions(
+ relationship.get("custom_extensions"), path + ".custom_extensions"))
+ .build();
+ }
+
+ private static Metric readMetric(ObjectNode metric, String path) {
+ validateObject(metric, path, METRIC_PROPERTIES);
+ return Metric.builder()
+ .withName(readText(metric, "name", path))
+ .withExpression(readExpression(metric.get("expression"), path + ".expression"))
+ .withDescription(readText(metric, "description", path))
+ .withDatatype(readDataType(metric, path))
+ .withAIContext(readAIContext(metric.get("ai_context"), path + ".ai_context"))
+ .withCustomExtensions(
+ readCustomExtensions(metric.get("custom_extensions"), path + ".custom_extensions"))
+ .build();
+ }
+
+ @Nullable
+ private static Expression readExpression(@Nullable JsonNode node, String path) {
+ if (node == null) {
+ return null;
+ }
+ ObjectNode expression = requireObject(node, path);
+ validateObject(expression, path, EXPRESSION_PROPERTIES);
+ return Expression.builder()
+ .withDialects(
+ readObjectArray(
+ expression.get("dialects"),
+ path + ".dialects",
+ OssieDocumentConverter::readDialectExpression,
+ DialectExpression[]::new))
+ .build();
+ }
+
+ private static DialectExpression readDialectExpression(ObjectNode dialect, String path) {
+ validateObject(dialect, path, DIALECT_EXPRESSION_PROPERTIES);
+ return DialectExpression.builder()
+ .withDialect(readText(dialect, "dialect", path))
+ .withExpression(readText(dialect, "expression", path))
+ .build();
+ }
+
+ @Nullable
+ private static Dimension readDimension(@Nullable JsonNode node, String path) {
+ if (node == null) {
+ return null;
+ }
+ ObjectNode dimension = requireObject(node, path);
+ validateObject(dimension, path, DIMENSION_PROPERTIES);
+ validateOptionalBoolean(dimension, "is_time", path);
+ JsonNode isTime = dimension.get("is_time");
+ return Dimension.builder().withIsTime(isTime == null ? null : isTime.booleanValue()).build();
+ }
+
+ @Nullable
+ private static DataType readDataType(ObjectNode object, String path) {
+ String value = readText(object, "datatype", path);
+ if (value == null) {
+ return null;
+ }
+ for (DataType type : DataType.values()) {
+ if (value.equals(dataTypeName(type))) {
+ return type;
+ }
+ }
+ throw invalid(
+ path + ".datatype",
+ "Unknown Semantic Model data type: "
+ + value
+ + ". Supported values: "
+ + Arrays.stream(DataType.values())
+ .map(OssieDocumentConverter::dataTypeName)
+ .collect(Collectors.joining(", ")));
+ }
+
+ private static String dataTypeName(DataType dataType) {
+ return switch (dataType) {
+ case STRING -> "String";
+ case INTEGER -> "Integer";
+ case DECIMAL -> "Decimal";
+ case FLOAT -> "Float";
+ case BOOLEAN -> "Boolean";
+ case DATE -> "Date";
+ case TIME -> "Time";
+ case DATE_TIME -> "DateTime";
+ case DATE_TIME_TZ -> "DateTimeTz";
+ case OPAQUE -> "Opaque";
+ };
+ }
+
+ @Nullable
+ private static CustomExtension[] readCustomExtensions(@Nullable JsonNode node, String path) {
+ return readObjectArray(
+ node,
+ path,
+ (extension, extensionPath) -> {
+ validateObject(extension, extensionPath, CUSTOM_EXTENSION_PROPERTIES);
+ return CustomExtension.builder()
+ .withVendorName(readText(extension, "vendor_name", extensionPath))
+ .withData(readText(extension, "data", extensionPath))
+ .build();
+ },
+ CustomExtension[]::new);
+ }
+
+ @Nullable
+ private static AIContext readAIContext(@Nullable JsonNode node, String path) {
+ if (node == null) {
+ return null;
+ }
+ if (node.isTextual()) {
+ return AIContext.of(node.textValue());
+ }
+ if (!(node instanceof ObjectNode)) {
+ throw invalid(path, "must be a string or object");
+ }
+ ObjectNode object = (ObjectNode) node;
+ Map<String, Object> additionalProperties = new LinkedHashMap<>();
+ object
+ .fields()
+ .forEachRemaining(
+ entry -> {
+ if (!AI_CONTEXT_PROPERTIES.contains(entry.getKey())) {
+ additionalProperties.put(
+ entry.getKey(), JSON_MAPPER.convertValue(entry.getValue(), Object.class));
+ }
+ });
+ return AIContext.of(
+ AIContextObject.builder()
+ .withInstructions(readText(object, "instructions", path))
+ .withSynonyms(readStringArray(object, "synonyms", path))
+ .withExamples(readStringArray(object, "examples", path))
+ .withAdditionalProperties(additionalProperties)
+ .build());
+ }
+
+ private static ObjectNode writeDefinition(SemanticModelDefinition definition) {
+ ObjectNode node = JSON_MAPPER.createObjectNode();
+ putOptional(node, "ai_context", writeAIContext(definition.aiContext()));
+ writeObjectArray(node, "datasets", definition.datasets(), OssieDocumentConverter::writeDataset);
+ writeObjectArray(
+ node,
+ "relationships",
+ definition.relationships(),
+ OssieDocumentConverter::writeRelationship);
+ writeObjectArray(node, "metrics", definition.metrics(), OssieDocumentConverter::writeMetric);
+ writeObjectArray(
+ node,
+ "custom_extensions",
+ definition.customExtensions(),
+ OssieDocumentConverter::writeCustomExtension);
+ return node;
+ }
+
+ private static ObjectNode writeDataset(Dataset dataset) {
+ ObjectNode node = JSON_MAPPER.createObjectNode();
+ node.put("name", dataset.name());
+ NameIdentifier source = dataset.source();
+ String[] namespace = source.namespace().levels();
+ node.put(
+ "source",
+ formatOssieSourceSegment(namespace[0])
+ + "."
+ + formatOssieSourceSegment(namespace[1])
+ + "."
+ + formatOssieSourceSegment(source.name()));
+ putOptional(node, "primary_key", dataset.primaryKey());
+ putOptional(node, "unique_keys", dataset.uniqueKeys());
+ putOptional(node, "description", dataset.description());
+ putOptional(node, "ai_context", writeAIContext(dataset.aiContext()));
+ writeObjectArray(node, "fields", dataset.fields(), OssieDocumentConverter::writeField);
+ writeObjectArray(
+ node,
+ "custom_extensions",
+ dataset.customExtensions(),
+ OssieDocumentConverter::writeCustomExtension);
+ return node;
+ }
+
+ private static String formatOssieSourceSegment(String segment) {
+ if (!segment.contains(".") && !segment.contains("`")) {
+ return segment;
+ }
+ return "`" + segment.replace("`", "``") + "`";
+ }
+
+ private static ObjectNode writeField(Field field) {
+ ObjectNode node = JSON_MAPPER.createObjectNode();
+ node.put("name", field.name());
+ node.set("expression", writeExpression(field.expression()));
+ if (field.dimension() != null) {
+ ObjectNode dimension = node.putObject("dimension");
+ putOptional(dimension, "is_time", field.dimension().isTime());
+ }
+ putOptional(node, "label", field.label());
+ putOptional(node, "description", field.description());
+ putOptional(node, "datatype", field.datatype() == null ? null : dataTypeName(field.datatype()));
+ putOptional(node, "ai_context", writeAIContext(field.aiContext()));
+ writeObjectArray(
+ node,
+ "custom_extensions",
+ field.customExtensions(),
+ OssieDocumentConverter::writeCustomExtension);
+ return node;
+ }
+
+ private static ObjectNode writeRelationship(Relationship relationship) {
+ ObjectNode node = JSON_MAPPER.createObjectNode();
+ node.put("name", relationship.name());
+ node.put("from", relationship.from());
+ node.put("to", relationship.to());
+ putOptional(node, "from_columns", relationship.fromColumns());
+ putOptional(node, "to_columns", relationship.toColumns());
+ putOptional(node, "ai_context", writeAIContext(relationship.aiContext()));
+ writeObjectArray(
+ node,
+ "custom_extensions",
+ relationship.customExtensions(),
+ OssieDocumentConverter::writeCustomExtension);
+ return node;
+ }
+
+ private static ObjectNode writeMetric(Metric metric) {
+ ObjectNode node = JSON_MAPPER.createObjectNode();
+ node.put("name", metric.name());
+ node.set("expression", writeExpression(metric.expression()));
+ putOptional(node, "description", metric.description());
+ putOptional(
+ node, "datatype", metric.datatype() == null ? null : dataTypeName(metric.datatype()));
+ putOptional(node, "ai_context", writeAIContext(metric.aiContext()));
+ writeObjectArray(
+ node,
+ "custom_extensions",
+ metric.customExtensions(),
+ OssieDocumentConverter::writeCustomExtension);
+ return node;
+ }
+
+ private static ObjectNode writeExpression(Expression expression) {
+ ObjectNode node = JSON_MAPPER.createObjectNode();
+ writeObjectArray(
+ node,
+ "dialects",
+ expression.dialects(),
+ dialect -> {
+ ObjectNode value = JSON_MAPPER.createObjectNode();
+ value.put("dialect", dialect.dialect());
+ value.put("expression", dialect.expression());
+ return value;
+ });
+ return node;
+ }
+
+ private static ObjectNode writeCustomExtension(CustomExtension extension) {
+ ObjectNode node = JSON_MAPPER.createObjectNode();
+ node.put("vendor_name", extension.vendorName());
+ node.put("data", extension.data());
+ return node;
+ }
+
+ @Nullable
+ private static JsonNode writeAIContext(@Nullable AIContext context) {
+ if (context == null) {
+ return null;
+ }
+ if (context.isText()) {
+ return JSON_MAPPER.getNodeFactory().textNode(context.text());
+ }
+ AIContextObject object = context.object();
+ ObjectNode node = JSON_MAPPER.createObjectNode();
+ putOptional(node, "instructions", object.instructions());
+ putOptional(node, "synonyms", object.synonyms());
+ putOptional(node, "examples", object.examples());
+ object
+ .additionalProperties()
+ .forEach((key, value) -> node.set(key, JSON_MAPPER.valueToTree(value)));
+ return node;
+ }
+
+ private static void stashProperties(ObjectNode root, Map<String, String> properties) {
+ Map<String, String> interchangeProperties = new LinkedHashMap<>();
+ if (properties != null) {
+ properties.forEach(
+ (key, value) -> {
+ if (!PROPERTY_OSSIE_VERSION.equals(key)) {
+ interchangeProperties.put(key, value);
+ }
+ });
+ }
+
+ JsonNode existingExtensions = root.get("custom_extensions");
+ ArrayNode extensions;
+ if (existingExtensions == null) {
+ if (interchangeProperties.isEmpty()) {
+ return;
+ }
+ extensions = root.putArray("custom_extensions");
+ } else if (existingExtensions instanceof ArrayNode) {
+ extensions = (ArrayNode) existingExtensions;
+ } else {
+ throw invalid("$.custom_extensions", "must be an array");
+ }
+ ensureNoPropertiesExtension(extensions);
+
+ if (interchangeProperties.isEmpty()) {
+ return;
+ }
+
+ ObjectNode extension = extensions.addObject();
+ extension.put("vendor_name", GRAVITINO_PROPERTIES_VENDOR);
+ extension.put("data", writeExtensionData(JSON_MAPPER.valueToTree(interchangeProperties)));
+ }
+
+ private static Map<String, String> extractProperties(ObjectNode root) {
+ JsonNode extensionsNode = root.get("custom_extensions");
+ if (!(extensionsNode instanceof ArrayNode)) {
+ return Map.of();
+ }
+
+ ArrayNode extensions = (ArrayNode) extensionsNode;
+ Map<String, String> properties = new LinkedHashMap<>();
+ boolean found = false;
+ int index = 0;
+ Iterator<JsonNode> iterator = extensions.iterator();
+ while (iterator.hasNext()) {
+ JsonNode candidate = iterator.next();
+ String path = "$.custom_extensions[" + index++ + "]";
+ if (!(candidate instanceof ObjectNode)) {
+ continue;
+ }
+ ObjectNode extension = (ObjectNode) candidate;
+ if (!GRAVITINO_PROPERTIES_VENDOR.equals(extension.path("vendor_name").asText(null))) {
+ continue;
+ }
+
+ if (found) {
+ throw invalid(
+ "$.custom_extensions",
+ "contains multiple " + GRAVITINO_PROPERTIES_VENDOR + " extensions");
+ }
+
+ validateObject(extension, path, CUSTOM_EXTENSION_PROPERTIES);
+ ObjectNode propertyNode = parsePropertiesData(extension.get("data"), path + ".data");
+ propertyNode
+ .fields()
+ .forEachRemaining(
+ entry -> {
+ if (!entry.getValue().isTextual()) {
+ throw invalid(
+ path + ".data",
+ "Gravitino property '" + entry.getKey() + "' must be a string");
+ }
+ properties.put(entry.getKey(), entry.getValue().textValue());
+ });
+ found = true;
+
+ iterator.remove();
+ }
+ if (extensions.isEmpty()) {
+ root.remove("custom_extensions");
+ }
+ return properties;
+ }
+
+ private static void ensureNoPropertiesExtension(ArrayNode extensions) {
+ for (int index = 0; index < extensions.size(); index++) {
+ if (GRAVITINO_PROPERTIES_VENDOR.equals(
+ extensions.get(index).path("vendor_name").asText(null))) {
+ throw invalid(
+ "$.custom_extensions[" + index + "].vendor_name",
+ "'" + GRAVITINO_PROPERTIES_VENDOR + "' is reserved for Gravitino properties");
+ }
+ }
+ }
+
+ private static ObjectNode parsePropertiesData(@Nullable JsonNode data, String path) {
+ if (data == null || !data.isTextual()) {
+ throw invalid(path, "must be a JSON string containing an object with string values");
+ }
+ try {
+ JsonNode parsed =
+ JSON_MAPPER
+ .reader()
+ .with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .readTree(data.textValue());
+ if (!(parsed instanceof ObjectNode)) {
+ throw invalid(path, "must contain a JSON object with string values");
+ }
+ return (ObjectNode) parsed;
+ } catch (JsonProcessingException e) {
+ throw invalid(path, "cannot parse Gravitino properties: " + e.getOriginalMessage());
+ }
+ }
+
+ private static String writeExtensionData(ObjectNode payload) {
+ try {
+ return JSON_MAPPER.writeValueAsString(payload);
+ } catch (JsonProcessingException e) {
+ throw new IllegalSemanticModelException(
+ e, "Cannot serialize Gravitino properties extension: %s", e.getOriginalMessage());
+ }
+ }
+
+ private static void validateObject(ObjectNode object, String path, Set<String> allowed) {
+ object
+ .fields()
+ .forEachRemaining(
+ entry -> {
+ if (!allowed.contains(entry.getKey())) {
+ throw invalid(
+ path + "." + entry.getKey(), "property is not defined by Apache Ossie");
+ }
+ if (entry.getValue().isNull()) {
+ throw invalid(path + "." + entry.getKey(), "must not be null");
+ }
+ });
+ }
+
+ private static void validateOptionalText(ObjectNode object, String name, String path) {
+ JsonNode value = object.get(name);
+ if (value != null && !value.isTextual()) {
+ throw invalid(path + "." + name, "must be a string");
+ }
+ }
+
+ private static void validateOptionalBoolean(ObjectNode object, String name, String path) {
+ JsonNode value = object.get(name);
+ if (value != null && !value.isBoolean()) {
+ throw invalid(path + "." + name, "must be a boolean");
+ }
+ }
+
+ private static void validateOptionalStringArray(ObjectNode object, String name, String path) {
+ JsonNode value = object.get(name);
+ if (value == null) {
+ return;
+ }
+ if (!(value instanceof ArrayNode)) {
+ throw invalid(path + "." + name, "must be an array of strings");
+ }
+ for (int index = 0; index < value.size(); index++) {
+ if (!value.get(index).isTextual()) {
+ throw invalid(path + "." + name + "[" + index + "]", "must be a string");
+ }
+ }
+ }
+
+ private static void validateOptionalStringArrayArray(
+ ObjectNode object, String name, String path) {
+ JsonNode value = object.get(name);
+ if (value == null) {
+ return;
+ }
+ if (!(value instanceof ArrayNode)) {
+ throw invalid(path + "." + name, "must be an array of string arrays");
+ }
+ for (int outerIndex = 0; outerIndex < value.size(); outerIndex++) {
+ JsonNode nestedValue = value.get(outerIndex);
+ if (!(nestedValue instanceof ArrayNode)) {
+ throw invalid(path + "." + name + "[" + outerIndex + "]", "must be an array of strings");
+ }
+ for (int innerIndex = 0; innerIndex < nestedValue.size(); innerIndex++) {
+ if (!nestedValue.get(innerIndex).isTextual()) {
+ throw invalid(
+ path + "." + name + "[" + outerIndex + "][" + innerIndex + "]", "must be a string");
+ }
+ }
+ }
+ }
+
+ @Nullable
+ private static String readText(ObjectNode object, String name, String path) {
+ validateOptionalText(object, name, path);
+ JsonNode value = object.get(name);
+ return value == null ? null : value.textValue();
+ }
+
+ @Nullable
+ private static String[] readStringArray(ObjectNode object, String name, String path) {
+ validateOptionalStringArray(object, name, path);
+ return object.has(name) ? stringArray(object.get(name)) : null;
+ }
+
+ private static String[] stringArray(JsonNode array) {
+ String[] values = new String[array.size()];
+ for (int index = 0; index < values.length; index++) {
+ values[index] = array.get(index).textValue();
+ }
+ return values;
+ }
+
+ @Nullable
+ private static String[][] readStringArrays(ObjectNode object, String name, String path) {
+ validateOptionalStringArrayArray(object, name, path);
+ JsonNode array = object.get(name);
+ if (array == null) {
+ return null;
+ }
+ String[][] values = new String[array.size()][];
+ for (int index = 0; index < values.length; index++) {
+ values[index] = stringArray(array.get(index));
+ }
+ return values;
+ }
+
+ private static ObjectNode requireObject(JsonNode node, String path) {
+ if (!(node instanceof ObjectNode)) {
+ throw invalid(path, "must be an object");
+ }
+ return (ObjectNode) node;
+ }
+
+ @Nullable
+ private static <T> T[] readObjectArray(
+ @Nullable JsonNode node, String path, ObjectReader<T> reader, IntFunction<T[]> arrayFactory) {
+ if (node == null) {
+ return null;
+ }
+ if (!(node instanceof ArrayNode)) {
+ throw invalid(path, "must be an array of objects");
+ }
+ T[] values = arrayFactory.apply(node.size());
+ for (int index = 0; index < values.length; index++) {
+ String itemPath = path + "[" + index + "]";
+ values[index] = reader.read(requireObject(node.get(index), itemPath), itemPath);
+ }
+ return values;
+ }
+
+ private static <T> void writeObjectArray(
+ ObjectNode object, String name, @Nullable T[] values, Function<T, ObjectNode> writer) {
+ if (values != null) {
+ ArrayNode array = object.putArray(name);
+ for (T value : values) {
+ array.add(writer.apply(value));
+ }
+ }
+ }
+
+ private static void putOptional(ObjectNode object, String name, @Nullable Object value) {
+ if (value != null) {
+ object.set(name, JSON_MAPPER.valueToTree(value));
+ }
+ }
+
+ private static String originalMessage(Exception exception) {
+ if (exception instanceof JsonProcessingException) {
+ return ((JsonProcessingException) exception).getOriginalMessage();
+ }
+ return exception.getMessage();
+ }
+
+ private static IllegalSemanticModelException invalid(String path, String detail) {
+ return new IllegalSemanticModelException("%s: %s", path, detail);
+ }
+
+ @FunctionalInterface
+ private interface ObjectReader<T> {
+ T read(ObjectNode object, String path);
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/semantic/SemanticModelPropertiesMetadata.java b/core/src/main/java/org/apache/gravitino/semantic/SemanticModelPropertiesMetadata.java
new file mode 100644
index 0000000000..30fe623530
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/semantic/SemanticModelPropertiesMetadata.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.semantic;
+
+import static org.apache.gravitino.semantic.OssieVersion.DEFAULT_VERSION;
+import static org.apache.gravitino.semantic.SemanticModel.PROPERTY_OSSIE_VERSION;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import java.util.Map;
+import java.util.function.Function;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.connector.PropertiesMetadata;
+import org.apache.gravitino.connector.PropertyEntry;
+
+/** Property metadata shared by all Gravitino-managed Semantic Models. */
+public final class SemanticModelPropertiesMetadata implements PropertiesMetadata {
+
+ private static final Map<String, PropertyEntry<?>> PROPERTY_ENTRIES =
+ ImmutableMap.of(
+ PROPERTY_OSSIE_VERSION,
+ new PropertyEntry.Builder<String>()
+ .withName(PROPERTY_OSSIE_VERSION)
+ .withDescription("The Apache Ossie document version used for import and export")
+ .withRequired(false)
+ .withImmutable(false)
+ .withJavaType(String.class)
+ .withDefaultValue(DEFAULT_VERSION)
+ .withDecoder(SemanticModelPropertiesMetadata::decodeOssieVersion)
+ .withEncoder(Function.identity())
+ .withHidden(false)
+ .withReserved(false)
+ .build());
+
+ /** Creates Semantic Model property metadata. */
+ public SemanticModelPropertiesMetadata() {}
+
+ @Override
+ public Map<String, PropertyEntry<?>> propertyEntries() {
+ return PROPERTY_ENTRIES;
+ }
+
+ private static String decodeOssieVersion(String value) {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(value), "Apache Ossie version must not be blank");
+ return value;
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java
index d10d207346..154eec5b69 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java
@@ -18,11 +18,18 @@
*/
package org.apache.gravitino.catalog;
+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.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.util.Locale;
@@ -33,11 +40,15 @@ import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.connector.capability.CapabilityResult;
import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.OssieDocument;
+import org.apache.gravitino.semantic.OssieDocumentConverter;
+import org.apache.gravitino.semantic.OssieFormat;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
public class TestSemanticModelNormalizeDispatcher {
@@ -112,6 +123,57 @@ public class TestSemanticModelNormalizeDispatcher {
() -> dispatcher.alterSemanticModel(INPUT_IDENT, new SemanticModelChange[0]));
}
+ @Test
+ public void testOssieImportUsesNativeCreateNormalization() {
+ SemanticModel model = mock(SemanticModel.class);
+ Map<String, String> properties = Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION);
+ when(delegate.createSemanticModel(
+ eq(NORMALIZED_IDENT), isNull(), any(SemanticModelDefinition.class), eq(properties)))
+ .thenReturn(model);
+
+ assertEquals(
+ model, dispatcher.importOssieDocument(INPUT_NAMESPACE, ossieDocument("SalesModel")));
+
+ ArgumentCaptor<SemanticModelDefinition> definition =
+ ArgumentCaptor.forClass(SemanticModelDefinition.class);
+ verify(delegate)
+ .createSemanticModel(eq(NORMALIZED_IDENT), isNull(), definition.capture(), eq(properties));
+ assertEquals(definition(), definition.getValue());
+ verifyNoMoreInteractions(delegate);
+ }
+
+ @Test
+ public void testOssieImportRejectsInvalidModelName() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> dispatcher.importOssieDocument(INPUT_NAMESPACE, ossieDocument("invalid model")));
+ verifyNoInteractions(delegate);
+ }
+
+ @Test
+ public void testOssieExportUsesNativeLoadNormalization() {
+ SemanticModel model = mock(SemanticModel.class);
+ when(model.name()).thenReturn("SalesModel");
+ when(model.definition()).thenReturn(definition());
+ when(model.properties()).thenReturn(Map.of());
+ when(delegate.loadSemanticModel(NORMALIZED_IDENT)).thenReturn(model);
+
+ OssieDocument document = dispatcher.exportOssieDocument(INPUT_IDENT, OssieFormat.JSON);
+
+ assertEquals(OssieFormat.JSON, document.format());
+ assertEquals("SalesModel", OssieDocumentConverter.importDocument(document).name());
+ verify(delegate).loadSemanticModel(NORMALIZED_IDENT);
+ verifyNoMoreInteractions(delegate);
+ }
+
+ private static OssieDocument ossieDocument(String name) {
+ return OssieDocument.yaml(
+ "version: 0.2.0.dev0\nname: "
+ + name
+ + "\ndatasets:\n"
+ + " - name: orders\n source: sales.mart.orders\n");
+ }
+
private static SemanticModelDefinition definition() {
Dataset dataset =
Dataset.builder()
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java
index f4be170d51..98da2ea078 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java
@@ -21,6 +21,9 @@ package org.apache.gravitino.catalog;
import static org.apache.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;
import static org.apache.gravitino.Configs.TREE_LOCK_MAX_NODE_IN_MEMORY;
import static org.apache.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;
+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;
@@ -44,9 +47,13 @@ import org.apache.gravitino.Schema;
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.lock.LockManager;
import org.apache.gravitino.secret.SecretManager;
+import org.apache.gravitino.semantic.CustomExtension;
import org.apache.gravitino.semantic.Dataset;
+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.SemanticModelChange;
@@ -56,6 +63,8 @@ import org.apache.gravitino.storage.memory.TestMemoryEntityStore.InMemoryEntityS
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
public class TestSemanticModelOperationDispatcher {
@@ -109,9 +118,90 @@ public class TestSemanticModelOperationDispatcher {
assertEquals("sales_model", created.name());
assertEquals(2, created.definition().datasets().length);
+ assertEquals(DEFAULT_VERSION, created.properties().get(PROPERTY_OSSIE_VERSION));
assertSame(created, dispatcher.loadSemanticModel(MODEL_IDENT));
}
+ @Test
+ public void testCreatePreservesExplicitOssieVersion() {
+ SemanticModel created =
+ dispatcher.createSemanticModel(
+ MODEL_IDENT,
+ "Sales",
+ validDefinition(),
+ Map.of(PROPERTY_OSSIE_VERSION, "future-version"));
+
+ assertEquals("future-version", created.properties().get(PROPERTY_OSSIE_VERSION));
+ }
+
+ @Test
+ public void testCreateRejectsBlankOssieVersionBeforeCatalogLookup() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ dispatcher.createSemanticModel(
+ MODEL_IDENT, null, validDefinition(), Map.of(PROPERTY_OSSIE_VERSION, " ")));
+ verify(catalogManager, never()).loadCatalog(METADATA_CATALOG_IDENT);
+ }
+
+ @Test
+ public void testCreateRejectsReservedPropertiesExtensionWithoutPersisting() {
+ IllegalSemanticModelException exception =
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () ->
+ dispatcher.createSemanticModel(
+ MODEL_IDENT, "Sales", definitionWithReservedExtension(), Map.of()));
+
+ assertTrue(exception.getMessage().contains("reserved for Gravitino properties"));
+ assertFalse(dispatcher.semanticModelExists(MODEL_IDENT));
+ }
+
+ @Test
+ public void testReplaceRejectsReservedPropertiesExtensionWithoutPersistingOtherChanges() {
+ SemanticModel original =
+ dispatcher.createSemanticModel(
+ MODEL_IDENT, "Original", validDefinition(), Map.of("owner", "sales"));
+
+ IllegalSemanticModelException exception =
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () ->
+ dispatcher.alterSemanticModel(
+ MODEL_IDENT,
+ SemanticModelChange.updateComment("Must not persist"),
+ SemanticModelChange.setProperty("owner", "changed"),
+ SemanticModelChange.replaceDefinition(definitionWithReservedExtension())));
+
+ assertTrue(exception.getMessage().contains("reserved for Gravitino properties"));
+ SemanticModel loaded = dispatcher.loadSemanticModel(MODEL_IDENT);
+ assertEquals(original.comment(), loaded.comment());
+ assertEquals(original.properties(), loaded.properties());
+ assertEquals(original.definition(), loaded.definition());
+ }
+
+ @Test
+ public void testAlterRejectsBlankOssieVersionBeforeCatalogLookup() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ dispatcher.alterSemanticModel(
+ MODEL_IDENT, SemanticModelChange.setProperty(PROPERTY_OSSIE_VERSION, " ")));
+ verify(catalogManager, never()).loadCatalog(METADATA_CATALOG_IDENT);
+ }
+
+ @Test
+ public void testAlterCanRemoveOssieVersion() {
+ dispatcher.createSemanticModel(
+ MODEL_IDENT, "Sales", validDefinition(), Map.of(PROPERTY_OSSIE_VERSION, "future-version"));
+
+ SemanticModel altered =
+ dispatcher.alterSemanticModel(
+ MODEL_IDENT, SemanticModelChange.removeProperty(PROPERTY_OSSIE_VERSION));
+
+ assertFalse(altered.properties().containsKey(PROPERTY_OSSIE_VERSION));
+ }
+
@Test
public void testSchemaFailureRemainsTyped() {
when(schemaDispatcher.loadSchema(SCHEMA_IDENT))
@@ -146,7 +236,9 @@ public class TestSemanticModelOperationDispatcher {
SemanticModelChange.rename("renamed_sales_model"),
SemanticModelChange.updateComment("Updated"));
NameIdentifier renamedIdent = NameIdentifier.of(NAMESPACE, renamed.name());
- assertEquals(Map.of("owner", "analytics"), propertyUpdated.properties());
+ assertEquals(
+ Map.of("owner", "analytics", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION),
+ propertyUpdated.properties());
assertEquals("Updated", renamed.comment());
SemanticModel replaced =
@@ -229,6 +321,101 @@ public class TestSemanticModelOperationDispatcher {
verify(catalogManager, never()).loadCatalog(METADATA_CATALOG_IDENT);
}
+ @ParameterizedTest
+ @EnumSource(OssieFormat.class)
+ public void testOssieExportImportRoundTrip(OssieFormat format) {
+ CustomExtension ordinary =
+ CustomExtension.builder()
+ .withVendorName("GRAVITINO")
+ .withData("{\"_apache_gravitino_interchange\":1}")
+ .build();
+ SemanticModelDefinition baseDefinition = validDefinition();
+ SemanticModelDefinition definition =
+ SemanticModelDefinition.builder()
+ .withDatasets(baseDefinition.datasets())
+ .withRelationships(baseDefinition.relationships())
+ .withCustomExtensions(new CustomExtension[] {ordinary})
+ .build();
+ SemanticModel original =
+ dispatcher.createSemanticModel(
+ MODEL_IDENT,
+ "Sales",
+ definition,
+ Map.of("domain", "sales", PROPERTY_OSSIE_VERSION, "future-version"));
+
+ OssieDocument document = dispatcher.exportOssieDocument(MODEL_IDENT, format);
+ assertEquals(format, document.format());
+ assertThrows(
+ SemanticModelAlreadyExistsException.class,
+ () -> dispatcher.importOssieDocument(NAMESPACE, document));
+ assertSame(original, dispatcher.loadSemanticModel(MODEL_IDENT));
+
+ assertTrue(dispatcher.dropSemanticModel(MODEL_IDENT));
+ SemanticModel imported = dispatcher.importOssieDocument(NAMESPACE, document);
+ assertEquals(original.name(), imported.name());
+ assertEquals(original.comment(), imported.comment());
+ assertEquals(original.definition(), imported.definition());
+ assertEquals(original.properties(), imported.properties());
+ assertSame(imported, dispatcher.loadSemanticModel(MODEL_IDENT));
+ }
+
+ @Test
+ public void testOssieImportReusesDefinitionValidationWithoutPersisting() {
+ OssieDocument invalid =
+ OssieDocument.yaml(
+ """
+ version: 0.2.0.dev0
+ name: sales_model
+ datasets:
+ - name: orders
+ source: sales.mart.orders
+ relationships:
+ - name: orders_to_missing
+ from: orders
+ to: missing
+ from_columns: [customer_id]
+ to_columns: [customer_id]
+ """);
+
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () -> dispatcher.importOssieDocument(NAMESPACE, invalid));
+ assertFalse(dispatcher.semanticModelExists(MODEL_IDENT));
+ }
+
+ @Test
+ public void testOssieImportRejectsWrongFormatBeforeCatalogLookup() {
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () ->
+ dispatcher.importOssieDocument(
+ NAMESPACE, OssieDocument.json(ossieDocument().content())));
+ verify(catalogManager, never()).loadCatalog(METADATA_CATALOG_IDENT);
+ }
+
+ @Test
+ public void testOssieOperationsPreserveMissingObjectErrors() {
+ assertThrows(
+ NoSuchSemanticModelException.class,
+ () -> dispatcher.exportOssieDocument(MODEL_IDENT, OssieFormat.YAML));
+ when(schemaDispatcher.loadSchema(SCHEMA_IDENT))
+ .thenThrow(new NoSuchSchemaException("Schema does not exist"));
+ assertThrows(
+ NoSuchSchemaException.class,
+ () -> dispatcher.importOssieDocument(NAMESPACE, ossieDocument()));
+ }
+
+ private static OssieDocument ossieDocument() {
+ return OssieDocument.yaml(
+ """
+ version: 0.2.0.dev0
+ name: sales_model
+ datasets:
+ - name: orders
+ source: sales.mart.orders
+ """);
+ }
+
private static SemanticModelDefinition validDefinition() {
Dataset orders =
dataset("orders", "orders", new String[] {"order_id"}, new String[][] {{"customer_id"}});
@@ -248,6 +435,18 @@ public class TestSemanticModelOperationDispatcher {
.build();
}
+ private static SemanticModelDefinition definitionWithReservedExtension() {
+ CustomExtension extension =
+ CustomExtension.builder()
+ .withVendorName(GRAVITINO_PROPERTIES_VENDOR)
+ .withData("not JSON")
+ .build();
+ return SemanticModelDefinition.builder()
+ .withDatasets(validDefinition().datasets())
+ .withCustomExtensions(new CustomExtension[] {extension})
+ .build();
+ }
+
private static Dataset dataset(
String name, String source, String[] primaryKey, String[][] uniqueKeys) {
return Dataset.builder()
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelValidator.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelValidator.java
index cff181337a..757354f7d7 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelValidator.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelValidator.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.catalog;
+import static org.apache.gravitino.semantic.CustomExtension.GRAVITINO_PROPERTIES_VENDOR;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -105,6 +106,50 @@ public class TestSemanticModelValidator {
"datasets[0].source: must contain exactly catalog.schema.name, but was 'sales.orders'");
}
+ @Test
+ public void testRejectsReservedRootExtensionRegardlessOfData() {
+ for (String data : new String[] {"{}", "{\"owner\":\"analytics\"}", "not JSON"}) {
+ CustomExtension reserved =
+ CustomExtension.builder()
+ .withVendorName(GRAVITINO_PROPERTIES_VENDOR)
+ .withData(data)
+ .build();
+ SemanticModelDefinition definition =
+ SemanticModelDefinition.builder()
+ .withDatasets(new Dataset[] {dataset("orders")})
+ .withCustomExtensions(new CustomExtension[] {reserved})
+ .build();
+
+ assertInvalid(
+ definition,
+ "customExtensions[0].vendorName: 'GRAVITINO_PROPERTIES' is reserved for Gravitino properties");
+ }
+ }
+
+ @Test
+ public void testPreservesOrdinaryRootAndNestedPropertiesVendorExtensions() {
+ CustomExtension nested =
+ CustomExtension.builder()
+ .withVendorName(GRAVITINO_PROPERTIES_VENDOR)
+ .withData("not JSON")
+ .build();
+ Dataset orders =
+ Dataset.builder()
+ .withName("orders")
+ .withSource(NameIdentifier.of("sales", "mart", "orders"))
+ .withCustomExtensions(new CustomExtension[] {nested})
+ .build();
+ CustomExtension ordinary =
+ CustomExtension.builder().withVendorName("GRAVITINO").withData("not JSON").build();
+ SemanticModelDefinition definition =
+ SemanticModelDefinition.builder()
+ .withDatasets(new Dataset[] {orders})
+ .withCustomExtensions(new CustomExtension[] {ordinary})
+ .build();
+
+ assertDoesNotThrow(() -> SemanticModelValidator.validateDefinition(definition));
+ }
+
@Test
public void testFieldNamesAreUniquePerDataset() {
Dataset duplicateFields =
diff --git a/core/src/test/java/org/apache/gravitino/semantic/TestOssieDocumentConverter.java b/core/src/test/java/org/apache/gravitino/semantic/TestOssieDocumentConverter.java
new file mode 100644
index 0000000000..366151e845
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/semantic/TestOssieDocumentConverter.java
@@ -0,0 +1,878 @@
+/*
+ * 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.semantic;
+
+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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+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.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.time.Instant;
+import java.util.Map;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.IllegalSemanticModelException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.OssieDocumentConverter.ImportedSemanticModel;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+/** Tests standalone Apache Ossie document import, export, and conversion diagnostics. */
+public class TestOssieDocumentConverter {
+
+ private static final JsonMapper JSON_MAPPER = JsonMapper.builder().build();
+ private static final ObjectMapper YAML_MAPPER = new ObjectMapper(new YAMLFactory());
+
+ @Test
+ public void testImportYamlAndJsonDocuments() {
+ String yaml =
+ """
+ version: 0.2.0.dev0
+ name: sales
+ description: Governed sales definitions
+ ai_context:
+ instructions: Use certified definitions
+ confidence: 0.95
+ datasets:
+ - name: orders
+ source: sales.mart.orders
+ primary_key: [order_id]
+ fields:
+ - name: order_id
+ expression:
+ dialects:
+ - dialect: ANSI_SQL
+ expression: order_id
+ datatype: String
+ dimension: {}
+ relationships: []
+ metrics:
+ - name: revenue
+ expression:
+ dialects:
+ - dialect: DAX
+ expression: SUM(orders.amount)
+ datatype: Decimal
+ custom_extensions:
+ - vendor_name: EXAMPLE
+ data: '{"certified":true}'
+ - vendor_name: GRAVITINO_PROPERTIES
+ data: '{"domain":"sales"}'
+ """;
+
+ ImportedSemanticModel yamlModel =
+ OssieDocumentConverter.importDocument(OssieDocument.yaml(yaml));
+ assertEquals("sales", yamlModel.name());
+ assertEquals("Governed sales definitions", yamlModel.comment());
+ assertEquals(
+ Map.of("domain", "sales", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION), yamlModel.properties());
+ SemanticModelDefinition yamlDefinition = yamlModel.definition();
+ assertEquals(
+ NameIdentifier.of("sales", "mart", "orders"), yamlDefinition.datasets()[0].source());
+ assertEquals("DAX", yamlDefinition.metrics()[0].expression().dialects()[0].dialect());
+ assertEquals(DataType.STRING, yamlDefinition.datasets()[0].fields()[0].datatype());
+ assertNull(yamlDefinition.datasets()[0].fields()[0].dimension().isTime());
+ assertEquals(1, yamlDefinition.customExtensions().length);
+ assertEquals("EXAMPLE", yamlDefinition.customExtensions()[0].vendorName());
+ assertEquals("Use certified definitions", yamlDefinition.aiContext().object().instructions());
+ assertEquals(
+ "0.95",
+ yamlDefinition.aiContext().object().additionalProperties().get("confidence").toString());
+
+ String json =
+ """
+ {
+ "version": "future-version",
+ "name": "inventory",
+ "datasets": [
+ {"name": "items", "source": "sales.mart.items", "fields": []}
+ ]
+ }
+ """;
+ ImportedSemanticModel jsonModel =
+ OssieDocumentConverter.importDocument(OssieDocument.json(json));
+ assertEquals("inventory", jsonModel.name());
+ assertEquals("future-version", jsonModel.properties().get(PROPERTY_OSSIE_VERSION));
+ assertEquals(
+ NameIdentifier.of("sales", "mart", "items"), jsonModel.definition().datasets()[0].source());
+ }
+
+ @Test
+ public void testExportJsonAndYamlRoundTrip() throws Exception {
+ SemanticModel semanticModel =
+ semanticModel(
+ definition(), Map.of("domain", "sales", PROPERTY_OSSIE_VERSION, "future-version"));
+
+ OssieDocument jsonDocument =
+ OssieDocumentConverter.exportDocument(semanticModel, OssieFormat.JSON);
+ assertEquals(OssieFormat.JSON, jsonDocument.format());
+ JsonNode json = JSON_MAPPER.readTree(jsonDocument.content());
+ assertEquals("future-version", json.path("version").textValue());
+ assertEquals("sales", json.path("name").textValue());
+ assertEquals("Governed sales definitions", json.path("description").textValue());
+ assertEquals("sales.mart.orders", json.at("/datasets/0/source").textValue());
+ assertEquals("order_id", json.at("/datasets/0/unique_keys/0/0").textValue());
+ assertTrue(json.at("/datasets/0/fields/0/dimension").isObject());
+ assertTrue(json.at("/datasets/0/fields/0/dimension").has("is_time"));
+ assertFalse(json.at("/datasets/0/fields/0/dimension/is_time").booleanValue());
+ assertEquals("Use order identifiers", json.at("/datasets/0/fields/0/ai_context").textValue());
+ assertEquals(
+ "FIELD_VENDOR",
+ json.at("/datasets/0/fields/0/custom_extensions/0/vendor_name").textValue());
+ assertFalse(json.has("semantic_model"));
+ assertFalse(json.has("definition"));
+ assertFalse(json.has("properties"));
+ assertFalse(json.has("audit"));
+ assertEquals(
+ GRAVITINO_PROPERTIES_VENDOR, json.at("/custom_extensions/1/vendor_name").textValue());
+ JsonNode properties = JSON_MAPPER.readTree(json.at("/custom_extensions/1/data").textValue());
+ assertEquals(JSON_MAPPER.readTree("{\"domain\":\"sales\"}"), properties);
+ assertFalse(properties.has(PROPERTY_OSSIE_VERSION));
+
+ ImportedSemanticModel jsonRoundTrip = OssieDocumentConverter.importDocument(jsonDocument);
+ assertEquals(semanticModel.name(), jsonRoundTrip.name());
+ assertEquals(semanticModel.comment(), jsonRoundTrip.comment());
+ assertEquals(semanticModel.definition(), jsonRoundTrip.definition());
+ assertEquals(semanticModel.properties(), jsonRoundTrip.properties());
+
+ OssieDocument yamlDocument =
+ OssieDocumentConverter.exportDocument(semanticModel, OssieFormat.YAML);
+ assertEquals(OssieFormat.YAML, yamlDocument.format());
+ assertTrue(yamlDocument.content().contains("version:"));
+ assertFalse(yamlDocument.content().contains("semantic_model:"));
+ ImportedSemanticModel yamlRoundTrip = OssieDocumentConverter.importDocument(yamlDocument);
+ assertEquals(semanticModel.definition(), yamlRoundTrip.definition());
+ assertEquals(semanticModel.properties(), yamlRoundTrip.properties());
+ }
+
+ @Test
+ public void testQuotedSourceRoundTrip() throws Exception {
+ NameIdentifier source = NameIdentifier.of("sales.eu", "ma`rt", "ord.ers");
+ Dataset dataset = Dataset.builder().withName("orders").withSource(source).build();
+ SemanticModelDefinition definition =
+ SemanticModelDefinition.builder().withDatasets(new Dataset[] {dataset}).build();
+
+ OssieDocument document =
+ OssieDocumentConverter.exportDocument(
+ semanticModel(definition, Map.of()), OssieFormat.JSON);
+ JsonNode json = JSON_MAPPER.readTree(document.content());
+ assertEquals("`sales.eu`.`ma``rt`.`ord.ers`", json.at("/datasets/0/source").textValue());
+
+ ImportedSemanticModel roundTrip = OssieDocumentConverter.importDocument(document);
+ assertEquals(source, roundTrip.definition().datasets()[0].source());
+ }
+
+ @Test
+ public void testExportDefaultsMissingOssieVersion() throws Exception {
+ SemanticModel semanticModel = semanticModel(definition(), Map.of());
+
+ OssieDocument document = OssieDocumentConverter.exportDocument(semanticModel, OssieFormat.JSON);
+ JsonNode json = JSON_MAPPER.readTree(document.content());
+
+ assertEquals(DEFAULT_VERSION, json.path("version").textValue());
+ ImportedSemanticModel roundTrip = OssieDocumentConverter.importDocument(document);
+ assertEquals(DEFAULT_VERSION, roundTrip.properties().get(PROPERTY_OSSIE_VERSION));
+ }
+
+ @Test
+ public void testRejectsMalformedAndUnsupportedDocuments() {
+ assertInvalid("[]", "root must be an object");
+ assertInvalid("name: sales\ndatasets: []\n", "$.version: must be a non-empty string");
+ assertInvalid("version: ' '\nname: sales\ndatasets: []\n", "must be a non-empty string");
+ assertInvalid("version: 0.2.0.dev0\nsemantic_model: []\n", "semantic_model");
+ assertInvalid(
+ "version: 0.2.0.dev0\nname: sales\ndescription: null\ndatasets: []\n",
+ "description: must not be null");
+ assertInvalid("version: 0.2.0.dev0\nname: sales\nunknown: true\ndatasets: []\n", "unknown");
+ assertInvalid(
+ "version: 0.2.0.dev0\n"
+ + "name: sales\n"
+ + "datasets:\n"
+ + " - name: orders\n"
+ + " source: SELECT * FROM orders\n",
+ "query sources are not supported");
+ assertInvalid(
+ "version: 0.2.0.dev0\n"
+ + "name: sales\n"
+ + "datasets:\n"
+ + " - name: orders\n"
+ + " source: '`sales.eu.mart.orders'\n",
+ "unterminated quoted segment");
+ assertInvalid(
+ "version: 0.2.0.dev0\n"
+ + "name: sales\n"
+ + "datasets:\n"
+ + " - name: orders\n"
+ + " source: 'sales.ma`rt.orders'\n",
+ "backticks must quote an entire segment");
+ assertInvalid(
+ "version: 0.2.0.dev0\n"
+ + "name: sales\n"
+ + "datasets:\n"
+ + " - name: orders\n"
+ + " source: sales.mart.orders\n"
+ + " fields:\n"
+ + " - name: id\n"
+ + " expression:\n"
+ + " dialects:\n"
+ + " - dialect: 123\n"
+ + " expression: id\n",
+ "dialect: must be a string");
+ assertInvalid(
+ "version: 0.2.0.dev0\n" + "name: first\n" + "name: second\n" + "datasets: []\n",
+ "Duplicate field 'name'");
+ assertInvalid(
+ "version: 0.2.0.dev0\nname: first\ndatasets: []\n"
+ + "---\nversion: 0.2.0.dev0\nname: second\ndatasets: []\n",
+ "Trailing token");
+ }
+
+ @Test
+ public void testRejectsIncorrectOssieTypes() {
+ assertInvalid("version: 0.2.0.dev0\nname: 123\ndatasets: []\n", "$.name: must be a string");
+ assertInvalid(
+ "version: 0.2.0.dev0\n"
+ + "name: sales\n"
+ + "datasets:\n"
+ + " - name: orders\n"
+ + " source: sales.mart.orders\n"
+ + " primary_key: [123]\n",
+ "$.datasets[0].primary_key[0]: must be a string");
+ assertInvalid(
+ "version: 0.2.0.dev0\n"
+ + "name: sales\n"
+ + "datasets:\n"
+ + " - name: orders\n"
+ + " source: sales.mart.orders\n"
+ + " fields:\n"
+ + " - name: id\n"
+ + " expression:\n"
+ + " dialects:\n"
+ + " - dialect: ANSI_SQL\n"
+ + " expression: id\n"
+ + " dimension:\n"
+ + " is_time: 'true'\n",
+ "$.datasets[0].fields[0].dimension.is_time: must be a boolean");
+ assertInvalid(
+ "version: 0.2.0.dev0\nname: sales\ndatasets: []\nmetrics: [123]\n",
+ "$.metrics[0]: must be an object");
+ }
+
+ /** Verifies that document errors retain their paths and native validation is still wrapped. */
+ @ParameterizedTest
+ @EnumSource(OssieFormat.class)
+ public void testPreservesValidationErrorMessages(OssieFormat format) throws Exception {
+ ObjectNode root = documentWithExtension("EXAMPLE", "{}");
+ root.putNull("description");
+ IllegalSemanticModelException rootError =
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () -> OssieDocumentConverter.importDocument(ossieDocument(root, format)));
+ assertEquals("$.description: must not be null", rootError.getMessage());
+ assertNull(rootError.getCause());
+
+ root.remove("description");
+ ObjectNode dataset = (ObjectNode) root.at("/datasets/0");
+ ObjectNode field =
+ dataset.putArray("fields").addObject().put("name", "id").put("datatype", 123);
+ field
+ .putObject("expression")
+ .putArray("dialects")
+ .addObject()
+ .put("dialect", "ANSI_SQL")
+ .put("expression", "id");
+ IllegalSemanticModelException nestedError =
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () -> OssieDocumentConverter.importDocument(ossieDocument(root, format)));
+ assertEquals("$.datasets[0].fields[0].datatype: must be a string", nestedError.getMessage());
+ assertNull(nestedError.getCause());
+
+ field.remove("datatype");
+ field.remove("expression");
+ IllegalSemanticModelException builderError =
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () -> OssieDocumentConverter.importDocument(ossieDocument(root, format)));
+ assertEquals(
+ "Cannot convert Apache Ossie document to a Gravitino Semantic Model: "
+ + "expression must not be null",
+ builderError.getMessage());
+ assertEquals(IllegalArgumentException.class, builderError.getCause().getClass());
+ }
+
+ @Test
+ public void testJsonFormatDoesNotFallBackToYaml() {
+ String yaml =
+ "version: 0.2.0.dev0\nname: sales\ndatasets:\n"
+ + " - name: orders\n source: sales.mart.orders\n";
+ assertEquals("sales", OssieDocumentConverter.importDocument(OssieDocument.yaml(yaml)).name());
+ assertInvalid(OssieDocument.json(yaml), "Cannot parse Apache Ossie JSON");
+ assertInvalid(
+ OssieDocument.json("{version: '0.2.0.dev0', name: sales, datasets: []}"),
+ "Cannot parse Apache Ossie JSON");
+ }
+
+ @Test
+ public void testRejectsMalformedJsonDocuments() {
+ assertInvalid(OssieDocument.json("[]"), "root must be an object");
+ assertInvalid(
+ OssieDocument.json("{\"name\":\"first\",\"name\":\"second\"}"), "Duplicate field 'name'");
+ assertInvalid(OssieDocument.json("{} {}"), "Trailing token");
+ assertInvalid(OssieDocument.json("{\"name\":}"), "Cannot parse Apache Ossie JSON");
+ }
+
+ @Test
+ public void testRejectsConflictingOssieVersionPropertyOnImport() {
+ String document =
+ """
+ version: root-version
+ name: sales
+ datasets:
+ - name: orders
+ source: sales.mart.orders
+ custom_extensions:
+ - vendor_name: GRAVITINO_PROPERTIES
+ data: '{"ossie-version":"extension-version"}'
+ """;
+
+ assertInvalid(document, "property 'ossie-version' conflicts with $.version");
+ }
+
+ @ParameterizedTest
+ @EnumSource(OssieFormat.class)
+ public void testRejectsInvalidPropertiesExtensionData(OssieFormat format) throws Exception {
+ String[] payloads = {
+ "",
+ "{",
+ "{} {}",
+ "{\"domain\":\"sales\",\"domain\":\"other\"}",
+ "null",
+ "[]",
+ "123",
+ "\"sales\""
+ };
+ for (String payload : payloads) {
+ assertInvalid(
+ ossieDocument(documentWithExtension(GRAVITINO_PROPERTIES_VENDOR, payload), format),
+ "$.custom_extensions[0].data");
+ }
+ for (String value : new String[] {"null", "true", "1", "[]", "{}"}) {
+ assertInvalid(
+ ossieDocument(
+ documentWithExtension(GRAVITINO_PROPERTIES_VENDOR, "{\"domain\":" + value + "}"),
+ format),
+ "Gravitino property 'domain' must be a string");
+ }
+ }
+
+ @Test
+ public void testValidatesPropertiesExtensionBeforeConsumingIt() throws Exception {
+ ObjectNode document = documentWithExtension(GRAVITINO_PROPERTIES_VENDOR, "{}");
+ ObjectNode extension = (ObjectNode) document.path("custom_extensions").get(0);
+ extension.put("extra", "not allowed");
+ assertInvalid(ossieDocument(document, OssieFormat.JSON), "$.custom_extensions[0].extra");
+ extension.remove("extra");
+ extension.put("data", 123);
+ assertInvalid(ossieDocument(document, OssieFormat.JSON), "$.custom_extensions[0].data");
+ extension.remove("data");
+ assertInvalid(ossieDocument(document, OssieFormat.JSON), "$.custom_extensions[0].data");
+ }
+
+ @ParameterizedTest
+ @EnumSource(OssieFormat.class)
+ public void testRejectsDuplicatePropertiesExtensions(OssieFormat format) throws Exception {
+ ObjectNode document = documentWithExtension(GRAVITINO_PROPERTIES_VENDOR, "{}");
+ document
+ .withArray("custom_extensions")
+ .add(document.path("custom_extensions").get(0).deepCopy());
+ assertInvalid(
+ ossieDocument(document, format), "contains multiple GRAVITINO_PROPERTIES extensions");
+ }
+
+ @ParameterizedTest
+ @EnumSource(OssieFormat.class)
+ public void testConsumesEmptyPropertiesExtension(OssieFormat format) throws Exception {
+ ImportedSemanticModel request =
+ OssieDocumentConverter.importDocument(
+ ossieDocument(documentWithExtension(GRAVITINO_PROPERTIES_VENDOR, "{}"), format));
+ assertEquals(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION), request.properties());
+ assertNull(request.definition().customExtensions());
+ }
+
+ @ParameterizedTest
+ @EnumSource(OssieFormat.class)
+ public void testPreservesOrdinaryGravitinoExtensions(OssieFormat format) throws Exception {
+ String[] payloads = {
+ "{\"_apache_gravitino_interchange\":1}",
+ "{\"_apache_gravitino_interchange\":{\"version\":1,\"properties\":{\"domain\":\"sales\"}}}",
+ "{\"domain\":\"sales\"}",
+ "{\"domain\":\"sales\",\"domain\":\"other\"}",
+ "{} {}",
+ "not JSON"
+ };
+ for (String payload : payloads) {
+ ImportedSemanticModel request =
+ OssieDocumentConverter.importDocument(
+ ossieDocument(documentWithExtension("GRAVITINO", payload), format));
+ assertEquals(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION), request.properties());
+ assertEquals(payload, request.definition().customExtensions()[0].data());
+
+ SemanticModel model =
+ semanticModel(
+ request.definition(),
+ Map.of("owner", "analytics", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION));
+ ImportedSemanticModel roundTrip =
+ OssieDocumentConverter.importDocument(
+ OssieDocumentConverter.exportDocument(model, format));
+ assertEquals(model.definition(), roundTrip.definition());
+ assertEquals(model.properties(), roundTrip.properties());
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(OssieFormat.class)
+ public void testPreservesNestedPropertiesVendorExtension(OssieFormat format) throws Exception {
+ CustomExtension nested =
+ CustomExtension.builder()
+ .withVendorName(GRAVITINO_PROPERTIES_VENDOR)
+ .withData("{\"nested\":true}")
+ .build();
+ Dataset dataset =
+ Dataset.builder()
+ .withName("orders")
+ .withSource(NameIdentifier.of("sales", "mart", "orders"))
+ .withCustomExtensions(new CustomExtension[] {nested})
+ .build();
+ SemanticModel model =
+ semanticModel(
+ SemanticModelDefinition.builder().withDatasets(new Dataset[] {dataset}).build(),
+ Map.of("owner", "analytics", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION));
+
+ ImportedSemanticModel roundTrip =
+ OssieDocumentConverter.importDocument(OssieDocumentConverter.exportDocument(model, format));
+ assertEquals(model.definition(), roundTrip.definition());
+ assertEquals(model.properties(), roundTrip.properties());
+ }
+
+ @Test
+ public void testDoesNotExportPropertiesExtensionForVersionOnly() throws Exception {
+ SemanticModel model =
+ semanticModel(definition(), Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION));
+ JsonNode document =
+ JSON_MAPPER.readTree(
+ OssieDocumentConverter.exportDocument(model, OssieFormat.JSON).content());
+ assertEquals(1, document.path("custom_extensions").size());
+ assertEquals("EXAMPLE", document.at("/custom_extensions/0/vendor_name").textValue());
+ }
+
+ @Test
+ public void testRejectsBlankOssieVersionPropertyOnExport() {
+ IllegalSemanticModelException exception =
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () ->
+ OssieDocumentConverter.exportDocument(
+ semanticModel(definition(), Map.of(PROPERTY_OSSIE_VERSION, " ")),
+ OssieFormat.JSON));
+
+ assertTrue(exception.getMessage().contains("property 'ossie-version' must not be blank"));
+ }
+
+ @Test
+ public void testRejectsReservedExtensionCollisionOnExport() {
+ CustomExtension reserved =
+ CustomExtension.builder()
+ .withVendorName(GRAVITINO_PROPERTIES_VENDOR)
+ .withData("{}")
+ .build();
+ SemanticModelDefinition definition =
+ SemanticModelDefinition.builder()
+ .withDatasets(new Dataset[] {dataset()})
+ .withCustomExtensions(new CustomExtension[] {reserved})
+ .build();
+
+ IllegalSemanticModelException exception =
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () ->
+ OssieDocumentConverter.exportDocument(
+ semanticModel(definition, Map.of()), OssieFormat.JSON));
+ assertTrue(exception.getMessage().contains("reserved for Gravitino properties"));
+ }
+
+ @Test
+ public void testPreservesCustomDialectOnImportAndExport() throws Exception {
+ Metric metric =
+ Metric.builder()
+ .withName("revenue")
+ .withExpression(expression("TRINO", "SUM(orders.amount)"))
+ .build();
+ SemanticModelDefinition definition =
+ SemanticModelDefinition.builder()
+ .withDatasets(new Dataset[] {dataset()})
+ .withMetrics(new Metric[] {metric})
+ .build();
+
+ OssieDocument document =
+ OssieDocumentConverter.exportDocument(
+ semanticModel(definition, Map.of()), OssieFormat.JSON);
+ JsonNode json = JSON_MAPPER.readTree(document.content());
+ assertEquals(
+ "TRINO",
+ json.path("metrics")
+ .get(0)
+ .path("expression")
+ .path("dialects")
+ .get(0)
+ .path("dialect")
+ .textValue());
+
+ ImportedSemanticModel roundTrip = OssieDocumentConverter.importDocument(document);
+ assertEquals("TRINO", roundTrip.definition().metrics()[0].expression().dialects()[0].dialect());
+ }
+
+ @ParameterizedTest
+ @EnumSource(OssieFormat.class)
+ public void testAllDataTypesRoundTripWithoutDTOs(OssieFormat format) throws Exception {
+ String[] names = {
+ "String",
+ "Integer",
+ "Decimal",
+ "Float",
+ "Boolean",
+ "Date",
+ "Time",
+ "DateTime",
+ "DateTimeTz",
+ "Opaque"
+ };
+ DataType[] types = DataType.values();
+ assertEquals(names.length, types.length);
+ Field[] fields = new Field[types.length];
+ Metric[] metrics = new Metric[types.length];
+ for (int index = 0; index < types.length; index++) {
+ fields[index] =
+ Field.builder()
+ .withName("field_" + index)
+ .withExpression(expression("value"))
+ .withDatatype(types[index])
+ .withDimension(Dimension.builder().build())
+ .build();
+ metrics[index] =
+ Metric.builder()
+ .withName("metric_" + index)
+ .withExpression(expression("value"))
+ .withDatatype(types[index])
+ .build();
+ }
+ Dataset dataset =
+ Dataset.builder()
+ .withName("orders")
+ .withSource(NameIdentifier.of("sales", "mart", "orders"))
+ .withFields(fields)
+ .build();
+ SemanticModelDefinition definition =
+ SemanticModelDefinition.builder()
+ .withDatasets(new Dataset[] {dataset})
+ .withMetrics(metrics)
+ .build();
+
+ OssieDocument document =
+ OssieDocumentConverter.exportDocument(semanticModel(definition, Map.of()), format);
+ JsonNode root =
+ (format == OssieFormat.JSON ? JSON_MAPPER : YAML_MAPPER).readTree(document.content());
+ for (int index = 0; index < names.length; index++) {
+ assertEquals(names[index], root.at("/datasets/0/fields/" + index + "/datatype").textValue());
+ assertEquals(names[index], root.at("/metrics/" + index + "/datatype").textValue());
+ assertEquals(0, root.at("/datasets/0/fields/" + index + "/dimension").size());
+ }
+ assertEquals(definition, OssieDocumentConverter.importDocument(document).definition());
+ }
+
+ @ParameterizedTest
+ @EnumSource(OssieFormat.class)
+ public void testStructuredAIContextRoundTripWithoutDTOs(OssieFormat format) throws Exception {
+ String content =
+ """
+ {
+ "version": "0.2.0.dev0",
+ "name": "sales",
+ "ai_context": {
+ "instructions": "Use certified definitions",
+ "synonyms": ["sales", "revenue"],
+ "examples": [],
+ "fraction": 0.12345678901234567890123456789,
+ "count": 123456789012345678901234567890,
+ "nested": {"missing": null, "values": [1, 2.5, null, "label", false]}
+ },
+ "datasets": [{"name": "orders", "source": "sales.mart.orders"}]
+ }
+ """;
+ OssieDocument input =
+ format == OssieFormat.JSON ? OssieDocument.json(content) : OssieDocument.yaml(content);
+ ImportedSemanticModel imported = OssieDocumentConverter.importDocument(input);
+ AIContextObject context = imported.definition().aiContext().object();
+ assertEquals("Use certified definitions", context.instructions());
+ assertEquals(2, context.synonyms().length);
+ assertEquals(0, context.examples().length);
+ assertEquals(
+ new BigDecimal("0.12345678901234567890123456789"),
+ context.additionalProperties().get("fraction"));
+ assertEquals(
+ new BigInteger("123456789012345678901234567890"),
+ context.additionalProperties().get("count"));
+
+ OssieDocument exported =
+ OssieDocumentConverter.exportDocument(
+ semanticModel(imported.definition(), imported.properties()), format);
+ JsonNode root =
+ (format == OssieFormat.JSON ? JSON_MAPPER : YAML_MAPPER).readTree(exported.content());
+ assertTrue(root.at("/ai_context/nested/missing").isNull());
+ assertTrue(root.at("/ai_context/nested/values/2").isNull());
+ assertEquals(
+ imported.definition(), OssieDocumentConverter.importDocument(exported).definition());
+ }
+
+ @ParameterizedTest
+ @EnumSource(OssieFormat.class)
+ public void testPreservesAbsentAndEmptyOptionalValues(OssieFormat format) throws Exception {
+ ObjectNode root = documentWithExtension("EXAMPLE", "{}");
+ ObjectNode dataset = (ObjectNode) root.at("/datasets/0");
+ dataset.putArray("primary_key");
+ dataset.putArray("unique_keys");
+ dataset.putArray("fields");
+ dataset.putObject("ai_context");
+ dataset.putArray("custom_extensions");
+ root.putArray("relationships");
+ root.putArray("metrics");
+
+ ImportedSemanticModel imported =
+ OssieDocumentConverter.importDocument(ossieDocument(root, format));
+ Dataset converted = imported.definition().datasets()[0];
+ assertNull(imported.comment());
+ assertNull(imported.definition().aiContext());
+ assertNull(converted.description());
+ assertEquals(0, converted.primaryKey().length);
+ assertEquals(0, converted.uniqueKeys().length);
+ assertEquals(0, converted.fields().length);
+ assertNull(converted.aiContext().object().instructions());
+ assertNull(converted.aiContext().object().synonyms());
+ assertNull(converted.aiContext().object().examples());
+ assertEquals(0, converted.customExtensions().length);
+ assertEquals(0, imported.definition().relationships().length);
+ assertEquals(0, imported.definition().metrics().length);
+ assertThrows(
+ UnsupportedOperationException.class, () -> imported.properties().put("key", "value"));
+
+ OssieDocument exported =
+ OssieDocumentConverter.exportDocument(
+ semanticModel(imported.definition(), imported.properties()), format);
+ assertEquals(
+ imported.definition(), OssieDocumentConverter.importDocument(exported).definition());
+ }
+
+ @ParameterizedTest
+ @EnumSource(OssieFormat.class)
+ public void testRetainsNativeValidationWithoutDTOs(OssieFormat format) throws Exception {
+ ObjectNode root = documentWithExtension("EXAMPLE", "{}");
+ root.remove("name");
+ assertInvalid(ossieDocument(root, format), "name");
+ root.put("name", " ");
+ assertInvalid(ossieDocument(root, format), "name");
+ root.put("name", "sales");
+ ObjectNode dataset = (ObjectNode) root.at("/datasets/0");
+ dataset.remove("source");
+ assertInvalid(ossieDocument(root, format), "source must not be null");
+ dataset.put("source", "sales.mart.orders");
+ dataset.putArray("unique_keys").addArray();
+ assertInvalid(ossieDocument(root, format), "uniqueKeys[0] must not be null or empty");
+ dataset.remove("unique_keys");
+
+ ObjectNode field = dataset.putArray("fields").addObject().put("name", "id");
+ assertInvalid(ossieDocument(root, format), "expression must not be null");
+ ObjectNode expression = field.putObject("expression");
+ expression.putArray("dialects");
+ assertInvalid(ossieDocument(root, format), "dialects must not be null or empty");
+ expression.withArray("dialects").addObject().put("dialect", "ANSI_SQL");
+ assertInvalid(ossieDocument(root, format), "expression must not be null or empty");
+ ((ObjectNode) expression.at("/dialects/0")).put("expression", "id");
+ expression.withArray("dialects").add(expression.at("/dialects/0").deepCopy());
+ assertInvalid(ossieDocument(root, format), "duplicate dialect");
+ expression.withArray("dialects").remove(1);
+ for (String type : new String[] {"string", "DATE_TIME", "", "Unknown"}) {
+ field.put("datatype", type);
+ assertInvalid(ossieDocument(root, format), "Unknown Semantic Model data type");
+ }
+ field.put("datatype", 123);
+ assertInvalid(ossieDocument(root, format), "datatype: must be a string");
+ field.remove("datatype");
+
+ ObjectNode relationship = root.putArray("relationships").addObject();
+ relationship.put("name", "join").put("from", "orders").put("to", "orders");
+ relationship.putArray("from_columns").add("id");
+ relationship.putArray("to_columns").add("id").add("other");
+ assertInvalid(ossieDocument(root, format), "must have the same length");
+ root.remove("relationships");
+ ObjectNode extension = (ObjectNode) root.at("/custom_extensions/0");
+ extension.remove("data");
+ assertInvalid(ossieDocument(root, format), "data must not be null");
+ extension.put("data", "{}");
+ root.putObject("ai_context").putArray("synonyms").addNull();
+ assertInvalid(ossieDocument(root, format), "synonyms[0]: must be a string");
+ }
+
+ private static ObjectNode documentWithExtension(String vendorName, String payload) {
+ ObjectNode root = JSON_MAPPER.createObjectNode();
+ root.put("version", DEFAULT_VERSION);
+ root.put("name", "sales");
+ ObjectNode dataset = root.putArray("datasets").addObject();
+ dataset.put("name", "orders");
+ dataset.put("source", "sales.mart.orders");
+ ObjectNode extension = root.putArray("custom_extensions").addObject();
+ extension.put("vendor_name", vendorName);
+ extension.put("data", payload);
+ return root;
+ }
+
+ private static OssieDocument ossieDocument(ObjectNode root, OssieFormat format) throws Exception {
+ String content = JSON_MAPPER.writeValueAsString(root);
+ return format == OssieFormat.JSON ? OssieDocument.json(content) : OssieDocument.yaml(content);
+ }
+
+ private static SemanticModel semanticModel(
+ SemanticModelDefinition definition, Map<String, String> properties) {
+ return SemanticModelEntity.builder()
+ .withId(1L)
+ .withName("sales")
+ .withNamespace(Namespace.of("lake", "sales", "mart"))
+ .withComment("Governed sales definitions")
+ .withDefinition(definition)
+ .withProperties(properties)
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator("tester")
+ .withCreateTime(Instant.parse("2026-09-28T00:00:00Z"))
+ .build())
+ .build();
+ }
+
+ private static SemanticModelDefinition definition() {
+ Dataset orders = dataset();
+ Dataset customers =
+ Dataset.builder()
+ .withName("customers")
+ .withSource(NameIdentifier.of("sales", "mart", "customers"))
+ .build();
+ Relationship relationship =
+ Relationship.builder()
+ .withName("orders_to_customers")
+ .withFrom("orders")
+ .withTo("customers")
+ .withFromColumns(new String[] {"customer_id"})
+ .withToColumns(new String[] {"customer_id"})
+ .withAIContext(AIContext.of("Join orders to customers"))
+ .withCustomExtensions(new CustomExtension[] {extension("RELATIONSHIP_VENDOR")})
+ .build();
+ Metric metric =
+ Metric.builder()
+ .withName("revenue")
+ .withExpression(expression("SUM(orders.amount)"))
+ .withDescription("Recognized revenue")
+ .withDatatype(DataType.DECIMAL)
+ .withAIContext(AIContext.of("Use the certified revenue metric"))
+ .withCustomExtensions(new CustomExtension[] {extension("METRIC_VENDOR")})
+ .build();
+ return SemanticModelDefinition.builder()
+ .withAIContext(AIContext.of("Use certified definitions"))
+ .withDatasets(new Dataset[] {orders, customers})
+ .withRelationships(new Relationship[] {relationship})
+ .withMetrics(new Metric[] {metric})
+ .withCustomExtensions(new CustomExtension[] {extension("EXAMPLE")})
+ .build();
+ }
+
+ private static Dataset dataset() {
+ Field field =
+ Field.builder()
+ .withName("order_id")
+ .withExpression(expression("order_id"))
+ .withDimension(Dimension.builder().withIsTime(false).build())
+ .withLabel("Order ID")
+ .withDescription("Unique order identifier")
+ .withDatatype(DataType.STRING)
+ .withAIContext(AIContext.of("Use order identifiers"))
+ .withCustomExtensions(new CustomExtension[] {extension("FIELD_VENDOR")})
+ .build();
+ return Dataset.builder()
+ .withName("orders")
+ .withSource(NameIdentifier.of("sales", "mart", "orders"))
+ .withPrimaryKey(new String[] {"order_id"})
+ .withUniqueKeys(new String[][] {{"order_id"}})
+ .withDescription("Orders dataset")
+ .withAIContext(AIContext.of("Use certified orders"))
+ .withFields(new Field[] {field})
+ .withCustomExtensions(new CustomExtension[] {extension("DATASET_VENDOR")})
+ .build();
+ }
+
+ private static CustomExtension extension(String vendorName) {
+ return CustomExtension.builder()
+ .withVendorName(vendorName)
+ .withData("{\"certified\":true}")
+ .build();
+ }
+
+ private static Expression expression(String value) {
+ return expression(Dialects.ANSI_SQL, value);
+ }
+
+ private static Expression expression(String dialectName, String value) {
+ DialectExpression dialect =
+ DialectExpression.builder().withDialect(dialectName).withExpression(value).build();
+ return Expression.builder().withDialects(new DialectExpression[] {dialect}).build();
+ }
+
+ private static void assertInvalid(String document, String expectedMessage) {
+ assertInvalid(OssieDocument.yaml(document), expectedMessage);
+ }
+
+ private static void assertInvalid(OssieDocument document, String expectedMessage) {
+ IllegalSemanticModelException exception =
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () -> OssieDocumentConverter.importDocument(document));
+ assertTrue(
+ exception.getMessage().contains(expectedMessage),
+ () -> "Expected '" + expectedMessage + "' in: " + exception.getMessage());
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/semantic/TestSemanticModelPropertiesMetadata.java b/core/src/test/java/org/apache/gravitino/semantic/TestSemanticModelPropertiesMetadata.java
new file mode 100644
index 0000000000..39884d3bec
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/semantic/TestSemanticModelPropertiesMetadata.java
@@ -0,0 +1,46 @@
+/*
+ * 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.semantic;
+
+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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.apache.gravitino.connector.PropertyEntry;
+import org.junit.jupiter.api.Test;
+
+/** Tests the property metadata shared by Semantic Models. */
+public class TestSemanticModelPropertiesMetadata {
+
+ private static final SemanticModelPropertiesMetadata METADATA =
+ new SemanticModelPropertiesMetadata();
+
+ @Test
+ public void testOssieVersionProperty() {
+ PropertyEntry<?> entry = METADATA.getPropertyEntry(PROPERTY_OSSIE_VERSION);
+
+ assertFalse(entry.isRequired());
+ assertFalse(entry.isImmutable());
+ assertEquals(DEFAULT_VERSION, entry.getDefaultValue());
+ assertEquals("future-version", entry.decode("future-version"));
+ assertThrows(IllegalArgumentException.class, () -> entry.decode(" "));
+ }
+}
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java
index ab68d05ff0..657350edbd 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java
@@ -21,16 +21,22 @@ package org.apache.gravitino.server.web.rest;
import com.codahale.metrics.annotation.ResponseMetered;
import com.codahale.metrics.annotation.Timed;
import java.util.Collections;
+import java.util.Locale;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
@@ -43,6 +49,8 @@ import org.apache.gravitino.dto.responses.EntityListResponse;
import org.apache.gravitino.dto.responses.SemanticModelResponse;
import org.apache.gravitino.dto.util.DTOConverters;
import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.semantic.OssieDocument;
+import org.apache.gravitino.semantic.OssieFormat;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
@@ -57,6 +65,10 @@ import org.slf4j.LoggerFactory;
public class SemanticModelOperations {
private static final Logger LOG = LoggerFactory.getLogger(SemanticModelOperations.class);
+ private static final String VND_GRAVITINO_V1_JSON = "application/vnd.gravitino.v1+json";
+ private static final String OSSIE_YAML_MEDIA_TYPE = "application/yaml";
+ private static final String OSSIE_X_YAML_MEDIA_TYPE = "application/x-yaml";
+ private static final String OSSIE_TEXT_YAML_MEDIA_TYPE = "text/yaml";
private final SemanticModelDispatcher dispatcher;
@@ -119,7 +131,7 @@ public class SemanticModelOperations {
* @return A response containing the created Semantic Model.
*/
@POST
- @Produces("application/vnd.gravitino.v1+json")
+ @Produces(VND_GRAVITINO_V1_JSON)
@Timed(name = "create-semantic-model." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
@ResponseMetered(name = "create-semantic-model", absolute = true)
public Response createSemanticModel(
@@ -137,18 +149,8 @@ public class SemanticModelOperations {
if (request == null) {
throw new IllegalArgumentException("Request body must not be null");
}
- request.validate();
- SemanticModelDefinition definition = request.toDefinition();
- NameIdentifier ident =
- NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, request.getName());
SemanticModel semanticModel =
- dispatcher.createSemanticModel(
- ident,
- request.getComment(),
- definition,
- request.getProperties() == null
- ? Collections.emptyMap()
- : request.getProperties());
+ createSemanticModelEntity(metalake, catalog, schema, request);
LOG.info(
"Semantic Model created: {}.{}.{}.{}",
metalake,
@@ -162,6 +164,67 @@ public class SemanticModelOperations {
}
}
+ /**
+ * Imports a standalone Apache Ossie YAML or JSON document as a Semantic Model.
+ *
+ * <p>The request body is raw document text, not a JSON-encoded string. The {@code Content-Type}
+ * header selects the document format; an absent header defaults to YAML. Parsing does not fall
+ * back to another format if the document is invalid for the selected parser.
+ *
+ * @param metalake The metalake name.
+ * @param catalog The catalog name.
+ * @param schema The schema name.
+ * @param document The standalone Ossie document.
+ * @param headers The request headers specifying the document's media type.
+ * @return A native response containing the created Semantic Model.
+ */
+ @POST
+ @Path("ossie")
+ @Consumes({
+ MediaType.APPLICATION_JSON,
+ OSSIE_YAML_MEDIA_TYPE,
+ OSSIE_X_YAML_MEDIA_TYPE,
+ OSSIE_TEXT_YAML_MEDIA_TYPE
+ })
+ @Produces(VND_GRAVITINO_V1_JSON)
+ @Timed(name = "import-ossie-semantic-model." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "import-ossie-semantic-model", absolute = true)
+ public Response importOssieDocument(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema,
+ String document,
+ @Context HttpHeaders headers) {
+ LOG.info(
+ "Received import Apache Ossie Semantic Model request for schema: {}.{}.{}",
+ metalake,
+ catalog,
+ schema);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ OssieDocument ossieDocument =
+ MediaType.APPLICATION_JSON_TYPE.isCompatible(headers.getMediaType())
+ ? OssieDocument.json(document)
+ : OssieDocument.yaml(document);
+ SemanticModel semanticModel =
+ dispatcher.importOssieDocument(
+ NamespaceUtil.ofSemanticModel(metalake, catalog, schema), ossieDocument);
+ LOG.info(
+ "Apache Ossie Semantic Model imported: {}.{}.{}.{}",
+ metalake,
+ catalog,
+ schema,
+ semanticModel.name());
+ return Utils.ok(new SemanticModelResponse(DTOConverters.toDTO(semanticModel)));
+ });
+ } catch (Exception e) {
+ return ExceptionHandlers.handleSemanticModelException(
+ OperationType.CREATE, "Apache Ossie document", schema, e);
+ }
+ }
+
/**
* Loads a Semantic Model.
*
@@ -173,7 +236,7 @@ public class SemanticModelOperations {
*/
@GET
@Path("{semanticModel}")
- @Produces("application/vnd.gravitino.v1+json")
+ @Produces(VND_GRAVITINO_V1_JSON)
@Timed(name = "load-semantic-model." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
@ResponseMetered(name = "load-semantic-model", absolute = true)
public Response loadSemanticModel(
@@ -302,4 +365,86 @@ public class SemanticModelOperations {
OperationType.DROP, semanticModel, schema, e);
}
}
+
+ /**
+ * Exports a Semantic Model as a standalone Apache Ossie YAML or JSON document.
+ *
+ * @param metalake The metalake name.
+ * @param catalog The catalog name.
+ * @param schema The schema name.
+ * @param semanticModel The Semantic Model name.
+ * @param format The output format, either {@code yaml} or {@code json}.
+ * @return A response containing the serialized Ossie document.
+ */
+ @GET
+ @Path("{semanticModel}/ossie")
+ @Timed(name = "export-ossie-semantic-model." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "export-ossie-semantic-model", absolute = true)
+ public Response exportOssieDocument(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema,
+ @PathParam("semanticModel") String semanticModel,
+ @DefaultValue("yaml") @QueryParam("format") String format) {
+ LOG.info(
+ "Received export Semantic Model as Apache Ossie request: {}.{}.{}.{}, format: {}",
+ metalake,
+ catalog,
+ schema,
+ semanticModel,
+ format);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ OssieFormat outputFormat = parseOssieFormat(format);
+ NameIdentifier ident =
+ NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, semanticModel);
+ OssieDocument document = dispatcher.exportOssieDocument(ident, outputFormat);
+ String mediaType =
+ document.format() == OssieFormat.JSON
+ ? MediaType.APPLICATION_JSON
+ : OSSIE_YAML_MEDIA_TYPE;
+ return Response.ok(document.content(), mediaType)
+ .header(
+ "Content-Disposition",
+ ossieContentDisposition(semanticModel, document.format()))
+ .build();
+ });
+ } catch (Exception e) {
+ return ExceptionHandlers.handleSemanticModelException(
+ OperationType.LOAD, semanticModel, schema, e);
+ }
+ }
+
+ private SemanticModel createSemanticModelEntity(
+ String metalake, String catalog, String schema, SemanticModelCreateRequest request) {
+ request.validate();
+ SemanticModelDefinition definition = request.toDefinition();
+ NameIdentifier ident =
+ NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, request.getName());
+ return dispatcher.createSemanticModel(
+ ident,
+ request.getComment(),
+ definition,
+ request.getProperties() == null ? Collections.emptyMap() : request.getProperties());
+ }
+
+ private static OssieFormat parseOssieFormat(String format) {
+ if (format == null) {
+ throw new IllegalArgumentException("Ossie format must be yaml or json");
+ }
+ try {
+ return OssieFormat.valueOf(format.toUpperCase(Locale.ROOT));
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(
+ String.format("Unsupported Ossie format '%s'; expected yaml or json", format), e);
+ }
+ }
+
+ private static String ossieContentDisposition(String semanticModel, OssieFormat format) {
+ String safeName = semanticModel.replaceAll("[^A-Za-z0-9._-]", "_");
+ String extension = format.name().toLowerCase(Locale.ROOT);
+ return String.format("attachment; filename=\"%s.ossie.%s\"", safeName, extension);
+ }
}
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
index 1246f5c173..0b4e117641 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
@@ -18,15 +18,21 @@
*/
package org.apache.gravitino.server.web.rest;
+import static org.apache.gravitino.semantic.OssieVersion.DEFAULT_VERSION;
+import static org.apache.gravitino.semantic.SemanticModel.PROPERTY_OSSIE_VERSION;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.json.JsonMapper;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
@@ -69,6 +75,8 @@ import org.apache.gravitino.semantic.Dialects;
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.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
@@ -80,12 +88,15 @@ import org.glassfish.jersey.test.TestProperties;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
/** Tests Semantic Model REST lifecycle operations and their error mappings. */
public class TestSemanticModelOperations extends BaseOperationsTest {
private static final String VND_V1_JSON = "application/vnd.gravitino.v1+json";
+ private static final JsonMapper JSON_MAPPER = JsonMapper.builder().build();
private static class MockServletRequestFactory extends ServletRequestFactoryBase {
@Override
@@ -126,6 +137,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
@BeforeEach
void resetDispatcher() {
reset(dispatcher);
+ doCallRealMethod().when(dispatcher).importOssieDocument(any(), any());
+ doCallRealMethod().when(dispatcher).exportOssieDocument(any(), any());
}
@Test
@@ -530,6 +543,273 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
"sales changed in this transaction");
}
+ @ParameterizedTest
+ @ValueSource(strings = {"application/json", "application/json; charset=UTF-8"})
+ void testImportOssieYamlAndJsonDocuments(String jsonMediaType) {
+ NameIdentifier salesIdent = semanticModelIdentifier("sales");
+ NameIdentifier inventoryIdent = semanticModelIdentifier("inventory");
+ when(dispatcher.createSemanticModel(
+ eq(salesIdent),
+ eq("Sales definitions"),
+ any(SemanticModelDefinition.class),
+ eq(Map.of("domain", "sales", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION))))
+ .thenReturn(semanticModel("sales", "Sales definitions"));
+ when(dispatcher.createSemanticModel(
+ eq(inventoryIdent),
+ eq(null),
+ any(SemanticModelDefinition.class),
+ eq(Map.of(PROPERTY_OSSIE_VERSION, "future-version"))))
+ .thenReturn(semanticModel("inventory", null));
+
+ String yaml =
+ """
+ version: 0.2.0.dev0
+ name: sales
+ description: Sales definitions
+ datasets:
+ - name: orders
+ source: semantic_model_catalog.semantic_model_schema.orders
+ primary_key: [order_id]
+ fields:
+ - name: order_id
+ expression:
+ dialects:
+ - dialect: ANSI_SQL
+ expression: orders.order_id
+ datatype: String
+ custom_extensions:
+ - vendor_name: GRAVITINO_PROPERTIES
+ data: '{"domain":"sales"}'
+ """;
+ Response yamlResponse = postDocument(semanticModelPath() + "/ossie", yaml, "application/yaml");
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), yamlResponse.getStatus());
+ SemanticModelResponse yamlBody = yamlResponse.readEntity(SemanticModelResponse.class);
+ yamlBody.validate();
+ Assertions.assertEquals("sales", yamlBody.getSemanticModel().name());
+
+ String json =
+ """
+ {
+ "version": "future-version",
+ "name": "inventory",
+ "datasets": [
+ {
+ "name": "orders",
+ "source": "semantic_model_catalog.semantic_model_schema.orders",
+ "fields": []
+ }
+ ]
+ }
+ """;
+ Response jsonResponse = postDocument(semanticModelPath() + "/ossie", json, jsonMediaType);
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), jsonResponse.getStatus());
+ SemanticModelResponse jsonBody = jsonResponse.readEntity(SemanticModelResponse.class);
+ jsonBody.validate();
+ Assertions.assertEquals("inventory", jsonBody.getSemanticModel().name());
+
+ verify(dispatcher).importOssieDocument(namespace, OssieDocument.yaml(yaml));
+ verify(dispatcher).importOssieDocument(namespace, OssieDocument.json(json));
+ ArgumentCaptor<SemanticModelDefinition> definitionCaptor =
+ ArgumentCaptor.forClass(SemanticModelDefinition.class);
+ verify(dispatcher)
+ .createSemanticModel(
+ eq(salesIdent),
+ eq("Sales definitions"),
+ definitionCaptor.capture(),
+ eq(Map.of("domain", "sales", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION)));
+ Assertions.assertEquals(
+ NameIdentifier.of(catalog, schema, "orders"),
+ definitionCaptor.getValue().datasets()[0].source());
+ Assertions.assertEquals(
+ Dialects.ANSI_SQL,
+ definitionCaptor.getValue().datasets()[0].fields()[0].expression().dialects()[0].dialect());
+ verify(dispatcher)
+ .createSemanticModel(
+ eq(inventoryIdent),
+ eq(null),
+ any(SemanticModelDefinition.class),
+ eq(Map.of(PROPERTY_OSSIE_VERSION, "future-version")));
+ verifyNoMoreInteractions(dispatcher);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"text/yaml", "application/x-yaml"})
+ void testImportOssieYamlMediaTypeAliases(String mediaType) {
+ NameIdentifier ident = semanticModelIdentifier("marketing");
+ when(dispatcher.createSemanticModel(
+ eq(ident),
+ eq(null),
+ any(SemanticModelDefinition.class),
+ eq(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION))))
+ .thenReturn(semanticModel("marketing", null));
+
+ String yaml =
+ """
+ version: 0.2.0.dev0
+ name: marketing
+ datasets:
+ - name: campaigns
+ source: semantic_model_catalog.semantic_model_schema.campaigns
+ fields: []
+ """;
+ Response response = postDocument(semanticModelPath() + "/ossie", yaml, mediaType);
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ SemanticModelResponse body = response.readEntity(SemanticModelResponse.class);
+ body.validate();
+ Assertions.assertEquals("marketing", body.getSemanticModel().name());
+ verify(dispatcher).importOssieDocument(namespace, OssieDocument.yaml(yaml));
+ verify(dispatcher)
+ .createSemanticModel(
+ eq(ident),
+ eq(null),
+ any(SemanticModelDefinition.class),
+ eq(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION)));
+ verifyNoMoreInteractions(dispatcher);
+ }
+
+ @Test
+ void testExportOssieYamlAndJsonDocuments() throws Exception {
+ NameIdentifier ident = semanticModelIdentifier("sales");
+ when(dispatcher.loadSemanticModel(ident))
+ .thenReturn(semanticModel("sales", "Sales definitions"));
+
+ Response yamlResponse = getOssie(semanticModelPath() + "/sales/ossie");
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), yamlResponse.getStatus());
+ Assertions.assertEquals("application/yaml", yamlResponse.getMediaType().toString());
+ Assertions.assertEquals(
+ "attachment; filename=\"sales.ossie.yaml\"",
+ yamlResponse.getHeaderString("Content-Disposition"));
+ String yaml = yamlResponse.readEntity(String.class);
+ Assertions.assertTrue(yaml.contains("version:"));
+ Assertions.assertTrue(yaml.contains("name:"));
+ Assertions.assertFalse(yaml.contains("semantic_model:"));
+ Assertions.assertFalse(yaml.contains("definition:"));
+
+ Response jsonResponse =
+ target(semanticModelPath() + "/sales/ossie")
+ .queryParam("format", "json")
+ .request("application/yaml")
+ .get();
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), jsonResponse.getStatus());
+ Assertions.assertEquals(MediaType.APPLICATION_JSON, jsonResponse.getMediaType().toString());
+ Assertions.assertEquals(
+ "attachment; filename=\"sales.ossie.json\"",
+ jsonResponse.getHeaderString("Content-Disposition"));
+ JsonNode json = JSON_MAPPER.readTree(jsonResponse.readEntity(String.class));
+ Assertions.assertEquals("0.2.0.dev0", json.path("version").textValue());
+ Assertions.assertEquals("sales", json.path("name").textValue());
+ Assertions.assertEquals(
+ "semantic_model_catalog.semantic_model_schema.orders",
+ json.at("/datasets/0/source").textValue());
+ Assertions.assertFalse(json.has("semantic_model"));
+ Assertions.assertFalse(json.has("definition"));
+ verify(dispatcher).exportOssieDocument(ident, OssieFormat.YAML);
+ verify(dispatcher).exportOssieDocument(ident, OssieFormat.JSON);
+ verify(dispatcher, times(2)).loadSemanticModel(ident);
+ verifyNoMoreInteractions(dispatcher);
+ }
+
+ @Test
+ void testOssieConversionErrorsDoNotCallNativeOperations() {
+ String querySource =
+ """
+ version: 0.2.0.dev0
+ name: sales
+ datasets:
+ - name: orders
+ source: SELECT * FROM orders
+ """;
+ assertError(
+ postDocument(semanticModelPath() + "/ossie", querySource, "application/x-yaml"),
+ Response.Status.BAD_REQUEST,
+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE,
+ IllegalSemanticModelException.class.getSimpleName(),
+ "query sources are not supported");
+ verify(dispatcher).importOssieDocument(namespace, OssieDocument.yaml(querySource));
+
+ assertError(
+ target(semanticModelPath() + "/sales/ossie").queryParam("format", "csv").request().get(),
+ Response.Status.BAD_REQUEST,
+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE,
+ IllegalArgumentException.class.getSimpleName(),
+ "expected yaml or json");
+ verifyNoMoreInteractions(dispatcher);
+ }
+
+ @Test
+ void testOssieImportRejectsBlankContentBeforeDispatch() {
+ for (String mediaType : new String[] {"application/yaml", MediaType.APPLICATION_JSON}) {
+ for (String content : new String[] {"", " \t\r\n"}) {
+ try (Response response = postDocument(semanticModelPath() + "/ossie", content, mediaType)) {
+ assertError(
+ response,
+ Response.Status.BAD_REQUEST,
+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE,
+ IllegalArgumentException.class.getSimpleName(),
+ "content must not be blank");
+ }
+ }
+ }
+ verifyNoMoreInteractions(dispatcher);
+ }
+
+ @Test
+ void testOssieImportRejectsYamlDeclaredAsJson() {
+ String yaml = "version: 0.2.0.dev0\nname: sales\ndatasets: []\n";
+ assertError(
+ postDocument(semanticModelPath() + "/ossie", yaml, MediaType.APPLICATION_JSON),
+ Response.Status.BAD_REQUEST,
+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE,
+ IllegalSemanticModelException.class.getSimpleName(),
+ "Cannot parse Apache Ossie JSON");
+ verify(dispatcher).importOssieDocument(namespace, OssieDocument.json(yaml));
+ verifyNoMoreInteractions(dispatcher);
+ }
+
+ @Test
+ void testOssieImportRejectsUnsupportedMediaType() {
+ try (Response response =
+ postDocument(semanticModelPath() + "/ossie", "name: sales", "text/plain")) {
+ Assertions.assertEquals(
+ Response.Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode(), response.getStatus());
+ }
+ verifyNoMoreInteractions(dispatcher);
+ }
+
+ @Test
+ void testOssieImportPropagatesCreateErrors() {
+ String yaml =
+ "version: 0.2.0.dev0\nname: sales\ndatasets:\n"
+ + " - name: orders\n source: sales.mart.orders\n";
+ doThrow(new SemanticModelAlreadyExistsException("sales already exists"))
+ .when(dispatcher)
+ .createSemanticModel(eq(semanticModelIdentifier("sales")), eq(null), any(), any());
+ assertError(
+ postDocument(semanticModelPath() + "/ossie", yaml, "application/yaml"),
+ Response.Status.CONFLICT,
+ ErrorConstants.ALREADY_EXISTS_CODE,
+ SemanticModelAlreadyExistsException.class.getSimpleName(),
+ "sales already exists");
+ }
+
+ @Test
+ void testOssieExportPropagatesLoadErrors() {
+ doThrow(new NoSuchSemanticModelException("sales does not exist"))
+ .when(dispatcher)
+ .loadSemanticModel(semanticModelIdentifier("sales"));
+ assertError(
+ getOssie(semanticModelPath() + "/sales/ossie"),
+ Response.Status.NOT_FOUND,
+ ErrorConstants.NOT_FOUND_CODE,
+ NoSuchSemanticModelException.class.getSimpleName(),
+ "sales does not exist");
+ }
+
private SemanticModelCreateRequest createRequest(
String name, String comment, SemanticModelDefinition definition) {
return new SemanticModelCreateRequest(
@@ -645,6 +925,17 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
return target(path).request(MediaType.APPLICATION_JSON_TYPE).accept(VND_V1_JSON).delete();
}
+ private Response postDocument(String path, String document, String mediaType) {
+ return target(path)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept(VND_V1_JSON)
+ .post(Entity.entity(document, mediaType));
+ }
+
+ private Response getOssie(String path) {
+ return target(path).request().get();
+ }
+
private static ErrorResponse assertError(
Response response,
Response.Status expectedStatus,