You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jena.apache.org by an...@apache.org on 2024/05/08 07:26:39 UTC
(jena) branch main updated: GH-2160: introduce jena-ontapi (OWL2 support)
This is an automated email from the ASF dual-hosted git repository.
andy pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/jena.git
The following commit(s) were added to refs/heads/main by this push:
new 52b1d6b473 GH-2160: introduce jena-ontapi (OWL2 support)
52b1d6b473 is described below
commit 52b1d6b473055291c4df4024ab1396729ed35493
Author: sszuev <ss...@gmail.com>
AuthorDate: Tue May 9 16:20:46 2023 +0300
GH-2160: introduce jena-ontapi (OWL2 support)
---
jena-ontapi/README.md | 50 +
jena-ontapi/pom.xml | 113 +
.../org/apache/jena/ontapi/GraphRepository.java | 123 +
.../org/apache/jena/ontapi/OntJenaException.java | 238 +
.../org/apache/jena/ontapi/OntModelControls.java | 297 +
.../org/apache/jena/ontapi/OntModelFactory.java | 348 +
.../org/apache/jena/ontapi/OntSpecification.java | 627 ++
.../java/org/apache/jena/ontapi/UnionGraph.java | 237 +
.../jena/ontapi/common/BaseEnhNodeFactoryImpl.java | 104 +
.../ontapi/common/CommonEnhNodeFactoryImpl.java | 101 +
.../ontapi/common/CompositeEnhNodeFactoryImpl.java | 111 +
.../apache/jena/ontapi/common/EnhNodeFactory.java | 151 +
.../apache/jena/ontapi/common/EnhNodeFilter.java | 198 +
.../apache/jena/ontapi/common/EnhNodeFinder.java | 128 +
.../apache/jena/ontapi/common/EnhNodeProducer.java | 196 +
.../org/apache/jena/ontapi/common/OntConfig.java | 83 +
.../org/apache/jena/ontapi/common/OntConfigs.java | 267 +
.../org/apache/jena/ontapi/common/OntEnhGraph.java | 167 +
.../jena/ontapi/common/OntEnhNodeFactories.java | 164 +
.../ontapi/common/OntObjectPersonalityBuilder.java | 285 +
.../jena/ontapi/common/OntPersonalities.java | 753 ++
.../apache/jena/ontapi/common/OntPersonality.java | 333 +
.../jena/ontapi/common/OntPersonalityImpl.java | 169 +
.../apache/jena/ontapi/common/OntVocabulary.java | 716 ++
.../apache/jena/ontapi/common/PunningsMode.java | 213 +
.../jena/ontapi/common/ResourceVocabulary.java | 53 +
.../jena/ontapi/common/ResourceVocabularyImpl.java | 161 +
.../jena/ontapi/common/WrappedEnhNodeFactory.java | 91 +
.../apache/jena/ontapi/impl/GraphListenerBase.java | 107 +
.../apache/jena/ontapi/impl/HierarchySupport.java | 357 +
.../apache/jena/ontapi/impl/OntGraphModelImpl.java | 1854 ++++
.../org/apache/jena/ontapi/impl/OntModelEvent.java | 93 +
.../apache/jena/ontapi/impl/UnionGraphImpl.java | 661 ++
.../ontapi/impl/factories/OWL1ObjectFactories.java | 398 +
.../ontapi/impl/factories/OWL2ObjectFactories.java | 852 ++
.../jena/ontapi/impl/factories/OntAnnotations.java | 83 +
.../jena/ontapi/impl/factories/OntClasses.java | 1068 +++
.../jena/ontapi/impl/factories/OntDataRanges.java | 230 +
.../jena/ontapi/impl/factories/OntDisjoints.java | 128 +
.../jena/ontapi/impl/factories/OntEntities.java | 278 +
.../jena/ontapi/impl/factories/OntIndividuals.java | 122 +
.../jena/ontapi/impl/factories/OntProperties.java | 233 +
.../jena/ontapi/impl/factories/OntSWRLs.java | 94 +
.../ontapi/impl/factories/RDFSObjectFactories.java | 186 +
.../ontapi/impl/factories/STDObjectFactories.java | 152 +
.../ontapi/impl/factories/SWRLObjectFactories.java | 128 +
.../ontapi/impl/objects/OntAnnotationImpl.java | 182 +
.../impl/objects/OntAnnotationPropertyImpl.java | 105 +
.../jena/ontapi/impl/objects/OntClassImpl.java | 1549 ++++
.../ontapi/impl/objects/OntDataPropertyImpl.java | 144 +
.../jena/ontapi/impl/objects/OntDataRangeImpl.java | 245 +
.../jena/ontapi/impl/objects/OntDisjointImpl.java | 290 +
.../impl/objects/OntFacetRestrictionImpl.java | 196 +
.../apache/jena/ontapi/impl/objects/OntIDImpl.java | 114 +
.../ontapi/impl/objects/OntIndividualImpl.java | 301 +
.../jena/ontapi/impl/objects/OntListImpl.java | 761 ++
.../ontapi/impl/objects/OntNamedDataRangeImpl.java | 88 +
.../objects/OntNegativePropertyAssertionImpl.java | 157 +
.../jena/ontapi/impl/objects/OntObjectImpl.java | 702 ++
.../ontapi/impl/objects/OntObjectPropertyImpl.java | 376 +
.../jena/ontapi/impl/objects/OntPropertyImpl.java | 147 +
.../jena/ontapi/impl/objects/OntSWRLImpl.java | 507 +
.../ontapi/impl/objects/OntSimpleClassImpl.java | 271 +
.../ontapi/impl/objects/OntSimplePropertyImpl.java | 90 +
.../jena/ontapi/impl/objects/OntStatementImpl.java | 507 +
.../impl/repositories/DocumentGraphRepository.java | 167 +
.../impl/repositories/OntUnionGraphListener.java | 304 +
.../impl/repositories/OntUnionGraphRepository.java | 311 +
.../java/org/apache/jena/ontapi/model/AsNamed.java | 38 +
.../apache/jena/ontapi/model/CreateClasses.java | 416 +
.../apache/jena/ontapi/model/CreateDisjoint.java | 133 +
.../org/apache/jena/ontapi/model/CreateRanges.java | 151 +
.../org/apache/jena/ontapi/model/CreateSWRL.java | 174 +
.../apache/jena/ontapi/model/HasCardinality.java | 51 +
.../org/apache/jena/ontapi/model/HasDisjoint.java | 36 +
.../apache/jena/ontapi/model/HasProperties.java | 45 +
.../org/apache/jena/ontapi/model/HasProperty.java | 40 +
.../apache/jena/ontapi/model/HasRDFNodeList.java | 39 +
.../org/apache/jena/ontapi/model/HasValue.java | 48 +
.../java/org/apache/jena/ontapi/model/IOModel.java | 76 +
.../org/apache/jena/ontapi/model/MutableModel.java | 112 +
.../apache/jena/ontapi/model/OntAnnotation.java | 129 +
.../jena/ontapi/model/OntAnnotationProperty.java | 160 +
.../org/apache/jena/ontapi/model/OntClass.java | 1250 +++
.../apache/jena/ontapi/model/OntDataProperty.java | 320 +
.../org/apache/jena/ontapi/model/OntDataRange.java | 278 +
.../org/apache/jena/ontapi/model/OntDisjoint.java | 107 +
.../org/apache/jena/ontapi/model/OntEntity.java | 103 +
.../jena/ontapi/model/OntFacetRestriction.java | 106 +
.../java/org/apache/jena/ontapi/model/OntID.java | 190 +
.../apache/jena/ontapi/model/OntIndividual.java | 549 ++
.../java/org/apache/jena/ontapi/model/OntList.java | 211 +
.../org/apache/jena/ontapi/model/OntModel.java | 713 ++
.../apache/jena/ontapi/model/OntNamedProperty.java | 88 +
.../jena/ontapi/model/OntNegativeAssertion.java | 81 +
.../org/apache/jena/ontapi/model/OntObject.java | 438 +
.../jena/ontapi/model/OntObjectProperty.java | 835 ++
.../org/apache/jena/ontapi/model/OntProperty.java | 264 +
.../jena/ontapi/model/OntRelationalProperty.java | 274 +
.../org/apache/jena/ontapi/model/OntResource.java | 101 +
.../java/org/apache/jena/ontapi/model/OntSWRL.java | 215 +
.../org/apache/jena/ontapi/model/OntStatement.java | 356 +
.../apache/jena/ontapi/model/PrefixedModel.java | 53 +
.../org/apache/jena/ontapi/model/RDFNodeList.java | 120 +
.../apache/jena/ontapi/model/SetCardinality.java | 41 +
.../apache/jena/ontapi/model/SetComponents.java | 64 +
.../apache/jena/ontapi/model/SetProperties.java | 48 +
.../org/apache/jena/ontapi/model/SetProperty.java | 42 +
.../org/apache/jena/ontapi/model/SetValue.java | 50 +
.../org/apache/jena/ontapi/model/WithOntList.java | 38 +
.../java/org/apache/jena/ontapi/utils/Graphs.java | 959 ++
.../org/apache/jena/ontapi/utils/Iterators.java | 653 ++
.../org/apache/jena/ontapi/utils/OntModels.java | 376 +
.../org/apache/jena/ontapi/utils/StdModels.java | 236 +
.../org/apache/jena/ontapi/vocabulary/OWL.java | 47 +
.../org/apache/jena/ontapi/vocabulary/RDF.java | 47 +
.../org/apache/jena/ontapi/vocabulary/SWRL.java | 68 +
.../org/apache/jena/ontapi/vocabulary/SWRLB.java | 111 +
.../org/apache/jena/ontapi/vocabulary/XSD.java | 44 +
.../jena/ontapi/DocumentGraphRepositoryTest.java | 74 +
.../org/apache/jena/ontapi/GraphUtilsTest.java | 331 +
.../org/apache/jena/ontapi/JenaReasonerTest.java | 196 +
.../org/apache/jena/ontapi/ModelUtilsTest.java | 166 +
.../org/apache/jena/ontapi/OntAnnotationsTest.java | 621 ++
.../ontapi/OntClassDeclaredPropertiesTest.java | 516 ++
.../jena/ontapi/OntClassHierarchyRootTest.java | 267 +
.../jena/ontapi/OntClassIndividualsTest.java | 728 ++
.../org/apache/jena/ontapi/OntClassMiscTest.java | 218 +
.../apache/jena/ontapi/OntClassSubClassesTest.java | 1578 ++++
.../jena/ontapi/OntClassSuperClassesTest.java | 661 ++
.../apache/jena/ontapi/OntDataPropertyTest.java | 122 +
.../org/apache/jena/ontapi/OntDatatypeTest.java | 158 +
.../java/org/apache/jena/ontapi/OntEntityTest.java | 108 +
.../org/apache/jena/ontapi/OntExpressionTest.java | 253 +
.../jena/ontapi/OntIndividualClassesTest.java | 739 ++
.../apache/jena/ontapi/OntIndividualMiscTest.java | 203 +
.../java/org/apache/jena/ontapi/OntListTest.java | 593 ++
.../apache/jena/ontapi/OntModelClassesTest.java | 282 +
.../jena/ontapi/OntModelHierarchyRootsTest.java | 300 +
.../jena/ontapi/OntModelIndividualsTest.java | 357 +
.../org/apache/jena/ontapi/OntModelMiscTest.java | 71 +
.../apache/jena/ontapi/OntModelOWL1SpecsTest.java | 296 +
.../apache/jena/ontapi/OntModelOWL2ELSpecTest.java | 287 +
.../apache/jena/ontapi/OntModelOWL2QLSpecTest.java | 346 +
.../apache/jena/ontapi/OntModelOWL2RLSpecTest.java | 389 +
.../jena/ontapi/OntModelOWLLiteSpecTest.java | 186 +
.../apache/jena/ontapi/OntModelOWLSpecsTest.java | 1329 +++
.../apache/jena/ontapi/OntModelPropertiesTest.java | 335 +
.../apache/jena/ontapi/OntModelRDFSSpecTest.java | 276 +
.../apache/jena/ontapi/OntObjectPropertyTest.java | 197 +
.../org/apache/jena/ontapi/OntPersonalityTest.java | 357 +
.../org/apache/jena/ontapi/OntPropertyTest.java | 419 +
.../jena/ontapi/OntUnionGraphRepositoryTest.java | 601 ++
.../java/org/apache/jena/ontapi/SWRLModelTest.java | 262 +
.../java/org/apache/jena/ontapi/StreamsTest.java | 204 +
.../org/apache/jena/ontapi/TestModelFactory.java | 369 +
.../apache/jena/ontapi/TestOntPersonalities.java | 88 +
.../test/java/org/apache/jena/ontapi/TestSpec.java | 153 +
.../org/apache/jena/ontapi/UnionGraphTest.java | 425 +
.../apache/jena/ontapi/testutils/MiscUtils.java | 66 +
.../jena/ontapi/testutils/ModelTestUtils.java | 379 +
.../jena/ontapi/testutils/RDFIOTestUtils.java | 65 +
jena-ontapi/src/test/resources/builtins-owl.rdf | 279 +
jena-ontapi/src/test/resources/builtins-rdfs.rdf | 235 +
jena-ontapi/src/test/resources/dttest1.nt | 2 +
jena-ontapi/src/test/resources/dttest2.nt | 2 +
jena-ontapi/src/test/resources/dttest3.nt | 2 +
jena-ontapi/src/test/resources/family.ttl | 3747 ++++++++
jena-ontapi/src/test/resources/food.ttl | 1030 +++
.../src/test/resources/frame-view-test-ldp.rdf | 90 +
jena-ontapi/src/test/resources/koala.owl | 250 +
.../list-syntax-categories-test-comps.rdf | 78 +
.../list-syntax-categories-test-with-import.rdf | 84 +
.../test/resources/list-syntax-categories-test.rdf | 83 +
.../src/test/resources/log4j2-test.properties | 42 +
jena-ontapi/src/test/resources/pizza.ttl | 2138 +++++
jena-ontapi/src/test/resources/simple.ttl | 9752 ++++++++++++++++++++
jena-ontapi/src/test/resources/swrl-test.owl | 64 +
jena-ontapi/src/test/resources/wine.ttl | 1874 ++++
jena-ontapi/src/test/resources/with-recursion.ttl | 30 +
pom.xml | 2 +
181 files changed, 67494 insertions(+)
diff --git a/jena-ontapi/README.md b/jena-ontapi/README.md
new file mode 100644
index 0000000000..a77516091b
--- /dev/null
+++ b/jena-ontapi/README.md
@@ -0,0 +1,50 @@
+# Apache Jena OWL2 Model
+
+
+### Summary
+
+This is enhanced [Apache Jena](https://github.com/apache/jena) Inference [RDF](https://www.w3.org/TR/rdf11-concepts/) Model with [OWL2](https://www.w3.org/TR/owl2-syntax/) support.
+
+### Major components
+
+- [OntModel](src/main/java/org/apache/jena/ontapi/model/OntModel.java) - the main interface to work with OWL2 & OWL1 & RDFS ontologies
+- [OntModelFactory](src/main/java/org/apache/jena/ontapi/OntModelFactory.java) - factory for creating different `OntModel` types
+- [GraphRepository](src/main/java/org/apache/jena/ontapi/GraphRepository.java) - graph store accessor
+- [OntSpecification](src/main/java/org/apache/jena/ontapi/OntSpecification.java) - encapsulates `ReasonerFactory`, `OntConfig`, `OntPersonality`
+- [UnionGraph](src/main/java/org/apache/jena/ontapi/UnionGraph.java) - a Graph implementation with support hierarchy
+- [OntModelConfig](src/main/java/org/apache/jena/ontapi/OntModelControls.java) - model configuration, defines
+ what a model can do and what it cannot do
+- [OntPersonality](src/main/java/org/apache/jena/ontapi/common/OntPersonality.java) - a configuration class
+ to conduct Jena's polymorphism for `OntObject`s
+
+### Supported specifications
+
+- OWL2 DL & Full: NO_INF, RULES_INF, RDFS_INF, TRANS_INF + BUILTIN_INF (default)
+- OWL2 EL: NO_INF, RULES_INF, RDFS_INF, TRANS_INF
+- OWL2 QL: NO_INF, RULES_INF, RDFS_INF, TRANS_INF
+- OWL2 RL: NO_INF, RULES_INF, RDFS_INF, TRANS_INF
+- OWL1 DL & Full: NO_INF, RULES_INF, RDFS_INF, TRANS_INF, MICRO_RULES, MINI_RULES
+- OWL1 Lite: NO_INF, RULES_INF, RDFS_INF, TRANS_INF
+- RDFS: NO_INF, RDFS_INF, TRANS_INF
+
+### Example
+
+```java
+GraphRepository repository = GraphRepository.createGraphDocumentRepositoryMem();
+
+OntModel m = OntModelFactory.createModel(OntSpecification.OWL2_DL_MEM_BUILTIN_INF, repository)
+ .setNsPrefixes(OntModelFactory.STANDARD);
+
+m.setID("ont").setVersionIRI("ont#v1");
+
+OntObjectProperty p = m.createObjectProperty("p");
+OntClass a = m.createOntClass("a");
+OntIndividual i = a.createIndividual("i");
+OntClass b = m.createOntClass("b")
+ .addSuperClass(m.createObjectIntersectionOf(a, m.createObjectHasValue(p, i)));
+
+m.ontObjects(OntClass.class).forEach(System.out::println);
+m.ontObjects(OntIndividual.class).forEach(System.out::println);
+
+m.write(System.out, "ttl");
+```
\ No newline at end of file
diff --git a/jena-ontapi/pom.xml b/jena-ontapi/pom.xml
new file mode 100644
index 0000000000..fc83dc956e
--- /dev/null
+++ b/jena-ontapi/pom.xml
@@ -0,0 +1,113 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>jena-ontapi</artifactId>
+ <packaging>jar</packaging>
+ <name>Apache Jena - ONTAPI</name>
+ <parent>
+ <groupId>org.apache.jena</groupId>
+ <artifactId>jena</artifactId>
+ <version>5.1.0-SNAPSHOT</version>
+ <relativePath>..</relativePath>
+ </parent>
+
+ <description>Ontology API for Apache Jena</description>
+
+ <properties>
+ <build.time.xsd>${maven.build.timestamp}</build.time.xsd>
+ <automatic.module.name>org.apache.jena.ontapi</automatic.module.name>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.jena</groupId>
+ <artifactId>jena-arq</artifactId>
+ <version>5.1.0-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-params</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-slf4j2-impl</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-source-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-sources</id>
+ <goals>
+ <goal>jar-no-fork</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-javadocs</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attache-tests</id>
+ <goals>
+ <goal>test-jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
\ No newline at end of file
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/GraphRepository.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/GraphRepository.java
new file mode 100644
index 0000000000..caf8af9f23
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/GraphRepository.java
@@ -0,0 +1,123 @@
+/*
+ * 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.jena.ontapi;
+
+import org.apache.jena.ontapi.impl.repositories.DocumentGraphRepository;
+import org.apache.jena.graph.Graph;
+import org.apache.jena.graph.GraphMemFactory;
+import org.apache.jena.ontapi.model.OntID;
+
+import java.util.Objects;
+import java.util.function.Supplier;
+import java.util.stream.Stream;
+
+/**
+ * Graph repository.
+ * Each {@link Graph} is associated with ID.
+ * For OWL Ontology Graphs, Graph ID can be {@link OntID#getImportsIRI()}.
+ *
+ * @see org.apache.jena.ontology.OntDocumentManager
+ */
+public interface GraphRepository {
+
+ /**
+ * A factory method to creates {@link GraphRepository} instance
+ * that loads graphs on demand from the location to memory.
+ * The location is specified by the method {@link DocumentGraphRepository#addMapping(String, String)}.
+ *
+ * @return {@link DocumentGraphRepository}
+ */
+ static DocumentGraphRepository createGraphDocumentRepositoryMem() {
+ return createGraphDocumentRepository(GraphMemFactory::createDefaultGraph);
+ }
+
+ /**
+ * A factory method to creates {@link GraphRepository} instance
+ * that loads graphs on demand from the location.
+ * The location is specified by the method {@link DocumentGraphRepository#addMapping(String, String)}.
+ *
+ * @param factory {@link Supplier} to produce new {@link Graph}, {@code null} for default
+ * @return {@link DocumentGraphRepository}
+ */
+ static DocumentGraphRepository createGraphDocumentRepository(Supplier<Graph> factory) {
+ return new DocumentGraphRepository(Objects.requireNonNull(factory, "Null graph factory"));
+ }
+
+ /**
+ * Gets Graph by ID.
+ *
+ * @param id {@code String} Graph's identifier
+ * @return {@link Graph}
+ */
+ Graph get(String id);
+
+ /**
+ * @return {@code Stream} of Graph's identifiers
+ */
+ Stream<String> ids();
+
+ /**
+ * Associates the specified graph with the specified ID,
+ * returning the previous association or {@code null} if there was no association.
+ *
+ * @param id {@code String} Graph's identifier
+ * @param graph {@link Graph}
+ * @return {@link Graph} or {@code null}
+ */
+ Graph put(String id, Graph graph);
+
+ /**
+ * Removes graph.
+ *
+ * @param id {@code String} Graph's identifier
+ * @return {@link Graph}
+ */
+ Graph remove(String id);
+
+ /**
+ * Removes all graphs.
+ */
+ void clear();
+
+ /**
+ * @return number of graphs
+ */
+ default long count() {
+ return ids().count();
+ }
+
+ /**
+ * Lists all graphs.
+ *
+ * @return {@code Stream} of {@link Graph}s
+ */
+ default Stream<Graph> graphs() {
+ return ids().map(this::get).filter(Objects::nonNull);
+ }
+
+ /**
+ * @param id {@code String} Graph's identifier
+ * @return boolean
+ */
+ default boolean contains(String id) {
+ Objects.requireNonNull(id);
+ return ids().anyMatch(id::equals);
+ }
+
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntJenaException.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntJenaException.java
new file mode 100644
index 0000000000..0f3c154d9a
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntJenaException.java
@@ -0,0 +1,238 @@
+/*
+ * 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.jena.ontapi;
+
+import org.apache.jena.ontapi.common.EnhNodeFactory;
+import org.apache.jena.shared.JenaException;
+
+/**
+ * A base ONT-API jena exception.
+ * The class also contains some exception-related utilities.
+ */
+public class OntJenaException extends JenaException {
+
+ public OntJenaException() {
+ super();
+ }
+
+ public OntJenaException(String message) {
+ super(message);
+ }
+
+ public OntJenaException(Throwable cause) {
+ super(cause);
+ }
+
+ public OntJenaException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public static <T> T notNull(T obj) {
+ return notNull(obj, null);
+ }
+
+ public static <T> T notNull(T obj, String message) {
+ if (obj == null)
+ throw message == null ? new IllegalArgument() : new IllegalArgument(message);
+ return obj;
+ }
+
+ /**
+ * Stub for TO-DO.
+ *
+ * @param message error description
+ * @param <X> any
+ * @return {@link X}
+ */
+ public static <X> X TODO(String message) {
+ throw new RuntimeException(message);
+ }
+
+ /**
+ * @param object any
+ * @param <X> any
+ * @return the specified {@code object}
+ * @throws IllegalStateException if {@link X} is {@code null}
+ * @see java.util.Objects#requireNonNull(Object)
+ */
+ public static <X> X checkNotNull(X object) {
+ if (object == null) {
+ throw new IllegalStateException();
+ }
+ return object;
+ }
+
+ /**
+ * @param object any
+ * @param message error description
+ * @param <X> any
+ * @return the specified {@code object}
+ * @throws IllegalStateException if {@link X} is {@code null}
+ * @see java.util.Objects#requireNonNull(Object)
+ */
+ public static <X> X checkNotNull(X object, String message) {
+ checkTrue(object != null, message);
+ return object;
+ }
+
+ /**
+ * @param mustBeFalse condition, if {@code true} and exception is expected
+ * @param message error description
+ * @throws IllegalStateException if parameter condition is {@code true}
+ */
+ public static void checkFalse(Boolean mustBeFalse, String message) {
+ if (mustBeFalse) {
+ throw new IllegalStateException(message);
+ }
+ }
+
+ /**
+ * @param mustBeTrue condition, if {@code false} and exception is expected
+ * @param message error description
+ * @throws IllegalStateException if parameter condition is {@code false}
+ */
+ public static void checkTrue(Boolean mustBeTrue, String message) {
+ if (!mustBeTrue) {
+ throw new IllegalStateException(message);
+ }
+ }
+
+ /**
+ * @param feature boolean
+ * @throws Unsupported if {@code feature} is {@code false}
+ */
+ public static void checkSupported(boolean feature) {
+ checkSupported(feature, null);
+ }
+
+ /**
+ * @param feature boolean
+ * @param message error description
+ * @throws Unsupported if {@code feature} is {@code false}
+ */
+ public static void checkSupported(boolean feature, String message) {
+ if (!feature) {
+ throw new OntJenaException.Unsupported(message);
+ }
+ }
+
+ /**
+ * Exception that is thrown when an ontology resource is converted to another facet,
+ * using {@link org.apache.jena.rdf.model.RDFNode#as as()},
+ * and the requested conversion is not possible.
+ * This is an analogue of {@link org.apache.jena.ontology.ConversionException},
+ * and it is used mostly by {@link EnhNodeFactory}.
+ */
+ public static class Conversion extends OntJenaException {
+ public Conversion(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public Conversion(String message) {
+ super(message);
+ }
+ }
+
+ /**
+ * Exception, which may happen while creation of ont-object.
+ */
+ public static class Creation extends OntJenaException {
+ public Creation(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public Creation(String message) {
+ super(message);
+ }
+ }
+
+ /**
+ * An exception to indicate that a feature is not supported right now
+ * or by design for current conditions.
+ */
+ public static class IllegalCall extends OntJenaException {
+ public IllegalCall() {
+ super();
+ }
+
+ public IllegalCall(String message) {
+ super(message);
+ }
+ }
+
+ /**
+ * An exception that is thrown if a recursion is found in the graph.
+ * Example of such a graph recursion:
+ * <pre>{@code _:b0 a owl:Class ; owl:complementOf _:b0 .}</pre>
+ */
+ public static class Recursion extends OntJenaException {
+
+ public Recursion(String message) {
+ super(message);
+ }
+ }
+
+ /**
+ * A Jena exception that indicates wrong input.
+ */
+ public static class IllegalArgument extends OntJenaException {
+ public IllegalArgument() {
+ super();
+ }
+
+ public IllegalArgument(String message) {
+ super(message);
+ }
+
+ public IllegalArgument(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ }
+
+ /**
+ * A Jena exception that indicates that Jena-object state is broken,
+ * which may happen in multithreading or in other uncommon situations.
+ */
+ public static class IllegalState extends OntJenaException {
+ public IllegalState() {
+ super();
+ }
+
+ public IllegalState(String message) {
+ super(message);
+ }
+
+ public IllegalState(String message, Throwable cause) {
+ super(message, cause);
+ }
+ }
+
+ /**
+ * Exception that is raised when an ontology operation is attempted that is
+ * not present in the configuration (e.g. language profile) for the current ontology model.
+ */
+ public static class Unsupported extends OntJenaException {
+ public Unsupported(String message) {
+ super(message);
+ }
+ }
+
+
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntModelControls.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntModelControls.java
new file mode 100644
index 0000000000..7943736f2a
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntModelControls.java
@@ -0,0 +1,297 @@
+/*
+ * 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.jena.ontapi;
+
+import org.apache.jena.ontapi.common.OntConfig;
+import org.apache.jena.ontapi.model.OntClass;
+import org.apache.jena.ontapi.model.OntIndividual;
+import org.apache.jena.ontapi.model.OntObjectProperty;
+import org.apache.jena.ontapi.model.OntRelationalProperty;
+import org.apache.jena.ontapi.model.OntDataProperty;
+import org.apache.jena.ontapi.model.OntID;
+import org.apache.jena.ontapi.model.OntModel;
+import org.apache.jena.ontapi.vocabulary.OWL;
+import org.apache.jena.rdf.model.Resource;
+
+/**
+ * Default settings for {@link OntConfig}.
+ */
+public enum OntModelControls {
+ /**
+ * If {@code true}, {@link OntID}
+ * will be generated automatically if it is absent (as a b-node).
+ * A valid OWL ontology must have a single ontology ID.
+ */
+ USE_GENERATE_ONTOLOGY_HEADER_IF_ABSENT_STRATEGY,
+ /**
+ * If {@code true}, a multiple ontology header is allowed.
+ * Since a valid OWL ontology can have only a single ontology ID, the most suitable will be chosen.
+ * Note that if there are several anonymous headers with similar contents,
+ * then there is no guarantee that the same node will always be selected after restarting JVM.
+ */
+ USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY,
+ /**
+ * If this key is set to {@code true}, then the class/property hierarchies
+ * (e.g., see {@link OntClass#subClasses()})
+ * are to be inferred by the naked model itself using builtin algorithms.
+ * Should not be used in conjunction with Reasoner.
+ *
+ * @see OntSpecification#OWL2_DL_MEM_BUILTIN_INF
+ */
+ USE_BUILTIN_HIERARCHY_SUPPORT,
+ /**
+ * If this key is set to {@code true},
+ * then {@code owl:DataRange} and {@code owl:distinctMembers} will also be considered,
+ * although in OWL2 they are deprecated.
+ * Applicable only for OWL2.
+ */
+ USE_OWL2_DEPRECATED_VOCABULARY_FEATURE,
+ /**
+ * If this key is set to {@code true},
+ * then {@code owl:DataRange} (OWL1) instead of {@code rdfs:Datatype} (OWL2).
+ */
+ USE_OWL1_DATARANGE_DECLARATION_FEATURE,
+ /**
+ * If this key is set to {@code true},
+ * then {@code owl:distinctMembers} (OWL1) is used instead of {@code owl:members} (OWL2).
+ * E.g. {@code _:x rdf:type owl:AllDifferent . _:x owl:distinctMembers (a1...an). }
+ */
+ USE_OWL1_DISTINCT_MEMBERS_PREDICATE_FEATURE,
+ /**
+ * If this key is set to {@code true}, all class expressions are allowed to be named (can have URI).
+ * This option is for compatibility with {@link org.apache.jena.ontology.OntModel}.
+ * In OWL2, complex class expression should be anonymous.
+ */
+ ALLOW_NAMED_CLASS_EXPRESSIONS,
+ /**
+ * If this key is set to {@code true}, there is a special type of class expressions,
+ * which includes any structure declared as {@code owl:Class} or {@code owl:Restriction}
+ * that cannot be classified as a specific type.
+ * Casting such a construction to a particular class type
+ * (e.g. {@code generic.as(OntClass.OneOf.class)}) will result in an exception,
+ * but as a class expression, it can a type of the individual, can be a domain for property, etc.
+ * This option is for compatibility with {@link org.apache.jena.ontology.OntModel}.
+ */
+ ALLOW_GENERIC_CLASS_EXPRESSIONS,
+ /**
+ * Controls anonymous individuals.
+ * Some specifications (e.g., OWL2 EL) do not allow anonymous individuals.
+ */
+ ALLOW_ANONYMOUS_INDIVIDUALS,
+ /**
+ * Used while {@link OntModel#individuals()}.
+ * If {@code true}, the class type is checked only by declaration
+ * ({@code owl:Class} & {@code owl:Restriction} for OWL profile, {@code rdfs:Class} for RDFS profile).
+ * Otherwise, a full checking is performed.
+ */
+ USE_SIMPLIFIED_TYPE_CHECKING_WHILE_LIST_INDIVIDUALS,
+ /**
+ * If {@code true},
+ * named class testing is compatible with the legacy {@link org.apache.jena.ontology.OntModel Jena OntModel},
+ * otherwise, a strict check against the specification for the class declaration is performed
+ * ({@code owl:Class} for OWL & {@code rdfs:Class} for RDFS types are required).
+ * Note that this only applies to
+ * {@link org.apache.jena.enhanced.EnhNode#canAs EnhNode#canAs} and {@link org.apache.jena.enhanced.EnhNode#as EnhNode#as} methods;
+ * iteration (e.g., methods {@code OntModel.ontObjects(OntClass.class)})
+ * still does not take into account classes with incorrect or missing declarations.
+ * For legacy Jena's casting rules see {@link org.apache.jena.ontology.Profile} impls.
+ */
+ USE_LEGACY_COMPATIBLE_NAMED_CLASS_FACTORY,
+ /**
+ * If this key is set to {@code true},
+ * then {@link OWL#NamedIndividual owl:NamedIndividual}
+ * declaration is used for creating individuals.
+ */
+ USE_OWL2_NAMED_INDIVIDUAL_DECLARATION_FEATURE,
+ /**
+ * Controls {@link OWL#hasKey owl:hasKey} functionality.
+ * If disabled,
+ * {@link OntClass#hasKeys() OntClass#hasKeys()} will return empty {@code Stream},
+ * modification operations, such as
+ * {@link OntClass#addHasKey(OntRelationalProperty...) OntClass#addHasKey(OntRelationalProperty...)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL2_CLASS_HAS_KEY_FEATURE,
+ /**
+ * Controls {@link OWL#disjointUnionOf owl:disjointUnionOf} functionality.
+ * If disabled,
+ * {@link OntClass.Named#disjointUnions() OntClass.Named#disjointUnions()}
+ * will return empty {@code Stream}, modification operations, such as
+ * {@link OntClass.Named#addDisjointUnion(OntClass...) OntClass.Named#addDisjointUnion(OntClass...)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL2_NAMED_CLASS_DISJOINT_UNION_FEATURE,
+ /**
+ * Controls {@link OWL#disjointWith owl:disjointWith} functionality.
+ * If disabled,
+ * {@link OntClass#disjoints() OntClass#disjoints()}
+ * will return empty {@code Stream}, modification operations, such as
+ * {@link OntClass#addDisjointClass(OntClass) OntClass#addDisjointClass(OntClass)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_CLASS_DISJOINT_WITH_FEATURE,
+ /**
+ * Controls {@link OWL#equivalentClass owl:equivalentClass} functionality.
+ * If disabled,
+ * {@link OntClass#equivalentClasses() OntClass#equivalentClasses()}
+ * will return empty {@code Stream}, modification operations, such as
+ * {@link OntClass#addEquivalentClass(OntClass) OntClass#addEquivalentClass(OntClass)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_CLASS_EQUIVALENT_FEATURE,
+ /**
+ * Controls {@link OWL#propertyDisjointWith owl:propertyDisjointWith} functionality.
+ * If disabled,
+ * {@link OntRelationalProperty#disjointProperties() OntRelationalProperty#disjointProperties()}
+ * will return empty {@code Stream}, modification operations, such as
+ * {@link OntObjectProperty#addDisjointProperty(OntObjectProperty) OntObjectProperty#addDisjointProperty(OntObjectProperty)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL2_PROPERTY_DISJOINT_WITH_FEATURE,
+ /**
+ * Controls {@link OWL#equivalentProperty owl:equivalentProperty} functionality.
+ * If disabled,
+ * {@link OntRelationalProperty#equivalentProperties() OntRelationalProperty#equivalentProperties()}
+ * will return empty {@code Stream}, modification operations, such as
+ * {@link OntObjectProperty#addEquivalentProperty(OntObjectProperty) OntObjectProperty#addEquivalentProperty(OntObjectProperty)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_PROPERTY_EQUIVALENT_FEATURE,
+ /**
+ * Controls data {@link OWL#FunctionalProperty owl:FunctionalProperty} functionality.
+ * If disabled,
+ * {@link OntDataProperty#isFunctional() OntDataProperty#isFunctional()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntDataProperty#setFunctional(boolean) OntDataProperty#setFunctional(boolean)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_DATA_PROPERTY_FUNCTIONAL_FEATURE,
+ /**
+ * Controls object {@link OWL#FunctionalProperty owl:FunctionalProperty} functionality.
+ * If disabled,
+ * {@link OntObjectProperty#isFunctional() OntObjectProperty#isFunctional()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntObjectProperty#setFunctional(boolean) OntObjectProperty#setFunctional(boolean)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_OBJECT_PROPERTY_FUNCTIONAL_FEATURE,
+ /**
+ * Controls {@link OWL#InverseFunctionalProperty owl:InverseFunctionalProperty} functionality.
+ * If disabled,
+ * {@link OntObjectProperty#isInverseFunctional() OntObjectProperty#isInverseFunctional()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntObjectProperty#setInverseFunctional(boolean) OntObjectProperty#setInverseFunctional(boolean)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_PROPERTY_INVERSE_FUNCTIONAL_FEATURE,
+ /**
+ * Controls {@link OWL#SymmetricProperty owl:SymmetricProperty} functionality.
+ * If disabled,
+ * {@link OntObjectProperty#isSymmetric() OntObjectProperty#isSymmetric()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntObjectProperty#setSymmetric(boolean) OntObjectProperty#setSymmetric(boolean)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_PROPERTY_SYMMETRIC_FEATURE,
+ /**
+ * Controls {@link OWL#AsymmetricProperty owl:AsymmetricProperty} functionality.
+ * If disabled,
+ * {@link OntObjectProperty#isAsymmetric() OntObjectProperty#isAsymmetric()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntObjectProperty#setAsymmetric(boolean) OntObjectProperty#setAsymmetric(boolean)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_PROPERTY_ASYMMETRIC_FEATURE,
+ /**
+ * Controls {@link OWL#TransitiveProperty owl:TransitiveProperty} functionality.
+ * If disabled,
+ * {@link OntObjectProperty#isTransitive() OntObjectProperty#isTransitive()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntObjectProperty#setTransitive(boolean) OntObjectProperty#setTransitive(boolean)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_PROPERTY_TRANSITIVE_FEATURE,
+ /**
+ * Controls {@link OWL#ReflexiveProperty owl:ReflexiveProperty} functionality.
+ * If disabled,
+ * {@link OntObjectProperty#isReflexive() OntObjectProperty#isReflexive()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntObjectProperty#setReflexive(boolean) OntObjectProperty#setReflexive(boolean)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_PROPERTY_REFLEXIVE_FEATURE,
+ /**
+ * Controls {@link OWL#IrreflexiveProperty owl:IrreflexiveProperty} functionality.
+ * If disabled,
+ * {@link OntObjectProperty#isIrreflexive() OntObjectProperty#isIrreflexive()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntObjectProperty#setIrreflexive(boolean) OntObjectProperty#setIrreflexive(boolean)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_PROPERTY_IRREFLEXIVE_FEATURE,
+ /**
+ * Controls {@link OWL#inverseOf owl:inverseOf} functionality.
+ * If disabled,
+ * {@link OntObjectProperty#inverseProperties() OntObjectProperty#inverseProperties()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntObjectProperty#addInverseProperty(OntObjectProperty) OntObjectProperty#addInverseProperty(OntObjectProperty)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_PROPERTY_INVERSE_OF_FEATURE,
+ /**
+ * If this key is set to {@code true}, an anonymous inverse object property type is enabled (OWL2 feature).
+ * That is {@code _:x owl:inverseOf PN}, where {@code _:x} is a b-node and {@code PN} is a named object property.
+ */
+ USE_OWL_INVERSE_OBJECT_PROPERTY_FEATURE,
+ /**
+ * Controls {@link OWL#propertyChainAxiom owl:propertyChainAxiom} functionality.
+ * If disabled,
+ * {@link OntObjectProperty#propertyChains() OntObjectProperty#propertyChains()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntObjectProperty#addPropertyChain(OntObjectProperty...) OntObjectProperty#addPropertyChain(OntObjectProperty...)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_PROPERTY_CHAIN_AXIOM_FEATURE,
+ /**
+ * Controls {@link OWL#sameAs owl:sameAs} functionality.
+ * If disabled,
+ * {@link OntIndividual#sameIndividuals() OntIndividual#sameIndividuals()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntIndividual#addSameIndividual(OntIndividual) OntIndividual#addSameIndividual(OntIndividual)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_INDIVIDUAL_SAME_AS_FEATURE,
+ /**
+ * Controls {@link OWL#differentFrom owl:differentFrom} functionality.
+ * If disabled,
+ * {@link OntIndividual#differentIndividuals() OntIndividual#differentIndividuals()}
+ * will return {@code false}, modification operations, such as
+ * {@link OntIndividual#removeDifferentIndividual(Resource) OntIndividual#removeDifferentIndividual(Resource)},
+ * will throw {@link OntJenaException.Unsupported OntJenaException.Unsupported} exception.
+ */
+ USE_OWL_INDIVIDUAL_DIFFERENT_FROM_FEATURE,
+ /**
+ * If this key is set to {@code true},
+ * then {@link OWL#qualifiedCardinality owl:qualifiedCardinality},
+ * {@link OWL#maxQualifiedCardinality owl:maxQualifiedCardinality},
+ * {@link OWL#minQualifiedCardinality owl:minQualifiedCardinality}
+ * predicates are allowed for Cardinality restrictions.
+ */
+ USE_OWL2_QUALIFIED_CARDINALITY_RESTRICTION_FEATURE,
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntModelFactory.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntModelFactory.java
new file mode 100644
index 0000000000..dc4ab10090
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntModelFactory.java
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.jena.ontapi;
+
+import org.apache.jena.ontapi.common.OntConfigs;
+import org.apache.jena.ontapi.common.OntObjectPersonalityBuilder;
+import org.apache.jena.ontapi.common.OntPersonality;
+import org.apache.jena.ontapi.impl.OntGraphModelImpl;
+import org.apache.jena.ontapi.impl.UnionGraphImpl;
+import org.apache.jena.ontapi.impl.repositories.OntUnionGraphRepository;
+import org.apache.jena.ontapi.model.OntModel;
+import org.apache.jena.ontapi.utils.Graphs;
+import org.apache.jena.ontapi.vocabulary.OWL;
+import org.apache.jena.ontapi.vocabulary.RDF;
+import org.apache.jena.graph.Graph;
+import org.apache.jena.graph.GraphMemFactory;
+import org.apache.jena.graph.Node;
+import org.apache.jena.graph.NodeFactory;
+import org.apache.jena.ontapi.model.OntID;
+import org.apache.jena.rdf.model.Model;
+import org.apache.jena.rdf.model.impl.ModelCom;
+import org.apache.jena.reasoner.InfGraph;
+import org.apache.jena.reasoner.Reasoner;
+import org.apache.jena.reasoner.ReasonerFactory;
+import org.apache.jena.shared.PrefixMapping;
+import org.apache.jena.sys.JenaSystem;
+import org.apache.jena.vocabulary.RDFS;
+import org.apache.jena.vocabulary.XSD;
+
+import java.util.Objects;
+
+/**
+ * A factory to produce {@link OntModel OWL2 model}s, {@link Model Common model}s and {@link Graph graph}s.
+ * Currently, OWL2 models support only direct semantic with no additional entailment reasoning.
+ * This corresponds to {@link org.apache.jena.ontology.OntModelSpec#OWL_MEM OWL_MEM spec} for {@link org.apache.jena.ontology.OntModel Jena OWL model}.
+ */
+public class OntModelFactory {
+
+ /**
+ * A {@code PrefixMapping} that contains the "standard" for OWL2 prefixes we know about, viz rdf, rdfs, xsd, and owl.
+ */
+ public static final PrefixMapping STANDARD = PrefixMapping.Factory.create()
+ .setNsPrefix("owl", OWL.NS)
+ .setNsPrefix("rdfs", RDFS.uri)
+ .setNsPrefix("rdf", RDF.uri)
+ .setNsPrefix("xsd", XSD.NS)
+ .lock();
+
+ static {
+ init();
+ }
+
+ /**
+ * Initializes Jena System.
+ */
+ public static void init() {
+ JenaSystem.init();
+ }
+
+ /**
+ * Creates default (in-memory) graph implementation.
+ *
+ * @return {@code Graph}
+ */
+ public static Graph createDefaultGraph() {
+ return GraphMemFactory.createGraphMem();
+ }
+
+ /**
+ * Wraps the given {@code base} graph as {@link UnionGraph}
+ *
+ * @param base {@code Graph}
+ * @return {@link UnionGraph}
+ */
+ public static UnionGraph createUnionGraph(Graph base) {
+ // non-distinct graph since requiring distinct is expensive;
+ // usually OWL imports-closure does not contain duplicate data and
+ // cyclic imports are resolved by the UnionGraph itself and do non lead to duplication data
+ return new UnionGraphImpl(base, false);
+ }
+
+ /**
+ * Creates default (in-memory) RDF Model implementation.
+ *
+ * @return {@link Model}
+ * @see org.apache.jena.rdf.model.ModelFactory#createDefaultModel()
+ */
+ public static Model createDefaultModel() {
+ return createDefaultModel(createDefaultGraph());
+ }
+
+ /**
+ * Creates default RDF Model implementation wrapping the given graph.
+ *
+ * @param graph {@link Graph}, not {@code null}
+ * @return {@link Model}
+ * @see org.apache.jena.rdf.model.ModelFactory#createDefaultModel()
+ */
+ public static Model createDefaultModel(Graph graph) {
+ return new ModelCom(Objects.requireNonNull(graph));
+ }
+
+ /**
+ * Creates a fresh in-memory Ontology RDF Model with default personalities.
+ *
+ * @return {@link OntModel}
+ */
+ public static OntModel createModel() {
+ return createModel(createDefaultGraph());
+ }
+
+ /**
+ * Creates an Ontology RDF Model wrapper around the given graph with default personalities.
+ *
+ * @param graph {@link Graph}
+ * @return {@link OntModel}
+ */
+ public static OntModel createModel(Graph graph) {
+ return createModel(graph, OntSpecification.OWL2_DL_MEM_BUILTIN_INF).setNsPrefixes(STANDARD);
+ }
+
+ /**
+ * Creates an Ontology RDF Model wrapper around the given graph with given personalities.
+ *
+ * @param graph {@link Graph}
+ * @param personality {@link OntPersonality}
+ * @return {@link OntModel}
+ */
+ public static OntModel createModel(Graph graph, OntPersonality personality) {
+ OntPersonality withBuiltinHierarchySupport = OntObjectPersonalityBuilder.from(personality)
+ .setConfig(OntConfigs.OWL2_CONFIG.setTrue(OntModelControls.USE_BUILTIN_HIERARCHY_SUPPORT))
+ .build();
+ return createModel(graph, new OntSpecification(withBuiltinHierarchySupport, null)).setNsPrefixes(STANDARD);
+ }
+
+ /**
+ * Creates an Ontology Model according to the specified specification.
+ *
+ * @param spec {@link OntSpecification}
+ * @return {@link OntModel}
+ */
+ public static OntModel createModel(OntSpecification spec) {
+ return createModel(createDefaultGraph(), spec).setNsPrefixes(STANDARD);
+ }
+
+ /**
+ * Creates an Ontology Model according to the specified specification.
+ *
+ * @param data {@link Graph} (base graph)
+ * @param spec {@link OntSpecification}
+ * @return {@link OntModel}
+ */
+ public static OntModel createModel(Graph data, OntSpecification spec) {
+ Objects.requireNonNull(data);
+ ReasonerFactory reasonerFactory = Objects.requireNonNull(spec).getReasonerFactory();
+ if (reasonerFactory == null) {
+ return new OntGraphModelImpl(Graphs.makeOntUnionFrom(data, OntModelFactory::createUnionGraph), spec.getPersonality());
+ }
+ return createModel(data, spec.getPersonality(), reasonerFactory.create(null));
+ }
+
+ /**
+ * Creates an {@link OntModel Ontology Model} which is {@link org.apache.jena.rdf.model.InfModel Inference Model}.
+ * The specified graph and its subgraphs (if any) must not be {@link InfGraph}.
+ *
+ * @param graph {@link Graph}
+ * @param personality {@link OntPersonality}
+ * @param reasoner {@link Reasoner}
+ * @return {@link OntModel}
+ * @see OntModel#asInferenceModel()
+ */
+ public static OntModel createModel(Graph graph, OntPersonality personality, Reasoner reasoner) {
+ Objects.requireNonNull(graph);
+ Objects.requireNonNull(reasoner);
+ Objects.requireNonNull(personality);
+ if (Graphs.dataGraphs(graph).anyMatch(it -> it instanceof InfGraph)) {
+ throw new IllegalArgumentException("InfGraph in the hierarchy detected");
+ }
+ UnionGraph unionGraph = Graphs.makeOntUnionFrom(graph, OntModelFactory::createUnionGraph);
+ InfGraph infGraph = reasoner.bind(unionGraph);
+ return new OntGraphModelImpl(infGraph, personality);
+ }
+
+ /**
+ * Creates an Ontology Model associated with {@link OntSpecification#OWL2_DL_MEM_BUILTIN_INF} spec.
+ * The {@code repository} manages all the dependencies.
+ * See {@link #createModel(Graph, OntSpecification, GraphRepository)}.
+ *
+ * @param uri String, subject of {@code uri rdf:type owl:Ontology} statement.
+ * @param repository {@link GraphRepository}
+ * @return {@link OntModel}
+ */
+ public static OntModel createModel(String uri, GraphRepository repository) {
+ Objects.requireNonNull(uri);
+ return createModel(
+ createDefaultModel().createResource(uri, OWL.Ontology).getModel().getGraph(),
+ OntSpecification.OWL2_DL_MEM_BUILTIN_INF,
+ repository
+ ).setNsPrefixes(STANDARD);
+ }
+
+ /**
+ * Creates an Ontology Model according to the specified specification.
+ * The {@code repository} manages all the dependencies.
+ * See {@link #createModel(Graph, OntSpecification, GraphRepository)}.
+ *
+ * @param spec {@link OntSpecification}
+ * @param repository {@link GraphRepository}
+ * @return {@link OntModel}
+ */
+ public static OntModel createModel(OntSpecification spec, GraphRepository repository) {
+ return createModel(createDefaultGraph(), spec, repository).setNsPrefixes(STANDARD);
+ }
+
+ /**
+ * Creates an Ontology Model according to the specified specification.
+ * The {@code repository} manages all the dependencies (imports closure).
+ * <p>
+ * Note that for consistency it is necessary to work only
+ * through the {@link OntModel} or {@link UnionGraph} interfaces.
+ * Working directly with the {@link UnionGraph#getBaseGraph()} or {@code repository} may break the state.
+ * Imports closure control is performed via {@link UnionGraph.Listener},
+ * any ontological graphs in the {@code repository} is wrapped as {@link UnionGraph},
+ * {@link InfGraph} are not stored in the {@code repository}.
+ * When adding subgraph using the {@link UnionGraph#addSubGraph(Graph)} method
+ * a statement {@code a owl:import b} will be added.
+ * In turns, adding a statement {@code a owl:import b} will cause adding a subgraph.
+ * If a subgraph cannot be found in the {@code repository},
+ * an empty ontology graph will be associated with the corresponding {@code owl:import}.
+ * The specified graph and its subgraphs (if any) must not be {@link InfGraph}.
+ * Note that the method adds ontology headers to each subgraph of the specified graph, including itself.
+ * Also note that attempt to change {@link OntID OntID}
+ * will cause {@link OntJenaException.IllegalArgument}
+ * if the ontology is in some other ontologies' import closure.
+ * <p>
+ * This method can also be used to retrieve {@link OntModel} from the {@code repository}:
+ * it returns a new instance of {@link OntModel} wrapping the existing {@link UnionGraph}
+ * if it is present in the {@code repository}.
+ *
+ * @param graph {@link Graph}
+ * @param spec {@link OntSpecification}
+ * @param repository {@link GraphRepository}
+ * @return {@link OntModel}
+ */
+ public static OntModel createModel(Graph graph, OntSpecification spec, GraphRepository repository) {
+ Objects.requireNonNull(spec);
+ Objects.requireNonNull(repository);
+ Objects.requireNonNull(graph);
+ if (Graphs.dataGraphs(graph).anyMatch(it -> it instanceof InfGraph)) {
+ throw new IllegalArgumentException("InfGraph in the hierarchy detected");
+ }
+ OntUnionGraphRepository ontUnionGraphRepository = new OntUnionGraphRepository(
+ repository,
+ OntModelFactory::createUnionGraph,
+ OntModelFactory::createDefaultGraph,
+ /*ignoreUnresolvedImports*/ true);
+ UnionGraph union;
+ if (graph instanceof UnionGraph) {
+ union = (UnionGraph) graph;
+ Graphs.flatHierarchy((UnionGraph) graph).forEach(it -> {
+ Graphs.findOntologyNameNode(it.getBaseGraph()).orElseGet(() -> Graphs.createOntologyHeaderNode(it, null));
+ ontUnionGraphRepository.put(it);
+ });
+ } else {
+ Graphs.dataGraphs(graph).forEach(it -> {
+ String name = Graphs.findOntologyNameNode(it)
+ .orElseGet(() -> Graphs.createOntologyHeaderNode(it, null))
+ .toString();
+ repository.put(name, it);
+ });
+ union = ontUnionGraphRepository.put(Graphs.getPrimary(graph));
+ }
+ ReasonerFactory reasonerFactory = spec.getReasonerFactory();
+ if (reasonerFactory == null) {
+ return new OntGraphModelImpl(union, spec.getPersonality());
+ }
+ InfGraph inf = reasonerFactory.create(null).bind(union);
+ return new OntGraphModelImpl(inf, spec.getPersonality());
+ }
+
+ /**
+ * Finds {@link OntModel} in the {@code repository},
+ * returning {@code null} if there is no ontology with the specified {@code uri}.
+ * The method constructs new {@link OntModel} instance, wrapping the found {@link UnionGraph}.
+ *
+ * @param uri ontology name:
+ * object from the statement {@code <ont> owl:versionIri <name>} or
+ * subject from the statement {@code <name> rdf:type owl:Ontology}
+ * @param spec {@link OntSpecification}
+ * @param repository {@link GraphRepository}
+ * @return {@link OntModel} or {@code null} if there is no such ontology
+ */
+ public static OntModel getModelOrNull(String uri, OntSpecification spec, GraphRepository repository) {
+ return getModelOrNull(NodeFactory.createURI(Objects.requireNonNull(uri)), spec, repository);
+ }
+
+ /**
+ * Finds {@link OntModel} in the {@code repository},
+ * returning {@code null} if there is no ontology with the specified {@code name}.
+ * The method constructs new {@link OntModel} instance, wrapping the found {@link UnionGraph}.
+ *
+ * @param name {@link Node} ontology name, URI or blank
+ * @param spec {@link OntSpecification}
+ * @param repository {@link GraphRepository}
+ * @return {@link OntModel} or {@code null} if there is no such ontology
+ */
+ public static OntModel getModelOrNull(Node name, OntSpecification spec, GraphRepository repository) {
+ Objects.requireNonNull(spec);
+ Objects.requireNonNull(repository);
+ Objects.requireNonNull(name);
+ if (!name.isURI() && !name.isBlank()) {
+ throw new IllegalArgumentException("Ontology name must be URI or blank Node");
+ }
+ OntUnionGraphRepository ontUnionGraphRepository = new OntUnionGraphRepository(
+ repository,
+ OntModelFactory::createUnionGraph,
+ OntModelFactory::createDefaultGraph,
+ /*ignoreUnresolvedImports*/ true);
+ if (!ontUnionGraphRepository.contains(name)) {
+ return null;
+ }
+ UnionGraph union = ontUnionGraphRepository.get(name);
+ ReasonerFactory reasonerFactory = spec.getReasonerFactory();
+ if (reasonerFactory == null) {
+ return new OntGraphModelImpl(union, spec.getPersonality());
+ }
+ InfGraph inf = reasonerFactory.create(null).bind(union);
+ return new OntGraphModelImpl(inf, spec.getPersonality());
+
+ }
+
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntSpecification.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntSpecification.java
new file mode 100644
index 0000000000..1c1fcfc029
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/OntSpecification.java
@@ -0,0 +1,627 @@
+/*
+ * 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.jena.ontapi;
+
+import org.apache.jena.ontapi.common.OntConfig;
+import org.apache.jena.ontapi.common.OntConfigs;
+import org.apache.jena.ontapi.common.OntPersonalities;
+import org.apache.jena.ontapi.common.OntPersonality;
+import org.apache.jena.reasoner.ReasonerFactory;
+import org.apache.jena.reasoner.rulesys.OWLFBRuleReasonerFactory;
+import org.apache.jena.reasoner.rulesys.OWLMicroReasonerFactory;
+import org.apache.jena.reasoner.rulesys.OWLMiniReasonerFactory;
+import org.apache.jena.reasoner.rulesys.RDFSRuleReasonerFactory;
+import org.apache.jena.reasoner.transitiveReasoner.TransitiveReasonerFactory;
+
+import java.util.Objects;
+
+/**
+ * Encapsulates a description of the components of an ontology model.
+ * Contains OWL2, OWL1 and RDFS specifications:
+ * <ul>
+ * <li>OWL2 (DL & FULL): full support last version of OWL</li>
+ * <li>OWL2 (EL): OWL2 Existential Logic subset</li>
+ * <li>OWL2 (QL): OWL2 Query Language subset</li>
+ * <li>OWL2 (RL): OWL2 Rule Language subset</li>
+ * <li>OWL1 (DL & FULL): does not support some language construct from OWL2, such as {@code OntDataRange.UnionOf};
+ * supposed to be compatible with legacy Jena's OntModel</li>
+ * <li>OWL1 LITE: does not support some language construct from OWL2 and OWL1, such as {@code OntClass.UnionOf};
+ * supposed to be compatible with old Jena's OntModel</li>
+ * <li>RDFS: supports only RDFS language: rdf:Property, rdf:Class, rdfs:subClassOf, etc</li>
+ * </ul>
+ *
+ * @see <a href="https://www.w3.org/TR/owl2-syntax/">OWL v2</a>
+ * @see <a href="https://www.w3.org/TR/owl2-profiles/#OWL_2_EL">OWL 2 EL</a>
+ * @see <a href="https://www.w3.org/TR/owl2-profiles/#OWL_2_QL">OWL 2 QL</a>
+ * @see <a href="https://www.w3.org/TR/owl2-profiles/#OWL_2_RL">OWL 2 RL</a>
+ * @see <a href="https://www.w3.org/TR/2008/WD-owl11-syntax-20080108/">OWL v1.1</a>
+ * @see <a href="https://www.w3.org/TR/owl-guide/">OWL v1</a>
+ * @see <a href="https://www.w3.org/TR/2004/REC-owl-features-20040210/#s3">OWL1 Lite</a>
+ * @see org.apache.jena.ontology.OntModelSpec OntModelSpec - legacy Jena's OWL1 specifications
+ */
+@SuppressWarnings("ClassCanBeRecord")
+public class OntSpecification {
+
+ private static final OntPersonality OWL2_FULL_PERSONALITY =
+ OntPersonalities.OWL2_ONT_PERSONALITY()
+ .setBuiltins(OntPersonalities.OWL2_FULL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_NO_PUNNINGS)
+ .setConfig(OntConfigs.OWL2_CONFIG)
+ .build();
+
+ private static final OntPersonality OWL2_DL_PERSONALITY =
+ OntPersonalities.OWL2_ONT_PERSONALITY()
+ .setBuiltins(OntPersonalities.OWL2_FULL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_DL2_PUNNINGS)
+ .setConfig(OntConfigs.OWL2_CONFIG)
+ .build();
+
+ private static final OntPersonality OWL2_EL_PERSONALITY =
+ OntPersonalities.OWL2_EL_ONT_PERSONALITY()
+ .setBuiltins(OntPersonalities.OWL2_EL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_DL2_PUNNINGS)
+ .setConfig(OntConfigs.OWL2_EL_CONFIG)
+ .build();
+
+ private static final OntPersonality OWL2_QL_PERSONALITY =
+ OntPersonalities.OWL2_QL_ONT_PERSONALITY()
+ .setBuiltins(OntPersonalities.OWL2_QL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_DL2_PUNNINGS)
+ .setConfig(OntConfigs.OWL2_QL_CONFIG)
+ .build();
+
+ private static final OntPersonality OWL2_RL_PERSONALITY =
+ OntPersonalities.OWL2_RL_ONT_PERSONALITY()
+ .setBuiltins(OntPersonalities.OWL2_RL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_DL2_PUNNINGS)
+ .setConfig(OntConfigs.OWL2_RL_CONFIG)
+ .build();
+
+ private static final OntPersonality OWL1_DL_PERSONALITY =
+ OntPersonalities.OWL1_ONT_PERSONALITY()
+ .setBuiltins(OntPersonalities.OWL1_FULL_BUILTINS)
+ .setReserved(OntPersonalities.OWL1_RESERVED)
+ .setPunnings(OntPersonalities.OWL_DL1_PUNNINGS)
+ .setConfig(OntConfigs.OWL1_CONFIG)
+ .build();
+
+ private static final OntPersonality OWL1_FULL_PERSONALITY =
+ OntPersonalities.OWL1_ONT_PERSONALITY()
+ .setBuiltins(OntPersonalities.OWL1_FULL_BUILTINS)
+ .setReserved(OntPersonalities.OWL1_RESERVED)
+ .setPunnings(OntPersonalities.OWL_NO_PUNNINGS)
+ .setConfig(OntConfigs.OWL1_CONFIG)
+ .build();
+
+ private static final OntPersonality OWL1_LITE_PERSONALITY =
+ OntPersonalities.OWL1_LITE_ONT_PERSONALITY()
+ .setBuiltins(OntPersonalities.OWL1_LITE_BUILTINS)
+ .setReserved(OntPersonalities.OWL1_RESERVED)
+ .setPunnings(OntPersonalities.OWL_DL1_PUNNINGS)
+ .setConfig(OntConfigs.OWL1_LITE_CONFIG)
+ .build();
+
+ private static final OntPersonality RDFS_PERSONALITY =
+ OntPersonalities.RDFS_ONT_PERSONALITY()
+ .setBuiltins(OntPersonalities.RDFS_BUILTINS)
+ .setReserved(OntPersonalities.RDFS_RESERVED)
+ .setPunnings(OntPersonalities.OWL_NO_PUNNINGS)
+ .setConfig(OntConfigs.RDFS_CONFIG)
+ .build();
+
+ /*
+ * *****************************************************************************************************************
+ * OWL 2 DL
+ * *****************************************************************************************************************
+ */
+
+ /**
+ * A specification for OWL2 ontology models that are stored in memory
+ * and use fast but incomplete builtin OWL inference engine for additional entailments
+ * that handles hierarchy.
+ * It supports {@code rdfs:subClassOf}, {@code rdfs:subPropertyOf} and class-individuals hierarchy,
+ * otherwise it behaves like a regular {@link #OWL2_DL_MEM}.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_DL_MEM_RDFS_INF
+ */
+ public static final OntSpecification OWL2_DL_MEM_BUILTIN_INF = new OntSpecification(
+ OntPersonalities.OWL2_ONT_PERSONALITY()
+ .setBuiltins(OntPersonalities.OWL2_FULL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_DL2_PUNNINGS)
+ .setConfig(OntConfigs.OWL2_CONFIG.setTrue(OntModelControls.USE_BUILTIN_HIERARCHY_SUPPORT))
+ .build(),
+ null
+ );
+
+ /**
+ * A specification for OWL2 DL ontology models
+ * that are stored in memory and do no additional entailment reasoning.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_DL_MEM
+ */
+ public static final OntSpecification OWL2_DL_MEM = new OntSpecification(
+ OWL2_DL_PERSONALITY, null
+ );
+
+ /**
+ * A specification for OWL2 DL ontology models
+ * that are stored in memory and use the RDFS inferencer for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_DL_MEM_RDFS_INF
+ */
+ public static final OntSpecification OWL2_DL_MEM_RDFS_INF = new OntSpecification(
+ OWL2_DL_PERSONALITY, RDFSRuleReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 DL ontology models
+ * that are stored in memory and use the transitive inferencer for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_DL_MEM_TRANS_INF
+ */
+ public static final OntSpecification OWL2_DL_MEM_TRANS_INF = new OntSpecification(
+ OWL2_DL_PERSONALITY, TransitiveReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 DL ontology models
+ * that are stored in memory and use the OWL rules inference engine for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_DL_MEM_RULE_INF
+ */
+ public static final OntSpecification OWL2_DL_MEM_RULES_INF = new OntSpecification(
+ OWL2_DL_PERSONALITY, OWLFBRuleReasonerFactory.theInstance()
+ );
+
+ /*
+ * *****************************************************************************************************************
+ * OWL 2 FULL
+ * *****************************************************************************************************************
+ */
+
+ /**
+ * A specification for Ontology models that are stored in memory and do no additional entailment reasoning.
+ * Full support for the OWL v2 specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM
+ */
+ public static final OntSpecification OWL2_FULL_MEM = new OntSpecification(
+ OWL2_FULL_PERSONALITY, null
+ );
+
+ /**
+ * A specification for OWL2 models that are stored in memory and use the RDFS inferencer for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_RDFS_INF
+ */
+ public static final OntSpecification OWL2_FULL_MEM_RDFS_INF = new OntSpecification(
+ OWL2_FULL_PERSONALITY, RDFSRuleReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 models that are stored in memory and use the transitive inferencer for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_TRANS_INF
+ */
+ public static final OntSpecification OWL2_FULL_MEM_TRANS_INF = new OntSpecification(
+ OWL2_FULL_PERSONALITY, TransitiveReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 ontology models
+ * that are stored in memory and use the OWL rules inference engine for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_RULE_INF
+ */
+ public static final OntSpecification OWL2_FULL_MEM_RULES_INF = new OntSpecification(
+ OWL2_FULL_PERSONALITY, OWLFBRuleReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 ontology models
+ * that are stored in memory and use the micro OWL rules inference engine for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_MICRO_RULE_INF
+ */
+ public static final OntSpecification OWL2_FULL_MEM_MICRO_RULES_INF = new OntSpecification(
+ OWL2_FULL_PERSONALITY, OWLMicroReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 ontology models
+ * that are stored in memory and use the mini OWL rules inference engine for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_MINI_RULE_INF
+ */
+ public static final OntSpecification OWL2_FULL_MEM_MINI_RULES_INF = new OntSpecification(
+ OWL2_FULL_PERSONALITY, OWLMiniReasonerFactory.theInstance()
+ );
+
+ /*
+ * *****************************************************************************************************************
+ * OWL 2 EL
+ * *****************************************************************************************************************
+ */
+
+ /**
+ * A specification for OWL2 EL Ontology models that are stored in memory and do no additional entailment reasoning.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM
+ */
+ public static final OntSpecification OWL2_EL_MEM = new OntSpecification(
+ OWL2_EL_PERSONALITY, null
+ );
+
+ /**
+ * A specification for OWL2 EL models that are stored in memory
+ * and use the RDFS inferencer for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_RDFS_INF
+ */
+ public static final OntSpecification OWL2_EL_MEM_RDFS_INF = new OntSpecification(
+ OWL2_EL_PERSONALITY, RDFSRuleReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 EL models that are stored in memory
+ * and use the transitive inferencer for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_TRANS_INF
+ */
+ public static final OntSpecification OWL2_EL_MEM_TRANS_INF = new OntSpecification(
+ OWL2_EL_PERSONALITY, TransitiveReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 EL ontology models
+ * that are stored in memory and use the OWL rules inference engine for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_RULE_INF
+ */
+ public static final OntSpecification OWL2_EL_MEM_RULES_INF = new OntSpecification(
+ OWL2_EL_PERSONALITY, OWLFBRuleReasonerFactory.theInstance()
+ );
+
+ /*
+ * *****************************************************************************************************************
+ * OWL 2 QL
+ * *****************************************************************************************************************
+ */
+
+ /**
+ * A specification for OWL2 QL Ontology models that are stored in memory and do no additional entailment reasoning.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM
+ */
+ public static final OntSpecification OWL2_QL_MEM = new OntSpecification(
+ OWL2_QL_PERSONALITY, null
+ );
+
+ /**
+ * A specification for OWL2 QL models that are stored in memory
+ * and use the RDFS inferencer for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_RDFS_INF
+ */
+ public static final OntSpecification OWL2_QL_MEM_RDFS_INF = new OntSpecification(
+ OWL2_QL_PERSONALITY, RDFSRuleReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 QL models that are stored in memory
+ * and use the transitive inferencer for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_TRANS_INF
+ */
+ public static final OntSpecification OWL2_QL_MEM_TRANS_INF = new OntSpecification(
+ OWL2_QL_PERSONALITY, TransitiveReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 QL ontology models
+ * that are stored in memory and use the OWL rules inference engine for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_RULE_INF
+ */
+ public static final OntSpecification OWL2_QL_MEM_RULES_INF = new OntSpecification(
+ OWL2_QL_PERSONALITY, OWLFBRuleReasonerFactory.theInstance()
+ );
+
+ /*
+ * *****************************************************************************************************************
+ * OWL 2 RL
+ * *****************************************************************************************************************
+ */
+
+ /**
+ * A specification for OWL2 RL Ontology models that are stored in memory and do no additional entailment reasoning.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM
+ */
+ public static final OntSpecification OWL2_RL_MEM = new OntSpecification(
+ OWL2_RL_PERSONALITY, null
+ );
+
+ /**
+ * A specification for OWL2 RL models that are stored in memory
+ * and use the RDFS inferencer for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_RDFS_INF
+ */
+ public static final OntSpecification OWL2_RL_MEM_RDFS_INF = new OntSpecification(
+ OWL2_RL_PERSONALITY, RDFSRuleReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 RL models that are stored in memory
+ * and use the transitive inferencer for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_TRANS_INF
+ */
+ public static final OntSpecification OWL2_RL_MEM_TRANS_INF = new OntSpecification(
+ OWL2_RL_PERSONALITY, TransitiveReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL2 RL ontology models
+ * that are stored in memory and use the OWL rules inference engine for additional entailments.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_RULE_INF
+ */
+ public static final OntSpecification OWL2_RL_MEM_RULES_INF = new OntSpecification(
+ OWL2_RL_PERSONALITY, OWLFBRuleReasonerFactory.theInstance()
+ );
+
+ /*
+ * *****************************************************************************************************************
+ * OWL 1 DL
+ * *****************************************************************************************************************
+ */
+
+ /**
+ * A specification for OWL1 DL ontology models
+ * that are stored in memory and do no additional entailment reasoning.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL DL v1.1 specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_DL_MEM
+ */
+ public static final OntSpecification OWL1_DL_MEM = new OntSpecification(
+ OWL1_DL_PERSONALITY, null
+ );
+
+ /**
+ * A specification for OWL1 DL ontology models
+ * that are stored in memory and use the RDFS inferencer for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1.1 specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_DL_MEM_RDFS_INF
+ */
+ public static final OntSpecification OWL1_DL_MEM_RDFS_INF = new OntSpecification(
+ OWL1_DL_PERSONALITY, RDFSRuleReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL1 DL ontology models
+ * that are stored in memory and use the transitive inferencer for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1.1 specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_DL_MEM_TRANS_INF
+ */
+ public static final OntSpecification OWL1_DL_MEM_TRANS_INF = new OntSpecification(
+ OWL1_DL_PERSONALITY, TransitiveReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL1 DL ontology models
+ * that are stored in memory and use the OWL rules inference engine for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1.1 specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_DL_MEM_RULE_INF
+ */
+ public static final OntSpecification OWL1_DL_MEM_RULES_INF = new OntSpecification(
+ OWL1_DL_PERSONALITY, OWLFBRuleReasonerFactory.theInstance()
+ );
+
+ /*
+ * *****************************************************************************************************************
+ * OWL 1 FULL
+ * *****************************************************************************************************************
+ */
+
+ /**
+ * A specification for OWL1 ontology models
+ * that are stored in memory and do no additional entailment reasoning.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1.1 specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM
+ */
+ public static final OntSpecification OWL1_FULL_MEM = new OntSpecification(
+ OWL1_FULL_PERSONALITY, null
+ );
+
+ /**
+ * A specification for OWL1 ontology models
+ * that are stored in memory and use the RDFS inferencer for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1.1 specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_RDFS_INF
+ */
+ public static final OntSpecification OWL1_FULL_MEM_RDFS_INF = new OntSpecification(
+ OWL1_FULL_PERSONALITY, RDFSRuleReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL1 ontology models
+ * that are stored in memory and use the transitive inferencer for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1.1 specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_TRANS_INF
+ */
+ public static final OntSpecification OWL1_FULL_MEM_TRANS_INF = new OntSpecification(
+ OWL1_FULL_PERSONALITY, TransitiveReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL1 ontology models
+ * that are stored in memory and use the OWL rules inference engine for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1.1 specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_RULE_INF
+ */
+ public static final OntSpecification OWL1_FULL_MEM_RULES_INF = new OntSpecification(
+ OWL1_FULL_PERSONALITY, OWLFBRuleReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL1 ontology models
+ * that are stored in memory and use the micro OWL rules inference engine for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1.1 specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_MICRO_RULE_INF
+ */
+ public static final OntSpecification OWL1_FULL_MEM_MICRO_RULES_INF = new OntSpecification(
+ OWL1_FULL_PERSONALITY, OWLMicroReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL1 ontology models
+ * that are stored in memory and use the mini OWL rules inference engine for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1.1 specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_MEM_MINI_RULE_INF
+ */
+ public static final OntSpecification OWL1_FULL_MEM_MINI_RULES_INF = new OntSpecification(
+ OWL1_FULL_PERSONALITY, OWLMiniReasonerFactory.theInstance()
+ );
+
+ /*
+ * *****************************************************************************************************************
+ * OWL 1 LITE
+ * *****************************************************************************************************************
+ */
+
+ /**
+ * A specification for OWL1 Lite ontology models
+ * that are stored in memory and do no additional entailment reasoning.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1 Lite specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_LITE_MEM
+ */
+ public static final OntSpecification OWL1_LITE_MEM = new OntSpecification(
+ OWL1_LITE_PERSONALITY, null
+ );
+
+ /**
+ * A specification for OWL1 Lite ontology models
+ * that are stored in memory and use the RDFS inferencer for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1 Lite specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_LITE_MEM_RDFS_INF
+ */
+ public static final OntSpecification OWL1_LITE_MEM_RDFS_INF = new OntSpecification(
+ OWL1_LITE_PERSONALITY, RDFSRuleReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL1 Lite ontology models
+ * that are stored in memory and use the transitive inferencer for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1 Lite specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_LITE_MEM_TRANS_INF
+ */
+ public static final OntSpecification OWL1_LITE_MEM_TRANS_INF = new OntSpecification(
+ OWL1_LITE_PERSONALITY, TransitiveReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for OWL1 Lite ontology models
+ * that are stored in memory and use the OWL rules inference engine for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of OWL v1 Lite specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#OWL_LITE_MEM_RULES_INF
+ */
+ public static final OntSpecification OWL1_LITE_MEM_RULES_INF = new OntSpecification(
+ OWL1_LITE_PERSONALITY, OWLFBRuleReasonerFactory.theInstance()
+ );
+
+ /*
+ * *****************************************************************************************************************
+ * RDFS
+ * *****************************************************************************************************************
+ */
+
+ /**
+ * A specification for RDFS models that are stored in memory and do no additional entailment reasoning.
+ * Supposed to be a replacement for the original legacy Jena interpretation of RDFS specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#RDFS_MEM
+ */
+ public static final OntSpecification RDFS_MEM = new OntSpecification(
+ RDFS_PERSONALITY, null
+ );
+
+ /**
+ * A specification for RDFS ontology models that are stored in memory
+ * and use the RDFS inferencer for additional entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of RDFS specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#RDFS_MEM_RDFS_INF
+ */
+ public static final OntSpecification RDFS_MEM_RDFS_INF = new OntSpecification(
+ RDFS_PERSONALITY, RDFSRuleReasonerFactory.theInstance()
+ );
+
+ /**
+ * A specification for RDFS ontology models that are stored in memory
+ * and use the transitive reasoner for entailments.
+ * Supposed to be a replacement for the original legacy Jena interpretation of RDFS specification.
+ *
+ * @see org.apache.jena.ontology.OntModelSpec#RDFS_MEM_TRANS_INF
+ */
+ public static final OntSpecification RDFS_MEM_TRANS_INF = new OntSpecification(
+ RDFS_PERSONALITY, TransitiveReasonerFactory.theInstance()
+ );
+
+
+ private final OntPersonality personality;
+ private final ReasonerFactory reasonerFactory;
+
+ public OntSpecification(OntPersonality personality, ReasonerFactory reasonerFactory) {
+ this.personality = Objects.requireNonNull(personality);
+ this.reasonerFactory = reasonerFactory;
+ }
+
+ public OntPersonality getPersonality() {
+ return personality;
+ }
+
+ public ReasonerFactory getReasonerFactory() {
+ return reasonerFactory;
+ }
+
+ public OntConfig getConfig() {
+ return personality.getConfig();
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/UnionGraph.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/UnionGraph.java
new file mode 100644
index 0000000000..0d847d1a6f
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/UnionGraph.java
@@ -0,0 +1,237 @@
+/*
+ * 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.jena.ontapi;
+
+import org.apache.jena.graph.Graph;
+import org.apache.jena.graph.GraphEventManager;
+import org.apache.jena.graph.GraphListener;
+import org.apache.jena.graph.Node;
+import org.apache.jena.graph.Triple;
+import org.apache.jena.shared.PrefixMapping;
+
+import java.util.stream.Stream;
+
+/**
+ * Hierarchical graph.
+ * <p>
+ * It consists of two parts:
+ * a {@link #getBaseGraph() base graph} and an {@link #subGraphs() sub-graphs} collection.
+ * A hierarchical UnionGraph may have parents, called super-graphs ({@link #superGraphs()}.
+ * Underlying sub-graphs are only used for searching; modify operations are performed only on the base graph.
+ * This graph allows building graph hierarchy which can be used to link different models.
+ * Also, it allows recursion, that is, it can contain itself somewhere in the hierarchy.
+ * The {@link PrefixMapping} of this graph is taken from the base graph,
+ * and, therefore, any changes in it reflect both the base and this graph.
+ * <p>
+ * Well-formed OWL ontology {@code UnionGraph} is expected to contain {@link UnionGraph}s as subgraphs,
+ * where graphs also connected by {@code owl:imports} relationships.
+ */
+@SuppressWarnings({"WeakerAccess"})
+public interface UnionGraph extends Graph {
+
+ @Override
+ EventManager getEventManager();
+
+ /**
+ * Answers {@code true} iff this graph is distinct,
+ * which means that the method {@link Graph#find(Triple)} does not produce duplicates.
+ *
+ * @return boolean
+ */
+ boolean isDistinct();
+
+ /**
+ * Returns the base (primary) data graph.
+ *
+ * @return {@link Graph}, not {@code null}
+ */
+ Graph getBaseGraph();
+
+ /**
+ * Answers {@code true} iff this {@code UnionGraph} has sub-graphs.
+ *
+ * @return boolean
+ */
+ boolean hasSubGraph();
+
+ /**
+ * Lists all sub-graphs.
+ * The {@link #getBaseGraph() base graph} is not included in the result.
+ *
+ * @return {@link Stream} of sub-{@link Graph graph}s
+ */
+ Stream<Graph> subGraphs();
+
+ /**
+ * Lists all parent graphs.
+ * The {@link #getBaseGraph() base graph} is not included in the result.
+ *
+ * @return {@link Stream} of sub-{@link UnionGraph graph}s
+ */
+ Stream<UnionGraph> superGraphs();
+
+ /**
+ * Adds the specified graph to the underlying graph collection.
+ * If the specified graph is {@link UnionGraph}, this graph becomes a super graph (see {@link #superGraphs()})
+ *
+ * @param graph {@link Graph}, not {@code null}
+ * @return this instance
+ */
+ UnionGraph addSubGraph(Graph graph);
+
+ /**
+ * Removes the specified graph from the underlying graph collection.
+ *
+ * @param graph {@link Graph}, not {@code null}
+ * @return this instance
+ */
+ UnionGraph removeSubGraph(Graph graph);
+
+ /**
+ * Adds the specified graph to the underlying graph collection if it is absent.
+ *
+ * @param graph {@link Graph}, not {@code null}
+ * @return this instance
+ */
+ default UnionGraph addSubGraphIfAbsent(Graph graph) {
+ if (!contains(graph)) {
+ addSubGraph(graph);
+ }
+ return this;
+ }
+
+ /**
+ * Answers {@code true} iff this {@code UnionGraph} contains the specified graph as a subgraph.
+ *
+ * @param graph {@link Graph} to test
+ * @return boolean
+ */
+ default boolean contains(Graph graph) {
+ return subGraphs().anyMatch(it -> it.equals(graph));
+ }
+
+ /**
+ * An enhanced {@link GraphEventManager Jena Graph Event Manager} and {@link Listener}s.
+ */
+ interface EventManager extends GraphEventManager, Listener {
+
+ /**
+ * Turns off all listeners.
+ */
+ void off();
+
+ /**
+ * Turns on all listeners.
+ */
+ void on();
+
+ /**
+ * Lists all encapsulated listeners.
+ *
+ * @return Stream of {@link GraphListener}s
+ */
+ Stream<GraphListener> listeners();
+
+ /**
+ * Lists all encapsulated listeners for the given type.
+ *
+ * @param type {@link L}
+ * @return Stream of {@link GraphListener}s
+ * @param <L> {@code Class}-type of {@link GraphListener}
+ */
+ @SuppressWarnings("unchecked")
+ default <L extends GraphListener> Stream<L> listeners(Class<L> type) {
+ return listeners().filter(it -> type.isAssignableFrom(it.getClass())).map(it -> (L) it);
+ }
+ }
+
+ interface Listener extends GraphListener {
+
+ /**
+ * Called before {@link UnionGraph#add(Node, Node, Node)} & {@link UnionGraph#add(Triple)}.
+ *
+ * @param graph {@link UnionGraph}
+ * @param triple {@link Triple}
+ */
+ void onAddTriple(UnionGraph graph, Triple triple);
+
+ /**
+ * Called before
+ * {@link UnionGraph#delete(Node, Node, Node)}
+ * & {@link UnionGraph#delete(Triple)}
+ * & {@link UnionGraph#remove(Node, Node, Node)}.
+ *
+ * @param graph {@link UnionGraph}
+ * @param triple {@link Triple}
+ */
+ void onDeleteTriple(UnionGraph graph, Triple triple);
+
+ /**
+ * Called before {@link UnionGraph#clear()}.
+ *
+ * @param graph {@link UnionGraph}
+ */
+ void onClear(UnionGraph graph);
+
+ /**
+ * Called before {@link UnionGraph#addSubGraph(Graph)}.
+ *
+ * @param graph {@link UnionGraph}
+ * @param subGraph {@link Graph}
+ */
+ void onAddSubGraph(UnionGraph graph, Graph subGraph);
+
+ /**
+ * Called before {@link UnionGraph#removeSubGraph(Graph)}.
+ *
+ * @param graph {@link Graph}
+ * @param subGraph {@link Graph}
+ */
+ void onRemoveSubGraph(UnionGraph graph, Graph subGraph);
+
+ /**
+ * Called after {@link UnionGraph#addSubGraph(Graph)}.
+ * Note it differs from {@link #notifyAddGraph(Graph, Graph)},
+ * which is called when RDF data added into the {@link UnionGraph#getBaseGraph()}.
+ *
+ * @param graph {@link UnionGraph}
+ * @param subGraph {@link Graph}
+ */
+ void notifySubGraphAdded(UnionGraph graph, Graph subGraph);
+
+ /**
+ * Called after {@link UnionGraph#addSubGraph(Graph)}.
+ *
+ * @param graph {@link UnionGraph}
+ * @param superGraph {@link UnionGraph}
+ */
+ void notifySuperGraphAdded(UnionGraph graph, UnionGraph superGraph);
+
+ /**
+ * Called after {@link UnionGraph#removeSubGraph(Graph)}.
+ * Note it differs from {@link #notifyDeleteGraph(Graph, Graph)},
+ * which is called when RDF data is added into the {@link UnionGraph#getBaseGraph()}.
+ *
+ * @param graph {@link Graph}
+ * @param subGraph {@link Graph}
+ */
+ void notifySubGraphRemoved(UnionGraph graph, Graph subGraph);
+
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/BaseEnhNodeFactoryImpl.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/BaseEnhNodeFactoryImpl.java
new file mode 100644
index 0000000000..5c51d15543
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/BaseEnhNodeFactoryImpl.java
@@ -0,0 +1,104 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.enhanced.EnhNode;
+import org.apache.jena.enhanced.Implementation;
+import org.apache.jena.graph.Node;
+
+/**
+ * An extended {@link Implementation} factory,
+ * the base class for any {@link EnhNodeFactory factories} to produce
+ * {@link OntObject Ontology Object}s.
+ * Used to bind implementation (node) and interface.
+ * Also, in addition to the standard jena methods,
+ * this implementation includes nodes' search and graph transformation functionality.
+ */
+public abstract class BaseEnhNodeFactoryImpl extends Implementation implements EnhNodeFactory {
+
+ protected static EnhNode safeWrap(Node n, EnhGraph g, Iterable<EnhNodeFactory> factories) {
+ for (EnhNodeFactory f : factories) {
+ EnhNode r = safeWrap(n, g, f);
+ if (r != null) return r;
+ }
+ return null;
+ }
+
+ protected static EnhNode safeWrap(Node n, EnhGraph g, EnhNodeFactory f) {
+ try {
+ return f.wrap(n, g);
+ } catch (OntJenaException.Conversion c) {
+ return null;
+ }
+ }
+
+ protected static boolean canWrap(Node node, EnhGraph eg, EnhNodeFactory... factories) {
+ for (EnhNodeFactory f : factories) {
+ if (f.canWrap(node, eg)) return true;
+ }
+ return false;
+ }
+
+ protected static boolean canWrap(Node node, EnhGraph eg, Iterable<EnhNodeFactory> factories) {
+ for (EnhNodeFactory f : factories) {
+ if (f.canWrap(node, eg)) return true;
+ }
+ return false;
+ }
+
+ protected static EnhNode wrap(Node node, EnhGraph eg, OntJenaException.Conversion ex, EnhNodeFactory... factories) {
+ for (EnhNodeFactory f : factories) {
+ try {
+ return f.wrap(node, eg);
+ } catch (OntJenaException.Conversion c) {
+ ex.addSuppressed(c);
+ }
+ }
+ throw ex;
+ }
+
+ protected static EnhNode wrap(Node node, EnhGraph eg, OntJenaException.Conversion ex, Iterable<EnhNodeFactory> factories) {
+ for (EnhNodeFactory f : factories) {
+ try {
+ return f.wrap(node, eg);
+ } catch (OntJenaException.Conversion c) {
+ ex.addSuppressed(c);
+ }
+ }
+ throw ex;
+ }
+
+ /**
+ * Creates a new {@link EnhNode} wrapping the given {@link Node} node in the context of the graph {@link EnhGraph}.
+ *
+ * @param node the node to be wrapped
+ * @param eg the graph containing the node
+ * @return A new enhanced node which wraps node but presents the interface(s) that this factory encapsulates.
+ * @throws OntJenaException.Conversion in case wrapping is impossible
+ */
+ @Override
+ public EnhNode wrap(Node node, EnhGraph eg) {
+ if (!canWrap(node, eg))
+ throw new OntJenaException.Conversion("Can't wrap node " + node + ". Use direct factory.");
+ return createInstance(node, eg);
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/CommonEnhNodeFactoryImpl.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/CommonEnhNodeFactoryImpl.java
new file mode 100644
index 0000000000..5bfa2990e0
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/CommonEnhNodeFactoryImpl.java
@@ -0,0 +1,101 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.enhanced.EnhNode;
+import org.apache.jena.graph.Node;
+import org.apache.jena.util.iterator.ExtendedIterator;
+
+import java.util.Objects;
+
+/**
+ * Default implementation of {@link EnhNodeFactory}.
+ * This is a kind of constructor that consists of three modules:
+ * <ul>
+ * <li>{@link EnhNodeProducer} for initialization and physical creation a node {@link EnhNode} in the graph {@link EnhGraph}.</li>
+ * <li>{@link EnhNodeFilter} to test the presence of a node in the graph.</li>
+ * <li>{@link EnhNodeFinder} to search for nodes in the graph.</li>
+ * </ul>
+ */
+public class CommonEnhNodeFactoryImpl extends BaseEnhNodeFactoryImpl {
+ private final EnhNodeProducer maker;
+ private final EnhNodeFinder finder;
+ private final EnhNodeFilter filter;
+
+ public CommonEnhNodeFactoryImpl(EnhNodeProducer maker, EnhNodeFinder finder, EnhNodeFilter filter) {
+ this.maker = Objects.requireNonNull(maker, "Null maker.");
+ this.finder = Objects.requireNonNull(finder, "Null finder.");
+ this.filter = Objects.requireNonNull(filter, "Null filter.");
+ }
+
+ public EnhNodeProducer getMaker() {
+ return maker;
+ }
+
+ public EnhNodeFinder getFinder() {
+ return finder;
+ }
+
+ public EnhNodeFilter getFilter() {
+ return filter;
+ }
+
+ @Override
+ public EnhNode wrap(Node node, EnhGraph eg) {
+ if (!canWrap(node, eg)) {
+ throw new OntJenaException.Conversion(
+ String.format("Can't wrap node to impl %s. Node: %s", maker.targetName(), OntEnhNodeFactories.toPrintString(node, eg))
+ );
+ }
+ return createInstance(node, eg);
+ }
+
+ @Override
+ public boolean canWrap(Node node, EnhGraph eg) {
+ return filter.test(node, eg);
+ }
+
+ @Override
+ public EnhNode createInGraph(Node node, EnhGraph eg) {
+ if (!canCreateInGraph(node, eg)) {
+ throw new OntJenaException.Creation(
+ String.format("Can't modify graph for impl %s. Node: %s", maker.targetName(), OntEnhNodeFactories.toPrintString(node, eg))
+ );
+ }
+ maker.doInsert(node, eg);
+ return createInstance(node, eg);
+ }
+
+ @Override
+ public boolean canCreateInGraph(Node node, EnhGraph eg) {
+ return maker.canInsert(node, eg);
+ }
+
+ @Override
+ public ExtendedIterator<EnhNode> iterator(EnhGraph eg) {
+ return finder.restrict(filter).iterator(eg).mapWith(n -> maker.newInstance(n, eg));
+ }
+
+ @Override
+ public EnhNode createInstance(Node node, EnhGraph eg) {
+ return maker.newInstance(node, eg);
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/CompositeEnhNodeFactoryImpl.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/CompositeEnhNodeFactoryImpl.java
new file mode 100644
index 0000000000..903e6878a5
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/CompositeEnhNodeFactoryImpl.java
@@ -0,0 +1,111 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.ontapi.utils.Iterators;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.enhanced.EnhNode;
+import org.apache.jena.graph.Node;
+import org.apache.jena.util.iterator.ExtendedIterator;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * A {@link EnhNodeFactory Ontology Object Factory} implementation to combine several other factories.
+ */
+@SuppressWarnings("WeakerAccess")
+public class CompositeEnhNodeFactoryImpl extends BaseEnhNodeFactoryImpl {
+ private final List<EnhNodeFactory> factories;
+ private final EnhNodeFinder finder;
+ private final EnhNodeFilter fittingFilter;
+
+ /**
+ * Creates a factory instance.
+ *
+ * @param finder {@link EnhNodeFinder}, optional, if {@code null} then uses only provided sub-factories to search
+ * @param fittingFilter {@link EnhNodeFilter}, optional, to trim searching
+ * @param factories array of factories to combine, must not be {@code null} or empty
+ */
+ public CompositeEnhNodeFactoryImpl(EnhNodeFinder finder, EnhNodeFilter fittingFilter, EnhNodeFactory... factories) {
+ this.finder = finder;
+ this.fittingFilter = fittingFilter;
+ if (factories.length == 0)
+ throw new IllegalArgumentException("Empty factory array");
+ this.factories = unbend(factories);
+ }
+
+ private static List<EnhNodeFactory> unbend(EnhNodeFactory... factories) {
+ return Arrays.stream(factories)
+ .flatMap(f -> f instanceof CompositeEnhNodeFactoryImpl ? ((CompositeEnhNodeFactoryImpl) f).factories.stream() : Stream.of(f))
+ .collect(Collectors.toList());
+ }
+
+ @Override
+ public EnhNode wrap(Node node, EnhGraph eg) {
+ EnhNode res = createInstance(node, eg);
+ if (res != null) return res;
+ throw new OntJenaException.Conversion(String.format(
+ "Can't wrap node %s. Use direct factory.", OntEnhNodeFactories.toPrintString(node, eg))
+ );
+ }
+
+ @Override
+ public boolean canWrap(Node node, EnhGraph eg) {
+ return !(fittingFilter != null && !fittingFilter.test(node, eg))
+ && Iterators.anyMatch(listFactories(), f -> f.canWrap(node, eg));
+ }
+
+ @Override
+ public EnhNode createInstance(Node node, EnhGraph eg) {
+ if (fittingFilter != null && !fittingFilter.test(node, eg)) return null;
+ return Iterators.findFirst(Iterators.filter(listFactories(), f -> f.canWrap(node, eg))
+ .mapWith(f -> f.createInstance(node, eg))).orElse(null);
+ }
+
+ @Override
+ public ExtendedIterator<EnhNode> iterator(EnhGraph eg) {
+ if (finder != null) {
+ return finder.iterator(eg).mapWith(n -> createInstance(n, eg)).filterDrop(Objects::isNull);
+ }
+ return Iterators.distinct(Iterators.flatMap(listFactories(), f -> f.iterator(eg)));
+ }
+
+ public EnhNodeFinder getFinder() {
+ return finder;
+ }
+
+ public EnhNodeFilter getFilter() {
+ return fittingFilter;
+ }
+
+ /**
+ * Lists all sub-factories.
+ *
+ * @return {@link ExtendedIterator} of {@link EnhNodeFactory}
+ */
+ public ExtendedIterator<? extends EnhNodeFactory> listFactories() {
+ return Iterators.create(factories);
+ }
+
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeFactory.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeFactory.java
new file mode 100644
index 0000000000..dbd6492ea1
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeFactory.java
@@ -0,0 +1,151 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.ontapi.utils.Graphs;
+import org.apache.jena.ontapi.utils.Iterators;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.enhanced.EnhNode;
+import org.apache.jena.enhanced.Implementation;
+import org.apache.jena.graph.Graph;
+import org.apache.jena.graph.Node;
+import org.apache.jena.ontapi.model.OntModel;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.util.iterator.ExtendedIterator;
+
+import java.util.stream.Stream;
+
+/**
+ * An {@link EnhNode} factory abstraction,
+ * that is an ONT-API analogue of the {@link Implementation Jena Implementation Factory}.
+ * Used to bind a concrete implementation (i.e. {@link EnhNode enhanced node}) and
+ * an interface ({@link OntObject OWL Object}) with a {@link Node Graph Node}.
+ * It is a part of {@link OntPersonality} mechanism to manipulate
+ * {@link OntModel OWL2 RDF-model} objects (which happens through {@link OntEnhGraph}).
+ * Also note, explicit links between different {@link EnhNodeFactory} factories are undesirable
+ * (for more details see {@link OntObjectPersonalityBuilder#add(Class, EnhNodeFactory)} and
+ * {@link OntEnhGraph}).
+ * <p>
+ * TODO: consider a possibility to replace {@link EnhGraph} with {@link OntEnhGraph}.
+ *
+ * @see OntPersonality
+ * @see OntEnhGraph
+ */
+public interface EnhNodeFactory {
+
+ /**
+ * Represents the given implementation factory as {@link Implementation Jena Implementation Factory}.
+ *
+ * @param f {@link OntPersonality}, not {@code null}
+ * @return {@link Implementation}, not {@code null}
+ * @throws OntJenaException in case the conversion is not possible
+ * @see OntPersonality#asJenaPersonality(OntPersonality)
+ * @see OntEnhGraph#asPersonalityModel(EnhGraph)
+ */
+ static Implementation asJenaImplementation(EnhNodeFactory f) throws OntJenaException {
+ if (f instanceof Implementation) {
+ return (Implementation) f;
+ }
+ return OntJenaException.TODO("The given EnhNodeFactory is not an instance of Jena Implementation.");
+ }
+
+ /**
+ * Returns an {@link ExtendedIterator Extended Iterator} over the {@link Node node}s found in the {@link EnhGraph}
+ * in the form of {@link EnhNode} with the interface that this factory encapsulates.
+ * It is assumed that the returned iterator is distinct (does not answer with duplicates).
+ * At least, it must be distinct if the {@code EnhGraph} encapsulates the distinct graph
+ * (see also {@link Graphs#isDistinct(Graph)}).
+ *
+ * @param eg {@link EnhGraph}
+ * @return {@link ExtendedIterator} of {@link EnhNode}s
+ */
+ ExtendedIterator<EnhNode> iterator(EnhGraph eg);
+
+ /**
+ * Checks that the wrapping ({@code node}, {@code eg}) would succeed.
+ *
+ * @param node node the node to test for suitability
+ * @param eg the enhanced graph the node appears in
+ * @return {@code true} iff the {@code node} can represent the type in the graph
+ */
+ boolean canWrap(Node node, EnhGraph eg);
+
+ /**
+ * Wraps the given pair of {@link Node node} and {@link EnhGraph graph} to a fresh {@link EnhNode} instance
+ * without any checking or throwing any exception.
+ * Some implementations may return {@code null} if the {@link #canWrap(Node, EnhGraph)} returns {@code false}.
+ * Unlike the method {@link #createInGraph(Node, EnhGraph)}, this method does not make any changes to the graph.
+ *
+ * @param node {@link Node}, not {@code null}
+ * @param eg {@link EnhGraph}, not {@code null}
+ * @return {@link EnhNode} or {@code null}
+ */
+ EnhNode createInstance(Node node, EnhGraph eg);
+
+ /**
+ * Creates a new {@link EnhNode} wrapping the given {@link Node} node in the context of the graph {@link EnhGraph}.
+ * Unlike the method {@link #createInGraph(Node, EnhGraph)}, this method does not make any changes to the graph.
+ *
+ * @param node {@link Node}, the node to be wrapped as {@link EnhNode}, not {@code null}
+ * @param eg {@link EnhGraph}, the graph containing the node, not {@code null}
+ * @return {@link EnhNode} a new enhanced node presenting the interface that this factory encapsulates
+ * @throws OntJenaException in case wrapping is impossible
+ */
+ default EnhNode wrap(Node node, EnhGraph eg) {
+ if (!canWrap(node, eg))
+ throw new OntJenaException.Conversion("Can't wrap node " + node + ". Use direct factory.");
+ return createInstance(node, eg);
+ }
+
+ /**
+ * Makes interface-defined changes in the given graph
+ * and returns a new enhanced node, wrapping the given {@link Node}.
+ *
+ * @param node {@link Node}, the node to be wrapped as {@link EnhNode}, not {@code null}
+ * @param eg {@link EnhGraph}, the graph which would contain the result {@link EnhNode}, not {@code null}
+ * @return a new enhanced node
+ * @throws OntJenaException in case modification of graph is not allowed for the specified node
+ */
+ default EnhNode createInGraph(Node node, EnhGraph eg) {
+ throw new OntJenaException.IllegalCall("Creation is not allowed: " + node);
+ }
+
+ /**
+ * Answers {@code true} iff the modifying of the {@link EnhGraph graph} is allowed
+ * by this implementation for the encapsulated object's interface.
+ *
+ * @param node {@link Node} the node to test that changes are permitted.
+ * @param eg {@link EnhGraph} the graph to be changed.
+ * @return true if creation is allowed.
+ */
+ default boolean canCreateInGraph(Node node, EnhGraph eg) {
+ return false;
+ }
+
+ /**
+ * Lists all enhanced nodes from the graph, with the interface that this factory encapsulates.
+ *
+ * @param eg the graph containing the node
+ * @return the stream of enhanced and suitability nodes
+ */
+ default Stream<EnhNode> find(EnhGraph eg) {
+ return Iterators.asStream(iterator(eg));
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeFilter.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeFilter.java
new file mode 100644
index 0000000000..b5228715a2
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeFilter.java
@@ -0,0 +1,198 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.utils.Graphs;
+import org.apache.jena.ontapi.vocabulary.RDF;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.graph.FrontsNode;
+import org.apache.jena.graph.Node;
+import org.apache.jena.rdf.model.Property;
+import org.apache.jena.rdf.model.Resource;
+
+import java.util.Collection;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * To filter resources.
+ * Used by {@link CommonEnhNodeFactoryImpl default factory} and {@link CompositeEnhNodeFactoryImpl} implementations as a component.
+ */
+@FunctionalInterface
+public interface EnhNodeFilter {
+ EnhNodeFilter TRUE = new EnhNodeFilter() {
+ @Override
+ public boolean test(Node n, EnhGraph g) {
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "TRUE";
+ }
+ };
+ EnhNodeFilter FALSE = new EnhNodeFilter() {
+ @Override
+ public boolean test(Node n, EnhGraph g) {
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return "FALSE";
+ }
+ };
+ EnhNodeFilter URI = new EnhNodeFilter() {
+ @Override
+ public boolean test(Node n, EnhGraph g) {
+ return n.isURI();
+ }
+
+ @Override
+ public String toString() {
+ return "URI";
+ }
+ };
+ EnhNodeFilter ANON = new EnhNodeFilter() {
+ @Override
+ public boolean test(Node n, EnhGraph g) {
+ return n.isBlank();
+ }
+
+ @Override
+ public String toString() {
+ return "BLANK";
+ }
+ };
+
+ /**
+ * Tests if the given {@link Node node} suits the encapsulated conditions in bounds of the specified {@link EnhGraph graph}.
+ *
+ * @param n {@link Node}, not {@code null}
+ * @param g {@link EnhGraph}, not {@code null}
+ * @return boolean
+ */
+ boolean test(Node n, EnhGraph g);
+
+ default EnhNodeFilter and(EnhNodeFilter other) {
+ if (Objects.requireNonNull(other, "Null and-filter.").equals(TRUE)) {
+ return this;
+ }
+ if (this.equals(TRUE)) return other;
+ if (other.equals(FALSE)) return FALSE;
+ if (this.equals(FALSE)) return FALSE;
+ return new EnhNodeFilter() {
+ @Override
+ public boolean test(Node n, EnhGraph g) {
+ return EnhNodeFilter.this.test(n, g) && other.test(n, g);
+ }
+
+ @Override
+ public String toString() {
+ return "(" + EnhNodeFilter.this + ")AND(" + other + ")";
+ }
+ };
+ }
+
+ default EnhNodeFilter or(EnhNodeFilter other) {
+ if (Objects.requireNonNull(other, "Null or-filter.").equals(TRUE)) {
+ return TRUE;
+ }
+ if (this.equals(TRUE)) return TRUE;
+ if (other.equals(FALSE)) return this;
+ if (this.equals(FALSE)) return other;
+ return new EnhNodeFilter() {
+ @Override
+ public boolean test(Node n, EnhGraph g) {
+ return EnhNodeFilter.this.test(n, g) || other.test(n, g);
+ }
+
+ @Override
+ public String toString() {
+ return "(" + EnhNodeFilter.this + ")OR(" + other + ")";
+ }
+ };
+ }
+
+ default EnhNodeFilter accumulate(EnhNodeFilter... filters) {
+ EnhNodeFilter res = this;
+ for (EnhNodeFilter o : filters) {
+ res = res.and(o);
+ }
+ return res;
+ }
+
+ class HasPredicate implements EnhNodeFilter {
+ protected final Node predicate;
+
+ public HasPredicate(Property predicate) {
+ this.predicate = Objects.requireNonNull(predicate, "Null predicate.").asNode();
+ }
+
+ @Override
+ public boolean test(Node n, EnhGraph g) {
+ return g.asGraph().contains(n, predicate, Node.ANY);
+ }
+
+ @Override
+ public String toString() {
+ return "HasPredicate::" + predicate.getLocalName();
+ }
+ }
+
+ class HasType implements EnhNodeFilter {
+ protected final Node type;
+
+ public HasType(Resource type) {
+ this.type = Objects.requireNonNull(type, "Null type.").asNode();
+ }
+
+ @Override
+ public boolean test(Node node, EnhGraph eg) {
+ return eg.asGraph().contains(node, RDF.Nodes.type, type);
+ }
+
+ @Override
+ public String toString() {
+ return "HasType::" + type.getLocalName();
+ }
+ }
+
+ class HasOneOfType implements EnhNodeFilter {
+ protected final Set<Node> types;
+
+ public HasOneOfType(Collection<Resource> types) {
+ if (types.isEmpty()) {
+ throw new IllegalStateException();
+ }
+ this.types = types.stream().map(FrontsNode::asNode).collect(Collectors.toUnmodifiableSet());
+ }
+
+ @Override
+ public boolean test(Node node, EnhGraph eg) {
+ return Graphs.hasOneOfType(node, eg.asGraph(), types);
+ }
+
+ @Override
+ public String toString() {
+ return "HasType::" + types;
+ }
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeFinder.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeFinder.java
new file mode 100644
index 0000000000..bf0e6062a5
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeFinder.java
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.jena.ontapi.common;
+
+import org.apache.jena.ontapi.utils.Graphs;
+import org.apache.jena.ontapi.utils.Iterators;
+import org.apache.jena.ontapi.vocabulary.RDF;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.graph.FrontsNode;
+import org.apache.jena.graph.Node;
+import org.apache.jena.graph.Triple;
+import org.apache.jena.rdf.model.Property;
+import org.apache.jena.rdf.model.Resource;
+import org.apache.jena.util.iterator.ExtendedIterator;
+import org.apache.jena.util.iterator.NullIterator;
+import org.apache.jena.util.iterator.WrappedIterator;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Stream;
+
+/**
+ * A class-helper to perform the preliminary resource search in a model.
+ * Subsequently, the search result Stream will be filtered by the {@link EnhNodeFilter} instance.
+ * Used as a component in {@link CommonEnhNodeFactoryImpl default factory} and {@link CompositeEnhNodeFactoryImpl} implementations
+ */
+@FunctionalInterface
+public interface EnhNodeFinder {
+ EnhNodeFinder ANY_SUBJECT = eg -> Graphs.listSubjects(eg.asGraph());
+ EnhNodeFinder ANY_BLANK_SUBJECT = eg -> Iterators.distinct(eg.asGraph().find().mapWith(Triple::getSubject).filterKeep(Node::isBlank));
+ EnhNodeFinder ANY_SUBJECT_AND_OBJECT = eg -> Graphs.listSubjectsAndObjects(eg.asGraph());
+ EnhNodeFinder ANYTHING = eg -> Graphs.listAllNodes(eg.asGraph());
+ EnhNodeFinder NOTHING = eg -> NullIterator.instance();
+ EnhNodeFinder ANY_TYPED = new ByPredicate(RDF.type);
+
+ /**
+ * Returns an iterator over the nodes in the given model, which satisfy some criterion,
+ * specific to this {@link EnhNodeFinder}.
+ * It is expected that the result does not contain duplicates.
+ *
+ * @param eg {@link EnhGraph}, model
+ * @return {@link ExtendedIterator} of {@link Node}s
+ */
+ ExtendedIterator<Node> iterator(EnhGraph eg);
+
+ /**
+ * Lists the nodes from the specified model by the encapsulated criterion.
+ *
+ * @param eg {@link EnhGraph}, model
+ * @return {@link Stream} of {@link Node}s
+ */
+ default Stream<Node> find(EnhGraph eg) {
+ return Iterators.asStream(iterator(eg));
+ }
+
+ default EnhNodeFinder restrict(EnhNodeFilter filter) {
+ if (Objects.requireNonNull(filter, "Null restriction filter.").equals(EnhNodeFilter.TRUE)) return this;
+ if (filter.equals(EnhNodeFilter.FALSE)) return eg -> NullIterator.instance();
+ return eg -> iterator(eg).filterKeep(n -> filter.test(n, eg));
+ }
+
+ class ByType implements EnhNodeFinder {
+ protected final Node type;
+
+ public ByType(Resource type) {
+ this(Objects.requireNonNull(type, "Null type.").asNode());
+ }
+
+ public ByType(Node type) {
+ this.type = Objects.requireNonNull(type, "Null type.");
+ }
+
+ @Override
+ public ExtendedIterator<Node> iterator(EnhGraph eg) {
+ return eg.asGraph().find(Node.ANY, RDF.Nodes.type, type).mapWith(Triple::getSubject);
+ }
+ }
+
+ class ByTypes implements EnhNodeFinder {
+ protected final List<Node> types;
+
+ public ByTypes(Collection<Resource> types) {
+ if (types.isEmpty()) {
+ throw new IllegalStateException();
+ }
+ this.types = types.stream().map(FrontsNode::asNode).distinct().toList();
+ }
+
+ @Override
+ public ExtendedIterator<Node> iterator(EnhGraph eg) {
+ if (types.size() == 1) {
+ return eg.asGraph().find(Node.ANY, RDF.Nodes.type, types.get(0)).mapWith(Triple::getSubject);
+ }
+ return Iterators.distinct(Iterators.flatMap(WrappedIterator.create(types.iterator()),
+ type -> eg.asGraph().find(Node.ANY, RDF.Nodes.type, type)).mapWith(Triple::getSubject));
+ }
+ }
+
+ class ByPredicate implements EnhNodeFinder {
+ protected final Node predicate;
+
+ public ByPredicate(Property predicate) {
+ this.predicate = Objects.requireNonNull(predicate, "Null predicate.").asNode();
+ }
+
+ @Override
+ public ExtendedIterator<Node> iterator(EnhGraph eg) {
+ return Iterators.distinct(eg.asGraph().find(Node.ANY, predicate, Node.ANY).mapWith(Triple::getSubject));
+ }
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeProducer.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeProducer.java
new file mode 100644
index 0000000000..e7c36153aa
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/EnhNodeProducer.java
@@ -0,0 +1,196 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.ontapi.impl.objects.OntObjectImpl;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.ontapi.vocabulary.RDF;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.enhanced.EnhNode;
+import org.apache.jena.graph.Node;
+import org.apache.jena.graph.Triple;
+import org.apache.jena.rdf.model.Resource;
+import org.apache.jena.shared.JenaException;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.function.BiFunction;
+
+/**
+ * To make some preparation while creating (create main triple).
+ * Also, to create new instance of the resource ({@link EnhNode}).
+ * Used in factory ({@link CommonEnhNodeFactoryImpl}).
+ */
+public interface EnhNodeProducer {
+
+ /**
+ * Wraps the given {@code node} as a {@link EnhNode Jena RDFNode}.
+ * No changes in the given {@link EnhGraph} are made.
+ *
+ * @param node {@link Node}
+ * @param eg {@link EnhGraph}
+ * @return {@link EnhNode}
+ */
+ EnhNode newInstance(Node node, EnhGraph eg);
+
+ /**
+ * Changes the {@link EnhGraph} according to the encapsulated rules.
+ *
+ * @param node {@link Node}
+ * @param eg {@link EnhGraph}
+ */
+ void doInsert(Node node, EnhGraph eg);
+
+ /**
+ * Answers {@code true} if the given {@code node} can be created in graph
+ * @param node {@link Node} ti test
+ * @param eg {@link EnhGraph}
+ * @return boolean
+ */
+ boolean canInsert(Node node, EnhGraph eg);
+
+ /**
+ * Returns a view string representation.
+ * @return the name (type) of {@link EnhNode} object
+ */
+ String targetName();
+
+ default EnhNodeProducer restrict(EnhNodeFilter filter) {
+ OntJenaException.notNull(filter, "Null restriction filter.");
+ return new EnhNodeProducer() {
+
+ @Override
+ public void doInsert(Node node, EnhGraph eg) {
+ EnhNodeProducer.this.doInsert(node, eg);
+ }
+
+ @Override
+ public boolean canInsert(Node node, EnhGraph eg) {
+ return EnhNodeProducer.this.canInsert(node, eg) && filter.test(node, eg);
+ }
+
+ @Override
+ public EnhNode newInstance(Node node, EnhGraph eg) {
+ return EnhNodeProducer.this.newInstance(node, eg);
+ }
+
+ @Override
+ public String targetName() {
+ return EnhNodeProducer.this.targetName();
+ }
+
+ @Override
+ public String toString() {
+ return "Producer[" + targetName() + "]Restriction[" + filter + "]";
+ }
+ };
+ }
+
+ /**
+ * The base maker implementation for our project.
+ * <p>
+ * Creation in graph is disabled for this maker
+ */
+ class Default implements EnhNodeProducer {
+ private final BiFunction<Node, EnhGraph, EnhNode> producer;
+ private final String targetName;
+
+ /**
+ * Class must be public and have a public constructor with parameters {@link Node} and {@link EnhGraph}.
+ *
+ * @param impl {@link OntObject} implementation
+ * @param producer factory to create new instance, if {@code null} reflection is used
+ */
+ public Default(Class<? extends EnhNode> impl, BiFunction<Node, EnhGraph, EnhNode> producer) {
+ this.targetName = OntJenaException.notNull(impl, "Null implementation class.").getName()
+ .replace(impl.getPackageName() + ".", "");
+ this.producer = OntJenaException.notNull(producer);
+ }
+
+ public Default(Class<? extends EnhNode> impl) {
+ this.targetName = OntJenaException.notNull(impl, "Null implementation class.")
+ .getName().replace(impl.getPackageName() + ".", "");
+ this.producer = (node, graph) -> newInstance(node, graph, impl, targetName);
+ }
+
+ @Override
+ public void doInsert(Node node, EnhGraph eg) {
+ throw new OntJenaException.IllegalCall("Creation is not allowed for node " +
+ node + " and target " + targetName());
+ }
+
+ @Override
+ public boolean canInsert(Node node, EnhGraph eg) {
+ return false;
+ }
+
+ @Override
+ public EnhNode newInstance(Node node, EnhGraph eg) {
+ return producer.apply(node, eg);
+ }
+
+ private static EnhNode newInstance(Node node,
+ EnhGraph eg,
+ Class<? extends EnhNode> impl,
+ String targetName) {
+ try {
+ return impl.getDeclaredConstructor(Node.class, EnhGraph.class).newInstance(node, eg);
+ } catch (InstantiationException | IllegalAccessException | NoSuchMethodException e) {
+ throw new OntJenaException("Can't create instance of " + targetName, e);
+ } catch (InvocationTargetException e) {
+ if (e.getCause() instanceof JenaException) throw (JenaException) e.getCause();
+ throw new OntJenaException("Can't init " + targetName, e);
+ }
+ }
+
+ @Override
+ public String targetName() {
+ return targetName;
+ }
+ }
+
+ /**
+ * to create a triple representing declaration.
+ */
+ class WithType extends Default {
+ protected final Node type;
+
+ public WithType(Class<? extends OntObjectImpl> impl,
+ Resource type,
+ BiFunction<Node, EnhGraph, EnhNode> producer) {
+ super(impl, producer);
+ this.type = OntJenaException.notNull(type, "Null type.").asNode();
+ }
+
+ public WithType(Class<? extends OntObjectImpl> impl, Resource type) {
+ super(impl);
+ this.type = OntJenaException.notNull(type, "Null type.").asNode();
+ }
+
+ @Override
+ public void doInsert(Node node, EnhGraph eg) {
+ eg.asGraph().add(Triple.create(node, RDF.type.asNode(), type));
+ }
+
+ @Override
+ public boolean canInsert(Node node, EnhGraph eg) {
+ return true;
+ }
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntConfig.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntConfig.java
new file mode 100644
index 0000000000..8998f9779e
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntConfig.java
@@ -0,0 +1,83 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.model.OntModel;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Configuration to control {@link OntModel} and {@link OntPersonality} behavior.
+ */
+public class OntConfig {
+ public static final OntConfig DEFAULT = new OntConfig();
+
+ private final Map<String, Object> settings;
+
+ public OntConfig() {
+ this(Map.of());
+ }
+
+ protected OntConfig(Map<String, Object> settings) {
+ this.settings = Map.copyOf(Objects.requireNonNull(settings));
+ }
+
+ public boolean getBoolean(Enum<?> key) {
+ return getBoolean(key.name());
+ }
+
+ public boolean getBoolean(String key) {
+ Object value = get(key);
+ if (value == null) {
+ return false;
+ }
+ if (value instanceof Boolean) {
+ return (Boolean) value;
+ }
+ throw new IllegalArgumentException("Config contains value for key = " + key + ", but it is not a boolean");
+ }
+
+ public Object get(String key) {
+ return settings.get(key);
+ }
+
+ public OntConfig setTrue(Enum<?> key) {
+ return setBoolean(key, true);
+ }
+
+ public OntConfig setFalse(Enum<?> key) {
+ return setBoolean(key, false);
+ }
+
+ public OntConfig setBoolean(Enum<?> key, boolean value) {
+ return setBoolean(key.name(), value);
+ }
+
+ public OntConfig setBoolean(String key, boolean value) {
+ return set(key, value);
+ }
+
+ public OntConfig set(String key, Object value) {
+ Map<String, Object> settings = new HashMap<>(this.settings);
+ settings.put(key, value);
+ return new OntConfig(settings);
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntConfigs.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntConfigs.java
new file mode 100644
index 0000000000..adb4244c1d
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntConfigs.java
@@ -0,0 +1,267 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntModelControls;
+
+/**
+ * Collection of ontology configurations.
+ */
+public class OntConfigs {
+
+ public static final OntConfig OWL2_CONFIG = OntConfig.DEFAULT
+ .setTrue(OntModelControls.USE_GENERATE_ONTOLOGY_HEADER_IF_ABSENT_STRATEGY)
+ .setTrue(OntModelControls.USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY)
+ .setFalse(OntModelControls.USE_BUILTIN_HIERARCHY_SUPPORT)
+ .setFalse(OntModelControls.USE_SIMPLIFIED_TYPE_CHECKING_WHILE_LIST_INDIVIDUALS)
+ .setTrue(OntModelControls.USE_OWL2_DEPRECATED_VOCABULARY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL1_DATARANGE_DECLARATION_FEATURE)
+ .setFalse(OntModelControls.USE_OWL1_DISTINCT_MEMBERS_PREDICATE_FEATURE)
+ .setFalse(OntModelControls.ALLOW_NAMED_CLASS_EXPRESSIONS)
+ .setFalse(OntModelControls.ALLOW_GENERIC_CLASS_EXPRESSIONS)
+ .setTrue(OntModelControls.ALLOW_ANONYMOUS_INDIVIDUALS)
+ .setFalse(OntModelControls.USE_LEGACY_COMPATIBLE_NAMED_CLASS_FACTORY)
+ .setTrue(OntModelControls.USE_OWL2_NAMED_INDIVIDUAL_DECLARATION_FEATURE)
+ .setTrue(OntModelControls.USE_OWL2_CLASS_HAS_KEY_FEATURE)
+ .setTrue(OntModelControls.USE_OWL2_NAMED_CLASS_DISJOINT_UNION_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_CLASS_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_CLASS_EQUIVALENT_FEATURE)
+ .setTrue(OntModelControls.USE_OWL2_PROPERTY_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_EQUIVALENT_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_INVERSE_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_DATA_PROPERTY_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_OBJECT_PROPERTY_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_SYMMETRIC_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_ASYMMETRIC_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_TRANSITIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_REFLEXIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_IRREFLEXIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_INVERSE_OF_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INVERSE_OBJECT_PROPERTY_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_CHAIN_AXIOM_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INDIVIDUAL_SAME_AS_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INDIVIDUAL_DIFFERENT_FROM_FEATURE)
+ .setTrue(OntModelControls.USE_OWL2_QUALIFIED_CARDINALITY_RESTRICTION_FEATURE);
+
+ public static final OntConfig OWL2_EL_CONFIG = OntConfig.DEFAULT
+ .setTrue(OntModelControls.USE_GENERATE_ONTOLOGY_HEADER_IF_ABSENT_STRATEGY)
+ .setTrue(OntModelControls.USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY)
+ .setFalse(OntModelControls.USE_BUILTIN_HIERARCHY_SUPPORT)
+ .setFalse(OntModelControls.USE_SIMPLIFIED_TYPE_CHECKING_WHILE_LIST_INDIVIDUALS)
+ .setFalse(OntModelControls.USE_OWL2_DEPRECATED_VOCABULARY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL1_DATARANGE_DECLARATION_FEATURE)
+ .setFalse(OntModelControls.USE_OWL1_DISTINCT_MEMBERS_PREDICATE_FEATURE)
+ .setFalse(OntModelControls.ALLOW_NAMED_CLASS_EXPRESSIONS)
+ .setFalse(OntModelControls.ALLOW_GENERIC_CLASS_EXPRESSIONS)
+ .setFalse(OntModelControls.ALLOW_ANONYMOUS_INDIVIDUALS)
+ .setFalse(OntModelControls.USE_LEGACY_COMPATIBLE_NAMED_CLASS_FACTORY)
+ .setTrue(OntModelControls.USE_OWL2_NAMED_INDIVIDUAL_DECLARATION_FEATURE)
+ .setTrue(OntModelControls.USE_OWL2_CLASS_HAS_KEY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_NAMED_CLASS_DISJOINT_UNION_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_CLASS_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_CLASS_EQUIVALENT_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_PROPERTY_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_EQUIVALENT_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_INVERSE_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_DATA_PROPERTY_FUNCTIONAL_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_OBJECT_PROPERTY_FUNCTIONAL_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_SYMMETRIC_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_ASYMMETRIC_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_TRANSITIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_REFLEXIVE_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_IRREFLEXIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_INVERSE_OF_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_INVERSE_OBJECT_PROPERTY_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_CHAIN_AXIOM_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INDIVIDUAL_SAME_AS_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INDIVIDUAL_DIFFERENT_FROM_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_QUALIFIED_CARDINALITY_RESTRICTION_FEATURE);
+
+ public static final OntConfig OWL2_QL_CONFIG = OntConfig.DEFAULT
+ .setTrue(OntModelControls.USE_GENERATE_ONTOLOGY_HEADER_IF_ABSENT_STRATEGY)
+ .setTrue(OntModelControls.USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY)
+ .setFalse(OntModelControls.USE_BUILTIN_HIERARCHY_SUPPORT)
+ .setFalse(OntModelControls.USE_SIMPLIFIED_TYPE_CHECKING_WHILE_LIST_INDIVIDUALS)
+ .setFalse(OntModelControls.USE_OWL2_DEPRECATED_VOCABULARY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL1_DATARANGE_DECLARATION_FEATURE)
+ .setFalse(OntModelControls.USE_OWL1_DISTINCT_MEMBERS_PREDICATE_FEATURE)
+ .setFalse(OntModelControls.ALLOW_NAMED_CLASS_EXPRESSIONS)
+ .setFalse(OntModelControls.ALLOW_GENERIC_CLASS_EXPRESSIONS)
+ .setFalse(OntModelControls.ALLOW_ANONYMOUS_INDIVIDUALS)
+ .setFalse(OntModelControls.USE_LEGACY_COMPATIBLE_NAMED_CLASS_FACTORY)
+ .setTrue(OntModelControls.USE_OWL2_NAMED_INDIVIDUAL_DECLARATION_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_CLASS_HAS_KEY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_NAMED_CLASS_DISJOINT_UNION_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_CLASS_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_CLASS_EQUIVALENT_FEATURE)
+ .setTrue(OntModelControls.USE_OWL2_PROPERTY_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_EQUIVALENT_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_INVERSE_FUNCTIONAL_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_DATA_PROPERTY_FUNCTIONAL_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_OBJECT_PROPERTY_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_SYMMETRIC_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_ASYMMETRIC_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_TRANSITIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_REFLEXIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_IRREFLEXIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_INVERSE_OF_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INVERSE_OBJECT_PROPERTY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_CHAIN_AXIOM_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_INDIVIDUAL_SAME_AS_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INDIVIDUAL_DIFFERENT_FROM_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_QUALIFIED_CARDINALITY_RESTRICTION_FEATURE);
+
+ public static final OntConfig OWL2_RL_CONFIG = OntConfig.DEFAULT
+ .setTrue(OntModelControls.USE_GENERATE_ONTOLOGY_HEADER_IF_ABSENT_STRATEGY)
+ .setTrue(OntModelControls.USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY)
+ .setFalse(OntModelControls.USE_BUILTIN_HIERARCHY_SUPPORT)
+ .setFalse(OntModelControls.USE_SIMPLIFIED_TYPE_CHECKING_WHILE_LIST_INDIVIDUALS)
+ .setTrue(OntModelControls.USE_OWL2_DEPRECATED_VOCABULARY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL1_DATARANGE_DECLARATION_FEATURE)
+ .setFalse(OntModelControls.USE_OWL1_DISTINCT_MEMBERS_PREDICATE_FEATURE)
+ .setFalse(OntModelControls.ALLOW_NAMED_CLASS_EXPRESSIONS)
+ .setFalse(OntModelControls.ALLOW_GENERIC_CLASS_EXPRESSIONS)
+ .setTrue(OntModelControls.ALLOW_ANONYMOUS_INDIVIDUALS)
+ .setFalse(OntModelControls.USE_LEGACY_COMPATIBLE_NAMED_CLASS_FACTORY)
+ .setTrue(OntModelControls.USE_OWL2_NAMED_INDIVIDUAL_DECLARATION_FEATURE)
+ .setTrue(OntModelControls.USE_OWL2_CLASS_HAS_KEY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_NAMED_CLASS_DISJOINT_UNION_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_CLASS_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_CLASS_EQUIVALENT_FEATURE)
+ .setTrue(OntModelControls.USE_OWL2_PROPERTY_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_EQUIVALENT_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_INVERSE_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_DATA_PROPERTY_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_OBJECT_PROPERTY_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_SYMMETRIC_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_ASYMMETRIC_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_TRANSITIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_REFLEXIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_IRREFLEXIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_INVERSE_OF_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INVERSE_OBJECT_PROPERTY_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_CHAIN_AXIOM_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INDIVIDUAL_SAME_AS_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INDIVIDUAL_DIFFERENT_FROM_FEATURE)
+ .setTrue(OntModelControls.USE_OWL2_QUALIFIED_CARDINALITY_RESTRICTION_FEATURE);
+
+ public static final OntConfig OWL1_CONFIG = OntConfig.DEFAULT
+ .setTrue(OntModelControls.USE_GENERATE_ONTOLOGY_HEADER_IF_ABSENT_STRATEGY)
+ .setTrue(OntModelControls.USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY)
+ .setFalse(OntModelControls.USE_BUILTIN_HIERARCHY_SUPPORT)
+ .setTrue(OntModelControls.USE_SIMPLIFIED_TYPE_CHECKING_WHILE_LIST_INDIVIDUALS)
+ .setTrue(OntModelControls.USE_OWL2_DEPRECATED_VOCABULARY_FEATURE)
+ .setTrue(OntModelControls.USE_OWL1_DATARANGE_DECLARATION_FEATURE)
+ .setTrue(OntModelControls.USE_OWL1_DISTINCT_MEMBERS_PREDICATE_FEATURE)
+ .setTrue(OntModelControls.ALLOW_NAMED_CLASS_EXPRESSIONS)
+ .setTrue(OntModelControls.ALLOW_GENERIC_CLASS_EXPRESSIONS)
+ .setTrue(OntModelControls.ALLOW_ANONYMOUS_INDIVIDUALS)
+ .setTrue(OntModelControls.USE_LEGACY_COMPATIBLE_NAMED_CLASS_FACTORY)
+ .setFalse(OntModelControls.USE_OWL2_NAMED_INDIVIDUAL_DECLARATION_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_CLASS_HAS_KEY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_NAMED_CLASS_DISJOINT_UNION_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_CLASS_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_CLASS_EQUIVALENT_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_PROPERTY_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_EQUIVALENT_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_INVERSE_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_DATA_PROPERTY_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_OBJECT_PROPERTY_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_SYMMETRIC_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_ASYMMETRIC_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_TRANSITIVE_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_REFLEXIVE_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_IRREFLEXIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_INVERSE_OF_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_INVERSE_OBJECT_PROPERTY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_CHAIN_AXIOM_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INDIVIDUAL_SAME_AS_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INDIVIDUAL_DIFFERENT_FROM_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_QUALIFIED_CARDINALITY_RESTRICTION_FEATURE);
+
+ public static final OntConfig OWL1_LITE_CONFIG = OntConfig.DEFAULT
+ .setTrue(OntModelControls.USE_GENERATE_ONTOLOGY_HEADER_IF_ABSENT_STRATEGY)
+ .setTrue(OntModelControls.USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY)
+ .setFalse(OntModelControls.USE_BUILTIN_HIERARCHY_SUPPORT)
+ .setTrue(OntModelControls.USE_SIMPLIFIED_TYPE_CHECKING_WHILE_LIST_INDIVIDUALS)
+ .setTrue(OntModelControls.USE_OWL2_DEPRECATED_VOCABULARY_FEATURE)
+ .setTrue(OntModelControls.USE_OWL2_DEPRECATED_VOCABULARY_FEATURE)
+ .setTrue(OntModelControls.USE_OWL1_DATARANGE_DECLARATION_FEATURE)
+ .setTrue(OntModelControls.USE_OWL1_DATARANGE_DECLARATION_FEATURE)
+ .setTrue(OntModelControls.USE_OWL1_DISTINCT_MEMBERS_PREDICATE_FEATURE)
+ .setTrue(OntModelControls.ALLOW_NAMED_CLASS_EXPRESSIONS)
+ .setTrue(OntModelControls.ALLOW_GENERIC_CLASS_EXPRESSIONS)
+ .setTrue(OntModelControls.ALLOW_ANONYMOUS_INDIVIDUALS)
+ .setTrue(OntModelControls.USE_LEGACY_COMPATIBLE_NAMED_CLASS_FACTORY)
+ .setFalse(OntModelControls.USE_OWL2_NAMED_INDIVIDUAL_DECLARATION_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_CLASS_HAS_KEY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_NAMED_CLASS_DISJOINT_UNION_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_CLASS_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_CLASS_EQUIVALENT_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_PROPERTY_DISJOINT_WITH_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_EQUIVALENT_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_INVERSE_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_DATA_PROPERTY_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_OBJECT_PROPERTY_FUNCTIONAL_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_SYMMETRIC_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_ASYMMETRIC_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_TRANSITIVE_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_REFLEXIVE_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_IRREFLEXIVE_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_PROPERTY_INVERSE_OF_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_INVERSE_OBJECT_PROPERTY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_CHAIN_AXIOM_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_INDIVIDUAL_SAME_AS_FEATURE)
+ .setTrue(OntModelControls.USE_OWL_INDIVIDUAL_DIFFERENT_FROM_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_QUALIFIED_CARDINALITY_RESTRICTION_FEATURE);
+
+ public static final OntConfig RDFS_CONFIG = OntConfig.DEFAULT
+ .setFalse(OntModelControls.USE_GENERATE_ONTOLOGY_HEADER_IF_ABSENT_STRATEGY)
+ .setFalse(OntModelControls.USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY)
+ .setFalse(OntModelControls.USE_BUILTIN_HIERARCHY_SUPPORT)
+ .setTrue(OntModelControls.USE_SIMPLIFIED_TYPE_CHECKING_WHILE_LIST_INDIVIDUALS)
+ .setFalse(OntModelControls.USE_OWL2_DEPRECATED_VOCABULARY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL1_DATARANGE_DECLARATION_FEATURE)
+ .setFalse(OntModelControls.USE_OWL1_DISTINCT_MEMBERS_PREDICATE_FEATURE)
+ .setFalse(OntModelControls.ALLOW_NAMED_CLASS_EXPRESSIONS)
+ .setFalse(OntModelControls.ALLOW_GENERIC_CLASS_EXPRESSIONS)
+ .setTrue(OntModelControls.ALLOW_ANONYMOUS_INDIVIDUALS)
+ .setTrue(OntModelControls.USE_LEGACY_COMPATIBLE_NAMED_CLASS_FACTORY)
+ .setFalse(OntModelControls.USE_OWL2_NAMED_INDIVIDUAL_DECLARATION_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_CLASS_HAS_KEY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_NAMED_CLASS_DISJOINT_UNION_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_CLASS_DISJOINT_WITH_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_CLASS_EQUIVALENT_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_PROPERTY_DISJOINT_WITH_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_EQUIVALENT_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_INVERSE_FUNCTIONAL_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_DATA_PROPERTY_FUNCTIONAL_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_OBJECT_PROPERTY_FUNCTIONAL_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_SYMMETRIC_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_ASYMMETRIC_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_TRANSITIVE_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_REFLEXIVE_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_IRREFLEXIVE_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_INVERSE_OF_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_INVERSE_OBJECT_PROPERTY_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_PROPERTY_CHAIN_AXIOM_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_INDIVIDUAL_SAME_AS_FEATURE)
+ .setFalse(OntModelControls.USE_OWL_INDIVIDUAL_DIFFERENT_FROM_FEATURE)
+ .setFalse(OntModelControls.USE_OWL2_QUALIFIED_CARDINALITY_RESTRICTION_FEATURE);
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntEnhGraph.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntEnhGraph.java
new file mode 100644
index 0000000000..8621ea4dce
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntEnhGraph.java
@@ -0,0 +1,167 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.ontapi.impl.OntGraphModelImpl;
+import org.apache.jena.ontapi.model.OntModel;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.graph.Node;
+import org.apache.jena.rdf.model.RDFNode;
+
+/**
+ * An abstraction to work with {@link OntPersonality}
+ * and an interface-analogue of the {@link EnhGraph Jena Enhanced Graph},
+ * and also a facility to provide implicit links between different
+ * {@link EnhNodeFactory} factories within a model.
+ * A .orElse(null) is assumed to be {@link OntEnhGraph}.
+ * <p>
+ * Explicit links between object factories are undesirable, since replacing one of the factories will affect others.
+ * But using this interface, it is possible to build safe implicit links and
+ * replacing one factory with a custom implementation will not break the whole model.
+ * More about this see in the description for
+ * the method {@link OntObjectPersonalityBuilder#add(Class, EnhNodeFactory)}.
+ */
+@SuppressWarnings("unused")
+public interface OntEnhGraph {
+
+ /**
+ * Represents the given {@code EnhGraph} as a {@link OntEnhGraph}.
+ *
+ * @param graph {@link EnhGraph enhanced graph},
+ * that is also assumed to be {@link OntModel}, not {@code null}
+ * @return {@link OntEnhGraph}
+ * @throws OntJenaException in case the conversion is not possible
+ * @see OntPersonality#asJenaPersonality(OntPersonality)
+ */
+ static OntEnhGraph asPersonalityModel(EnhGraph graph) throws OntJenaException {
+ if (graph instanceof OntEnhGraph) {
+ return (OntEnhGraph) graph;
+ }
+ throw new OntJenaException.IllegalArgument("The given EnhGraph is not a PersonalityModel: " + graph);
+ }
+
+ /**
+ * Represents the given {@code Ont[Graph]Model} as a {@link OntEnhGraph}.
+ *
+ * @param graph {@link OntModel OWL graph model},
+ * that is also assumed to be {@link EnhGraph}, not {@code null}
+ * @return {@link OntEnhGraph}
+ * @throws OntJenaException in case the conversion is not possible
+ * @see OntPersonality#asJenaPersonality(OntPersonality)
+ */
+ static OntEnhGraph asPersonalityModel(OntModel graph) throws OntJenaException {
+ if (graph instanceof OntEnhGraph) {
+ return (OntEnhGraph) graph;
+ }
+ throw new OntJenaException.IllegalArgument("The given OntGraphModel is not a PersonalityModel: " + graph);
+ }
+
+ /**
+ * Extracts {@link OntConfig} from the given enhanced graph.
+ *
+ * @param graph {@link OntModel OWL graph model},
+ * that is also assumed to be {@link EnhGraph}, not {@code null}
+ * @return {@link OntConfig}
+ */
+ static OntConfig config(EnhGraph graph) {
+ return asPersonalityModel(graph).getOntPersonality().getConfig();
+ }
+
+ /**
+ * Checks if the given {@link Node node} can be viewed as the given type.
+ * Opposite to the method {@link OntEnhGraph#findNodeAs(Node, Class)}, this method handles possible graph recursions.
+ *
+ * @param view Class-type
+ * @param node {@link Node}
+ * @param graph {@link EnhGraph}, assumed to be {@link OntGraphModelImpl}
+ * @return {@code true} if the node can be safely cast to the specified type
+ */
+ static boolean canAs(Class<? extends RDFNode> view, Node node, EnhGraph graph) {
+ return asPersonalityModel(graph).canNodeAs(view, node);
+ }
+
+ /**
+ * Returns the model personality, that is unmodifiable model's configuration storage.
+ *
+ * @return {@link OntPersonality}
+ */
+ OntPersonality getOntPersonality();
+
+ /**
+ * Answers an enhanced node that wraps the given {@link Node node} and conforms to the given interface type.
+ *
+ * @param node a {@link Node node}, that is assumed to be in this graph
+ * @param view a type denoting the enhanced facet desired
+ * @param <N> a subtype of {@link RDFNode}
+ * @return an enhanced node, not {@code null}
+ * @throws OntJenaException in case no RDFNode match found
+ * @see OntEnhGraph#findNodeAs(Node, Class)
+ * @see EnhGraph#getNodeAs(Node, Class)
+ */
+ <N extends RDFNode> N getNodeAs(Node node, Class<N> view);
+
+ /**
+ * Answers an enhanced node that wraps the given {@link Node node} and conforms to the given interface type.
+ * It works silently: no exception is thrown, instead returns {@code null}.
+ *
+ * @param node {@link Node}
+ * @param type {@link Class}-type
+ * @param <N> any subtype of {@link RDFNode}
+ * @return {@link RDFNode} or {@code null}
+ * @see OntEnhGraph#getNodeAs(Node, Class)
+ */
+ <N extends RDFNode> N findNodeAs(Node node, Class<N> type);
+
+ /**
+ * Answers an enhanced node that wraps the given {@link Node node} and conforms to the given interface type,
+ * taking into account possible graph recursions.
+ *
+ * @param node a {@link Node node}, that is assumed to be in this graph
+ * @param view a type denoting the enhanced facet desired
+ * @param <N> a subtype of {@link RDFNode}
+ * @return an enhanced node or {@code null} if no match found
+ * @throws OntJenaException.Recursion if a graph recursion is indicated
+ * @see OntEnhGraph#getNodeAs(Node, Class)
+ */
+ <N extends RDFNode> N safeFindNodeAs(Node node, Class<N> view);
+
+ /**
+ * Equivalent to {@code safeFindNodeAs(node, view) != null}.
+ *
+ * @param view {@link RDFNode} type
+ * @param node {@link Node}
+ * @return boolean
+ */
+ default boolean canNodeAs(Class<? extends RDFNode> view, Node node) {
+ return safeFindNodeAs(node, view) != null;
+ }
+
+ /**
+ * @param type {@link X}
+ * @param <X> any {@link OntObject} type
+ * @throws OntJenaException.Unsupported if the {@code type} is not supported by the configuration
+ */
+ default <X extends OntObject> void checkType(Class<X> type) {
+ OntJenaException.checkSupported(getOntPersonality().supports(type),
+ "Profile " + getOntPersonality().getName() + " does not support language construct " +
+ OntEnhNodeFactories.viewAsString(type));
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntEnhNodeFactories.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntEnhNodeFactories.java
new file mode 100644
index 0000000000..5a586b361c
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntEnhNodeFactories.java
@@ -0,0 +1,164 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.ontapi.utils.Iterators;
+import org.apache.jena.ontapi.utils.StdModels;
+import org.apache.jena.ontapi.vocabulary.RDF;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.enhanced.EnhNode;
+import org.apache.jena.graph.FrontsNode;
+import org.apache.jena.graph.Graph;
+import org.apache.jena.graph.Node;
+import org.apache.jena.graph.Triple;
+import org.apache.jena.rdf.model.Model;
+import org.apache.jena.rdf.model.RDFNode;
+import org.apache.jena.rdf.model.Resource;
+import org.apache.jena.rdf.model.Statement;
+import org.apache.jena.reasoner.InfGraph;
+import org.apache.jena.shared.PrefixMapping;
+import org.apache.jena.util.iterator.ExtendedIterator;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+/**
+ * A helper (factory) to produce {@link EnhNodeFactory EnhNode factories} instances or its components.
+ */
+public class OntEnhNodeFactories {
+
+ @SafeVarargs
+ public static EnhNodeFactory createFrom(EnhNodeFinder finder,
+ Class<? extends OntObject> type,
+ Class<? extends OntObject>... types) {
+ return createFrom(finder,
+ Stream.concat(Stream.of(type), Arrays.stream(types)).toList().stream());
+ }
+
+ public static EnhNodeFactory createFrom(EnhNodeFinder finder,
+ Stream<Class<? extends OntObject>> types) {
+ return createMulti(Objects.requireNonNull(finder, "Null finder"), types.map(WrappedEnhNodeFactory::new));
+ }
+
+ public static EnhNodeFactory createFrom(EnhNodeFinder finder,
+ EnhNodeFactory factory,
+ EnhNodeFactory... factories) {
+ return createMulti(Objects.requireNonNull(finder, "Null finder"),
+ Stream.concat(Stream.of(factory), Arrays.stream(factories)).toList().stream());
+ }
+
+ public static EnhNodeFactory createFrom(EnhNodeFactory factory,
+ EnhNodeFactory... factories) {
+ return createMulti(null,
+ Stream.concat(Stream.of(factory), Arrays.stream(factories)).toList().stream());
+ }
+
+ public static EnhNodeFactory createCommon(Class<? extends EnhNode> impl,
+ EnhNodeFinder finder,
+ EnhNodeFilter filter,
+ EnhNodeFilter... additional) {
+ return createCommon(new EnhNodeProducer.Default(impl), finder, filter, additional);
+ }
+
+ public static EnhNodeFactory createCommon(Class<? extends EnhNode> impl,
+ BiFunction<Node, EnhGraph, EnhNode> producer,
+ EnhNodeFinder finder,
+ EnhNodeFilter filter) {
+ return createCommon(new EnhNodeProducer.Default(impl, producer), finder, filter);
+ }
+
+ public static EnhNodeFactory createCommon(EnhNodeProducer maker, EnhNodeFinder finder, EnhNodeFilter primary, EnhNodeFilter... additional) {
+ return new CommonEnhNodeFactoryImpl(Objects.requireNonNull(maker, "Null maker"),
+ Objects.requireNonNull(finder, "Null finder"),
+ Objects.requireNonNull(primary, "Null filter").accumulate(additional));
+ }
+
+ public static EnhNodeFactory createCommon(Class<? extends OntObject> type,
+ EnhNodeProducer maker,
+ EnhNodeFinder finder,
+ EnhNodeFilter filter) {
+ Objects.requireNonNull(type, "Null type");
+ return new CommonEnhNodeFactoryImpl(Objects.requireNonNull(maker, "Null maker"),
+ Objects.requireNonNull(finder, "Null finder"),
+ Objects.requireNonNull(filter, "Null filter")) {
+
+ @Override
+ public String toString() {
+ return String.format("ObjectFactory[%s]", viewAsString(type));
+ }
+ };
+ }
+
+ public static EnhNodeFinder createFinder(Resource... types) {
+ return createFinder(FrontsNode::asNode, types);
+ }
+
+ @SafeVarargs
+ public static <R> EnhNodeFinder createFinder(Function<R, Node> asNode, R... types) {
+ return eg -> Iterators.distinct(listTriplesForTypes(eg.asGraph(), asNode, types).mapWith(Triple::getSubject));
+ }
+
+ private static EnhNodeFactory createMulti(EnhNodeFinder finder, Stream<EnhNodeFactory> factories) {
+ return new CompositeEnhNodeFactoryImpl(finder, null,
+ factories.peek(x -> Objects.requireNonNull(x, "Null component-factory")).toArray(EnhNodeFactory[]::new));
+ }
+
+ @SafeVarargs
+ private static <R> ExtendedIterator<Triple> listTriplesForTypes(Graph g, Function<R, Node> asNode, R... types) {
+ return Iterators.flatMap(Iterators.of(types).mapWith(asNode), t -> g.find(Node.ANY, RDF.Nodes.type, t));
+ }
+
+ /**
+ * Answers a short form of the given class-type.
+ *
+ * @param type {@code Class}-type, not {@code null}
+ * @return String
+ */
+ public static String viewAsString(Class<?> type) {
+ return type.getName().replace(OntObject.class.getPackage().getName() + ".", "");
+ }
+
+ public static String toPrintString(Node node, EnhGraph graph) {
+ if (!(graph instanceof Model m)) {
+ return node.toString(PrefixMapping.Standard);
+ }
+ PrefixMapping pm = PrefixMapping.Factory.create()
+ .setNsPrefixes((PrefixMapping) graph)
+ .setNsPrefixes(PrefixMapping.Standard);
+ if (m.getGraph() instanceof InfGraph) {
+ return node.toString(pm);
+ }
+ RDFNode rdfNode = m.asRDFNode(node);
+ if (!rdfNode.isResource()) {
+ return node.toString(pm);
+ }
+ List<Statement> properties = rdfNode.asResource().listProperties().toList();
+ if (properties.isEmpty()) {
+ return node.toString(pm);
+ }
+ StringBuilder sb = new StringBuilder("\n");
+ properties.forEach(s -> sb.append(StdModels.toString(s, pm)).append("\n"));
+ return sb.toString();
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntObjectPersonalityBuilder.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntObjectPersonalityBuilder.java
new file mode 100644
index 0000000000..def7d95efe
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntObjectPersonalityBuilder.java
@@ -0,0 +1,285 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.model.OntClass;
+import org.apache.jena.ontapi.model.OntEntity;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.enhanced.Implementation;
+import org.apache.jena.enhanced.Personality;
+import org.apache.jena.graph.Node;
+import org.apache.jena.rdf.model.Property;
+import org.apache.jena.rdf.model.RDFNode;
+import org.apache.jena.rdf.model.Resource;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+ * An {@link OntPersonality} builder.
+ * This must be the only place to create various {@code OntPersonality} objects.
+ * <p>
+ * Created by @szz on 17.01.2019.
+ */
+@SuppressWarnings("WeakerAccess")
+public class OntObjectPersonalityBuilder {
+ private final Map<Class<? extends OntObject>, Function<OntConfig, EnhNodeFactory>> extFactories = new HashMap<>();
+ private final Map<Class<? extends RDFNode>, Implementation> stdFactories = new HashMap<>();
+
+ private String name;
+ private OntPersonality.Punnings punnings;
+ private OntPersonality.Builtins builtins;
+ private OntPersonality.Reserved reserved;
+ private OntConfig config;
+
+ /**
+ * Makes a full copy of the given {@link OntPersonality}
+ * in the form of modifiable {@link OntObjectPersonalityBuilder builder}.
+ *
+ * @param from {@link OntPersonality} to copy settings, not {@code null}
+ * @return {@link OntObjectPersonalityBuilder}
+ */
+ public static OntObjectPersonalityBuilder from(OntPersonality from) {
+ return new OntObjectPersonalityBuilder()
+ .addPersonality(OntPersonality.asJenaPersonality(from))
+ .setPunnings(from.getPunnings())
+ .setBuiltins(from.getBuiltins())
+ .setReserved(from.getReserved())
+ .setConfig(from.getConfig());
+ }
+
+ private static <X> X require(X obj, Class<X> type) {
+ if (obj == null) {
+ throw new IllegalStateException("The " + type.getSimpleName() + " Vocabulary must be present in builder.");
+ }
+ return obj;
+ }
+
+ @SuppressWarnings("rawtypes")
+ private static <V extends ResourceVocabulary> V hasSpec(V voc, Class... types) {
+ Objects.requireNonNull(voc);
+ @SuppressWarnings("unchecked") Set<?> errors = Arrays.stream(types).filter(x -> !voc.supports(x)).collect(Collectors.toSet());
+ if (errors.isEmpty()) return voc;
+ throw new IllegalArgumentException("The vocabulary " + voc + " has missed required types: " + errors);
+ }
+
+ /**
+ * Makes a full copy of this builder.
+ *
+ * @return {@link OntObjectPersonalityBuilder}, a copy
+ */
+ public OntObjectPersonalityBuilder copy() {
+ OntObjectPersonalityBuilder res = new OntObjectPersonalityBuilder();
+ res.stdFactories.putAll(this.stdFactories);
+ res.extFactories.putAll(this.extFactories);
+ res.setName(name);
+ if (punnings != null) res.setPunnings(punnings);
+ if (builtins != null) res.setBuiltins(builtins);
+ if (reserved != null) res.setReserved(reserved);
+ if (config != null) res.setConfig(config);
+ return res;
+ }
+
+ /**
+ * Adds all factories from the specified builder.
+ * @param other {@link OntObjectPersonalityBuilder}
+ * @return this builder
+ */
+ public OntObjectPersonalityBuilder add(OntObjectPersonalityBuilder other) {
+ extFactories.putAll(other.extFactories);
+ stdFactories.putAll(other.stdFactories);
+ return this;
+ }
+
+ /**
+ * Associates the specified {@link EnhNodeFactory factory} with the specified {@link OntObject object} type.
+ * If the builder previously contained a mapping for the object type,
+ * the old factory is replaced by the specified factory.
+ * <p>
+ * Note: the {@link EnhNodeFactory factory} must not explicitly refer to another factory,
+ * instead it may contain implicit references through
+ * {@link OntEnhGraph#asPersonalityModel(EnhGraph)} method.
+ * For example, if you need a check, that some {@link Node node} is an OWL-Class inside your factory,
+ * you can use {@link OntEnhGraph#canAs(Class, Node, EnhGraph)}
+ * with the type {@link OntClass.Named}.
+ *
+ * @param type {@code Class}-type of the concrete {@link OntObject}.
+ * @param factory {@link EnhNodeFactory} the factory to produce the instances of the {@code type}
+ * @return this builder
+ */
+ public OntObjectPersonalityBuilder add(Class<? extends OntObject> type, EnhNodeFactory factory) {
+ return add(type, config -> factory);
+ }
+
+ /**
+ * Associates the specified {@link EnhNodeFactory factory} producer with the specified {@link OntObject object} type.
+ * If the builder previously contained a mapping for the object type,
+ * the old factory is replaced by the specified factory.
+ * <p>
+ * Note: the {@link EnhNodeFactory factory} must not explicitly refer to another factory,
+ * instead it may contain implicit references through
+ * {@link OntEnhGraph#asPersonalityModel(EnhGraph)} method.
+ * For example, if you need a check, that some {@link Node node} is an OWL-Class inside your factory,
+ * you can use {@link OntEnhGraph#canAs(Class, Node, EnhGraph)}
+ * with the type {@link OntClass.Named}.
+ *
+ * @param type {@code Class}-type of the concrete {@link OntObject}.
+ * @param factory {@code Function}, providing {@link EnhNodeFactory} by the {@link OntConfig}
+ * @return this builder
+ */
+ public OntObjectPersonalityBuilder add(Class<? extends OntObject> type, Function<OntConfig, EnhNodeFactory> factory) {
+ extFactories.put(type, factory);
+ return this;
+ }
+
+ /**
+ * Removes object factory.
+ *
+ * @param type {@code Class}-type of {@link OntObject}
+ * @return this builder
+ */
+ public OntObjectPersonalityBuilder remove(Class<? extends OntObject> type) {
+ extFactories.remove(type);
+ stdFactories.remove(type);
+ return this;
+ }
+
+ /**
+ * Adds everything from the specified {@link Personality Jena Personality} to the existing internal collection.
+ *
+ * @param from {@link Personality} with generic type {@link RDFNode}, not {@code null}
+ * @return this builder
+ * @see Personality#add(Personality)
+ */
+ public OntObjectPersonalityBuilder addPersonality(Personality<RDFNode> from) {
+ stdFactories.putAll(new JenaPersonalityAccessor(from).getMap());
+ return this;
+ }
+
+ /**
+ * Sets identifier of language profile ("OWL", "RDF").
+ *
+ * @param profileName String, can be {@code null}
+ * @return this builder
+ */
+ public OntObjectPersonalityBuilder setName(String profileName) {
+ this.name = profileName;
+ return this;
+ }
+
+ /**
+ * Sets a new punnings personality vocabulary.
+ *
+ * @param punnings {@link OntPersonality.Punnings}, not {@code null}
+ * @return this builder
+ */
+ public OntObjectPersonalityBuilder setPunnings(OntPersonality.Punnings punnings) {
+ this.punnings = hasSpec(punnings, getEntityTypes());
+ return this;
+ }
+
+ /**
+ * Sets a new builtins personality vocabulary.
+ *
+ * @param builtins {@link OntPersonality.Builtins}, not {@code null}
+ * @return this builder
+ */
+ public OntObjectPersonalityBuilder setBuiltins(OntPersonality.Builtins builtins) {
+ this.builtins = hasSpec(builtins, getEntityTypes());
+ return this;
+ }
+
+ /**
+ * Sets a new reserved personality vocabulary.
+ *
+ * @param reserved {@link OntPersonality.Reserved}, not {@code null}
+ * @return this builder
+ */
+ public OntObjectPersonalityBuilder setReserved(OntPersonality.Reserved reserved) {
+ this.reserved = hasSpec(reserved, Resource.class, Property.class);
+ return this;
+ }
+
+ /**
+ * Sets config, which controls OntModel behaviour.
+ *
+ * @param config {@link OntConfig}, not {@code null}
+ * @return this builder
+ */
+ public OntObjectPersonalityBuilder setConfig(OntConfig config) {
+ this.config = Objects.requireNonNull(config);
+ return this;
+ }
+
+ /**
+ * Builds a new personality configuration.
+ *
+ * @return {@link OntPersonality}, fresh instance
+ * @throws IllegalStateException in case the builder does not contain require components
+ */
+ public OntPersonality build() throws IllegalStateException {
+ OntConfig config = config();
+ OntPersonality.Punnings punnings = punnings();
+ OntPersonality.Builtins builtins = builtins();
+ OntPersonality.Reserved reserved = reserved();
+ OntPersonalityImpl res = new OntPersonalityImpl(name, config, punnings, builtins, reserved);
+ stdFactories.forEach(res::add);
+ extFactories.forEach((type, factory) -> res.register(type, factory.apply(config)));
+ return res;
+ }
+
+ private Class<?>[] getEntityTypes() {
+ return OntEntity.TYPES.toArray(Class[]::new);
+ }
+
+ private OntPersonality.Punnings punnings() {
+ return require(punnings, OntPersonality.Punnings.class);
+ }
+
+ private OntPersonality.Builtins builtins() {
+ return require(builtins, OntPersonality.Builtins.class);
+ }
+
+ private OntPersonality.Reserved reserved() {
+ return require(reserved, OntPersonality.Reserved.class);
+ }
+
+ private OntConfig config() {
+ return Objects.requireNonNull(config, "No config is set");
+ }
+
+ private static class JenaPersonalityAccessor extends Personality<RDFNode> {
+
+ public JenaPersonalityAccessor(Personality<RDFNode> other) {
+ super(other);
+ }
+
+ @Override
+ protected Map<Class<? extends RDFNode>, Implementation> getMap() {
+ return super.getMap();
+ }
+ }
+
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntPersonalities.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntPersonalities.java
new file mode 100644
index 0000000000..56551851fa
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntPersonalities.java
@@ -0,0 +1,753 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.impl.factories.OWL1ObjectFactories;
+import org.apache.jena.ontapi.impl.factories.OWL2ObjectFactories;
+import org.apache.jena.ontapi.impl.factories.RDFSObjectFactories;
+import org.apache.jena.ontapi.impl.factories.STDObjectFactories;
+import org.apache.jena.ontapi.impl.factories.SWRLObjectFactories;
+import org.apache.jena.ontapi.model.OntAnnotation;
+import org.apache.jena.ontapi.model.OntAnnotationProperty;
+import org.apache.jena.ontapi.model.OntClass;
+import org.apache.jena.ontapi.model.OntDataProperty;
+import org.apache.jena.ontapi.model.OntDataRange;
+import org.apache.jena.ontapi.model.OntDisjoint;
+import org.apache.jena.ontapi.model.OntEntity;
+import org.apache.jena.ontapi.model.OntFacetRestriction;
+import org.apache.jena.ontapi.model.OntID;
+import org.apache.jena.ontapi.model.OntIndividual;
+import org.apache.jena.ontapi.model.OntModel;
+import org.apache.jena.ontapi.model.OntNamedProperty;
+import org.apache.jena.ontapi.model.OntNegativeAssertion;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.ontapi.model.OntObjectProperty;
+import org.apache.jena.ontapi.model.OntProperty;
+import org.apache.jena.ontapi.model.OntRelationalProperty;
+import org.apache.jena.ontapi.model.OntSWRL;
+import org.apache.jena.ontapi.utils.StdModels;
+import org.apache.jena.ontapi.vocabulary.OWL;
+import org.apache.jena.enhanced.Personality;
+import org.apache.jena.graph.Node;
+import org.apache.jena.rdf.model.Alt;
+import org.apache.jena.rdf.model.Bag;
+import org.apache.jena.rdf.model.Container;
+import org.apache.jena.rdf.model.Literal;
+import org.apache.jena.rdf.model.Property;
+import org.apache.jena.rdf.model.RDFList;
+import org.apache.jena.rdf.model.RDFNode;
+import org.apache.jena.rdf.model.Resource;
+import org.apache.jena.rdf.model.Seq;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * Settings and personalities that are used for constructing {@link OntModel}.
+ * An access point to several predefined {@link OntPersonality Ontology Personality} constants.
+ */
+@SuppressWarnings("WeakerAccess")
+public class OntPersonalities {
+
+ public static final OntPersonality.Builtins RDFS_BUILTINS = createBuiltinsVocabulary(OntVocabulary.RDFS);
+ public static final OntPersonality.Builtins OWL2_FULL_BUILTINS = createBuiltinsVocabulary(
+ OntVocabulary.OWL2_FULL.and(OntVocabulary.DC).and(OntVocabulary.SKOS).and(OntVocabulary.SWRL));
+ public static final OntPersonality.Builtins OWL2_EL_BUILTINS = createBuiltinsVocabulary(OntVocabulary.OWL2_EL);
+ public static final OntPersonality.Builtins OWL2_QL_BUILTINS = createBuiltinsVocabulary(OntVocabulary.OWL2_QL);
+ public static final OntPersonality.Builtins OWL2_RL_BUILTINS = createBuiltinsVocabulary(OntVocabulary.OWL2_RL);
+ public static final OntPersonality.Builtins OWL1_FULL_BUILTINS = createBuiltinsVocabulary(OntVocabulary.OWL1_FULL);
+ public static final OntPersonality.Builtins OWL1_LITE_BUILTINS = createBuiltinsVocabulary(OntVocabulary.OWL1_LITE);
+
+ public static final OntPersonality.Reserved RDFS_RESERVED = createReservedVocabulary(OntVocabulary.RDFS);
+ public static final OntPersonality.Reserved OWL2_RESERVED = createReservedVocabulary(
+ OntVocabulary.OWL2_FULL.and(OntVocabulary.DC).and(OntVocabulary.SKOS).and(OntVocabulary.SWRL));
+ public static final OntPersonality.Reserved OWL1_RESERVED = createReservedVocabulary(OntVocabulary.OWL1_FULL);
+
+ public static final OntPersonality.Punnings OWL_DL1_PUNNINGS = createPunningsVocabulary(PunningsMode.DL1_COMPATIBLE);
+ public static final OntPersonality.Punnings OWL_DL2_PUNNINGS = createPunningsVocabulary(PunningsMode.DL2);
+ public static final OntPersonality.Punnings OWL_DL_WEAK_PUNNINGS = createPunningsVocabulary(PunningsMode.DL_WEAK);
+ public static final OntPersonality.Punnings OWL_NO_PUNNINGS = createPunningsVocabulary(PunningsMode.FULL);
+ public static final OntPersonality.Punnings RDFS_NO_PUNNINGS = createPunningsVocabulary(PunningsMode.FULL);
+
+ /**
+ * Standard resources. Private access since this constant is mutable.
+ *
+ * @see org.apache.jena.enhanced.BuiltinPersonalities#model
+ */
+ public static final Personality<RDFNode> STANDARD_PERSONALITY = new Personality<RDFNode>()
+ .add(RDFNode.class, STDObjectFactories.NODE)
+ .add(Resource.class, STDObjectFactories.RESOURCE)
+ .add(Property.class, STDObjectFactories.PROPERTY)
+ .add(Literal.class, STDObjectFactories.LITERAL)
+ .add(Container.class, STDObjectFactories.RESOURCE)
+ .add(Alt.class, STDObjectFactories.ALT)
+ .add(Bag.class, STDObjectFactories.BAG)
+ .add(Seq.class, STDObjectFactories.SEQ)
+ .add(RDFList.class, STDObjectFactories.RDF_LIST);
+
+ /**
+ * For RDFS Ontologies, limited functionality.
+ *
+ * @see <a href='https://www.w3.org/TR/rdf12-schema/'>RDF 1.2 Schema</a>
+ */
+ private static final OntObjectPersonalityBuilder RDFS_OBJECT_FACTORIES = templatePersonalityBuilder()
+ .setName("RDFS")
+ .addPersonality(STANDARD_PERSONALITY)
+ .add(OntObject.class, RDFSObjectFactories.ANY_OBJECT)
+ .add(OntEntity.class, RDFSObjectFactories.ANY_ENTITY)
+ .add(OntIndividual.Named.class, RDFSObjectFactories.NAMED_INDIVIDUAL)
+ .add(OntIndividual.Anonymous.class, RDFSObjectFactories.ANONYMOUS_INDIVIDUAL)
+ .add(OntIndividual.class, RDFSObjectFactories.ANY_INDIVIDUAL)
+ .add(OntProperty.class, RDFSObjectFactories.PROPERTY)
+ .add(OntAnnotationProperty.class, RDFSObjectFactories.ANNOTATION_PROPERTY)
+ .add(OntClass.class, RDFSObjectFactories.ANY_CLASS)
+ .add(OntClass.Named.class, RDFSObjectFactories.NAMED_CLASS);
+
+ /**
+ * Default personality builder for SWRL. Private access since this constant is mutable.
+ */
+ private static final OntObjectPersonalityBuilder SWRL_OBJECT_FACTORIES = templatePersonalityBuilder()
+ .add(OntSWRL.Variable.class, SWRLObjectFactories.VARIABLE_SWRL)
+ .add(OntSWRL.Builtin.class, SWRLObjectFactories.BUILTIN_SWRL)
+ .add(OntSWRL.IArg.class, SWRLObjectFactories.IARG_SWRL)
+ .add(OntSWRL.DArg.class, SWRLObjectFactories.DARG_SWRL)
+ .add(OntSWRL.Arg.class, SWRLObjectFactories.ANY_ARG_SWRL)
+ .add(OntSWRL.Atom.WithBuiltin.class, SWRLObjectFactories.BUILT_IN_ATOM_SWRL)
+ .add(OntSWRL.Atom.WithClass.class, SWRLObjectFactories.CLASS_ATOM_SWRL)
+ .add(OntSWRL.Atom.WithDataRange.class, SWRLObjectFactories.DATA_RANGE_ATOM_SWRL)
+ .add(OntSWRL.Atom.WithObjectProperty.class, SWRLObjectFactories.INDIVIDUAL_ATOM_SWRL)
+ .add(OntSWRL.Atom.WithDataProperty.class, SWRLObjectFactories.DATA_VALUED_ATOM_SWRL)
+ .add(OntSWRL.Atom.WithDifferentIndividuals.class, SWRLObjectFactories.DIFFERENT_INDIVIDUALS_ATOM_SWRL)
+ .add(OntSWRL.Atom.WithSameIndividuals.class, SWRLObjectFactories.SAME_INDIVIDUALS_ATOM_SWRL)
+ .add(OntSWRL.Atom.Unary.class, SWRLObjectFactories.ANY_UNARY_ATOM_SWRL)
+ .add(OntSWRL.Atom.Binary.class, SWRLObjectFactories.ANY_BINARY_ATOM_SWRL)
+ .add(OntSWRL.Atom.class, SWRLObjectFactories.ANY_ATOM_SWRL)
+ .add(OntSWRL.Imp.class, SWRLObjectFactories.IMPL_SWRL)
+ .add(OntSWRL.class, SWRLObjectFactories.ANY_OBJECT_SWRL);
+
+ /**
+ * Default personality builder for OWL2 (FULL + DL) and SWRL. Private access since this constant is mutable.
+ */
+ private static final OntObjectPersonalityBuilder OWL2_OBJECT_FACTORIES = templatePersonalityBuilder()
+ .setName("OWL2")
+ .addPersonality(STANDARD_PERSONALITY)
+ // the base ontology object:
+ .add(OntObject.class, OWL2ObjectFactories.ANY_OBJECT)
+
+ // ont-id:
+ .add(OntID.class, OWL2ObjectFactories.ID)
+
+ // annotation object:
+ .add(OntAnnotation.class, OWL2ObjectFactories.ANNOTATION)
+
+ // entities:
+ .add(OntClass.Named.class, OWL2ObjectFactories.NAMED_CLASS)
+ .add(OntDataRange.Named.class, OWL2ObjectFactories.NAMED_DATARANGE)
+ .add(OntIndividual.Named.class, OWL2ObjectFactories.NAMED_INDIVIDUAL)
+ .add(OntObjectProperty.Named.class, OWL2ObjectFactories.NAMED_OBJECT_PROPERTY)
+ .add(OntDataProperty.class, OWL2ObjectFactories.DATATYPE_PROPERTY)
+ .add(OntAnnotationProperty.class, OWL2ObjectFactories.ANNOTATION_PROPERTY)
+ .add(OntEntity.class, OWL2ObjectFactories.ANY_ENTITY)
+
+ // individuals:
+ .add(OntIndividual.Anonymous.class, OWL2ObjectFactories.ANONYMOUS_INDIVIDUAL)
+ .add(OntIndividual.class, OWL2ObjectFactories.ANY_INDIVIDUAL)
+
+ // property expressions:
+ .add(OntObjectProperty.Inverse.class, OWL2ObjectFactories.INVERSE_OBJECT_PROPERTY)
+ .add(OntObjectProperty.class, OWL2ObjectFactories.OBJECT_PROPERTY)
+ .add(OntRelationalProperty.class, OWL2ObjectFactories.ANY_DATA_OR_OBJECT_PROPERTY)
+ .add(OntNamedProperty.class, OWL2ObjectFactories.ANY_NAMED_PROPERTY)
+ .add(OntProperty.class, OWL2ObjectFactories.ANY_PROPERTY)
+
+ // class expressions:
+ .add(OntClass.ObjectSomeValuesFrom.class, OWL2ObjectFactories.OBJECT_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.DataSomeValuesFrom.class, OWL2ObjectFactories.DATA_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.ObjectAllValuesFrom.class, OWL2ObjectFactories.OBJECT_ALL_VALUES_FROM_CLASS)
+ .add(OntClass.DataAllValuesFrom.class, OWL2ObjectFactories.DATA_ALL_VALUES_FROM_CLASS)
+ .add(OntClass.ObjectHasValue.class, OWL2ObjectFactories.OBJECT_HAS_VALUE_CLASS)
+ .add(OntClass.DataHasValue.class, OWL2ObjectFactories.DATA_HAS_VALUE_CLASS)
+ .add(OntClass.ObjectMinCardinality.class, OWL2ObjectFactories.OBJECT_MIN_CARDINALITY_CLASS)
+ .add(OntClass.DataMinCardinality.class, OWL2ObjectFactories.DATA_MIN_CARDINALITY_CLASS)
+ .add(OntClass.ObjectMaxCardinality.class, OWL2ObjectFactories.OBJECT_MAX_CARDINALITY_CLASS)
+ .add(OntClass.DataMaxCardinality.class, OWL2ObjectFactories.DATA_MAX_CARDINALITY_CLASS)
+ .add(OntClass.ObjectCardinality.class, OWL2ObjectFactories.OBJECT_CARDINALITY_CLASS)
+ .add(OntClass.DataCardinality.class, OWL2ObjectFactories.DATA_CARDINALITY_CLASS)
+ .add(OntClass.HasSelf.class, OWL2ObjectFactories.HAS_SELF_CLASS)
+ .add(OntClass.UnionOf.class, OWL2ObjectFactories.UNION_OF_CLASS)
+ .add(OntClass.OneOf.class, OWL2ObjectFactories.ONE_OF_CLASS)
+ .add(OntClass.IntersectionOf.class, OWL2ObjectFactories.INTERSECTION_OF_CLASS)
+ .add(OntClass.ComplementOf.class, OWL2ObjectFactories.COMPLEMENT_OF_CLASS)
+ .add(OntClass.NaryDataAllValuesFrom.class, OWL2ObjectFactories.NARY_DATA_ALL_VALUES_FROM_CLASS)
+ .add(OntClass.NaryDataSomeValuesFrom.class, OWL2ObjectFactories.NARY_DATA_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.LogicalExpression.class, OWL2ObjectFactories.ANY_LOGICAL_CLASS)
+ .add(OntClass.CollectionOf.class, OWL2ObjectFactories.ANY_COLLECTION_OF_CLASS)
+ .add(OntClass.ValueRestriction.class, OWL2ObjectFactories.ANY_VALUE_RESTRICTION_CLASS)
+ .add(OntClass.CardinalityRestriction.class, OWL2ObjectFactories.ANY_CARDINALITY_RESTRICTION_CLASS)
+ .add(OntClass.ComponentRestriction.class, OWL2ObjectFactories.ANY_COMPONENT_RESTRICTION_CLASS)
+ .add(OntClass.UnaryRestriction.class, OWL2ObjectFactories.ANY_UNARY_RESTRICTION_CLASS)
+ .add(OntClass.Restriction.class, OWL2ObjectFactories.ANY_RESTRICTION_CLASS)
+ .add(OntClass.class, OWL2ObjectFactories.ANY_CLASS)
+
+ // data ranges:
+ .add(OntDataRange.OneOf.class, OWL2ObjectFactories.ONE_OF_DATARANGE)
+ .add(OntDataRange.Restriction.class, OWL2ObjectFactories.RESTRICTION_DATARANGE)
+ .add(OntDataRange.ComplementOf.class, OWL2ObjectFactories.COMPLEMENT_OF_DATARANGE)
+ .add(OntDataRange.UnionOf.class, OWL2ObjectFactories.UNION_OF_DATARANGE)
+ .add(OntDataRange.IntersectionOf.class, OWL2ObjectFactories.INTERSECTION_OF_DATARANGE)
+ .add(OntDataRange.Combination.class, OWL2ObjectFactories.ANY_COMPONENTS_DATARANGE)
+ .add(OntDataRange.class, OWL2ObjectFactories.ANY_DATARANGE)
+
+ // facet restrictions:
+ .add(OntFacetRestriction.Length.class, OWL2ObjectFactories.LENGTH_FACET_RESTRICTION)
+ .add(OntFacetRestriction.MinLength.class, OWL2ObjectFactories.MIN_LENGTH_FACET_RESTRICTION)
+ .add(OntFacetRestriction.MaxLength.class, OWL2ObjectFactories.MAX_LENGTH_FACET_RESTRICTION)
+ .add(OntFacetRestriction.MinInclusive.class, OWL2ObjectFactories.MIN_INCLUSIVE_FACET_RESTRICTION)
+ .add(OntFacetRestriction.MaxInclusive.class, OWL2ObjectFactories.MAX_INCLUSIVE_FACET_RESTRICTION)
+ .add(OntFacetRestriction.MinExclusive.class, OWL2ObjectFactories.MIN_EXCLUSIVE_FACET_RESTRICTION)
+ .add(OntFacetRestriction.MaxExclusive.class, OWL2ObjectFactories.MAX_EXCLUSIVE_FACET_RESTRICTION)
+ .add(OntFacetRestriction.Pattern.class, OWL2ObjectFactories.PATTERN_FACET_RESTRICTION)
+ .add(OntFacetRestriction.TotalDigits.class, OWL2ObjectFactories.TOTAL_DIGITS_FACET_RESTRICTION)
+ .add(OntFacetRestriction.FractionDigits.class, OWL2ObjectFactories.FRACTION_DIGITS_FACET_RESTRICTION)
+ .add(OntFacetRestriction.LangRange.class, OWL2ObjectFactories.LANG_RANGE_FACET_RESTRICTION)
+ .add(OntFacetRestriction.class, OWL2ObjectFactories.ANY_FACET_RESTRICTION)
+
+ // negative property assertions:
+ .add(OntNegativeAssertion.WithObjectProperty.class, OWL2ObjectFactories.OBJECT_NEGATIVE_PROPERTY_ASSERTION)
+ .add(OntNegativeAssertion.WithDataProperty.class, OWL2ObjectFactories.DATA_NEGATIVE_PROPERTY_ASSERTION)
+ .add(OntNegativeAssertion.class, OWL2ObjectFactories.ANY_NEGATIVE_PROPERTY_ASSERTION)
+
+ // disjoint anonymous collections:
+ .add(OntDisjoint.Classes.class, OWL2ObjectFactories.CLASSES_DISJOINT)
+ .add(OntDisjoint.Individuals.class, OWL2ObjectFactories.DIFFERENT_INDIVIDUALS_DISJOINT)
+ .add(OntDisjoint.ObjectProperties.class, OWL2ObjectFactories.OBJECT_PROPERTIES_DISJOINT)
+ .add(OntDisjoint.DataProperties.class, OWL2ObjectFactories.DATA_PROPERTIES_DISJOINT)
+ .add(OntDisjoint.Properties.class, OWL2ObjectFactories.ANY_PROPERTIES_DISJOINT)
+ .add(OntDisjoint.class, OWL2ObjectFactories.ANY_DISJOINT)
+
+ // SWRL objects:
+ .add(SWRL_OBJECT_FACTORIES);
+
+ /**
+ * Default personality builder for OWL2 EL. Private access since this constant is mutable.
+ *
+ * @see <a href="https://www.w3.org/TR/owl2-profiles/#OWL_2_EL">OWL 2 EL</a>
+ */
+ private static final OntObjectPersonalityBuilder OWL2_EL_OBJECT_FACTORIES = templatePersonalityBuilder()
+ .setName("OWL2-EL")
+ .addPersonality(STANDARD_PERSONALITY)
+ // the base ontology object:
+ .add(OntObject.class, OWL2ObjectFactories.ANY_OBJECT)
+
+ // ont-id:
+ .add(OntID.class, OWL2ObjectFactories.ID)
+
+ // annotation object:
+ .add(OntAnnotation.class, OWL2ObjectFactories.ANNOTATION)
+
+ // entities:
+ .add(OntClass.Named.class, OWL2ObjectFactories.NAMED_CLASS)
+ .add(OntDataRange.Named.class, OWL2ObjectFactories.NAMED_DATARANGE)
+ .add(OntIndividual.Named.class, OWL2ObjectFactories.NAMED_INDIVIDUAL)
+ .add(OntObjectProperty.Named.class, OWL2ObjectFactories.NAMED_OBJECT_PROPERTY)
+ .add(OntDataProperty.class, OWL2ObjectFactories.DATATYPE_PROPERTY)
+ .add(OntAnnotationProperty.class, OWL2ObjectFactories.ANNOTATION_PROPERTY)
+ .add(OntEntity.class, OWL2ObjectFactories.ANY_ENTITY)
+
+ // individuals:
+ .add(OntIndividual.class, OWL2ObjectFactories.EL_ANY_INDIVIDUAL)
+
+ // property expressions:
+ .add(OntObjectProperty.class, OWL2ObjectFactories.EL_OBJECT_PROPERTY)
+ .add(OntRelationalProperty.class, OWL2ObjectFactories.EL_ANY_DATA_OR_OBJECT_PROPERTY)
+ .add(OntNamedProperty.class, OWL2ObjectFactories.ANY_NAMED_PROPERTY)
+ .add(OntProperty.class, OWL2ObjectFactories.ANY_PROPERTY)
+
+ // class expressions:
+ .add(OntClass.ObjectSomeValuesFrom.class, OWL2ObjectFactories.OBJECT_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.DataSomeValuesFrom.class, OWL2ObjectFactories.DATA_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.ObjectHasValue.class, OWL2ObjectFactories.OBJECT_HAS_VALUE_CLASS)
+ .add(OntClass.DataHasValue.class, OWL2ObjectFactories.DATA_HAS_VALUE_CLASS)
+ .add(OntClass.HasSelf.class, OWL2ObjectFactories.HAS_SELF_CLASS)
+ .add(OntClass.OneOf.class, OWL2ObjectFactories.EL_ONE_OF_CLASS)
+ .add(OntClass.IntersectionOf.class, OWL2ObjectFactories.INTERSECTION_OF_CLASS)
+ .add(OntClass.LogicalExpression.class, OWL2ObjectFactories.EL_ANY_LOGICAL_CLASS)
+ .add(OntClass.CollectionOf.class, OWL2ObjectFactories.EL_ANY_COLLECTION_OF_CLASS)
+ .add(OntClass.ValueRestriction.class, OWL2ObjectFactories.EL_ANY_VALUE_RESTRICTION_CLASS)
+ .add(OntClass.ComponentRestriction.class, OWL2ObjectFactories.EL_ANY_COMPONENT_RESTRICTION_CLASS)
+ .add(OntClass.UnaryRestriction.class, OWL2ObjectFactories.EL_ANY_UNARY_RESTRICTION_CLASS)
+ .add(OntClass.Restriction.class, OWL2ObjectFactories.EL_ANY_RESTRICTION_CLASS)
+ .add(OntClass.class, OWL2ObjectFactories.EL_ANY_CLASS)
+
+ // data ranges:
+ .add(OntDataRange.OneOf.class, OWL2ObjectFactories.EL_ONE_OF_DATARANGE)
+ .add(OntDataRange.IntersectionOf.class, OWL2ObjectFactories.INTERSECTION_OF_DATARANGE)
+ .add(OntDataRange.Combination.class, OWL2ObjectFactories.EL_ANY_COMPONENTS_DATARANGE)
+ .add(OntDataRange.class, OWL2ObjectFactories.EL_ANY_DATARANGE)
+
+ // negative property assertions:
+ .add(OntNegativeAssertion.WithObjectProperty.class, OWL2ObjectFactories.OBJECT_NEGATIVE_PROPERTY_ASSERTION)
+ .add(OntNegativeAssertion.WithDataProperty.class, OWL2ObjectFactories.DATA_NEGATIVE_PROPERTY_ASSERTION)
+ .add(OntNegativeAssertion.class, OWL2ObjectFactories.ANY_NEGATIVE_PROPERTY_ASSERTION)
+
+ // disjoint anonymous collections:
+ .add(OntDisjoint.Classes.class, OWL2ObjectFactories.CLASSES_DISJOINT)
+ .add(OntDisjoint.Individuals.class, OWL2ObjectFactories.DIFFERENT_INDIVIDUALS_DISJOINT)
+ .add(OntDisjoint.class, OWL2ObjectFactories.EL_ANY_DISJOINT);
+
+ /**
+ * Default personality builder for OWL2 QL. Private access since this constant is mutable.
+ */
+ private static final OntObjectPersonalityBuilder OWL2_QL_OBJECT_FACTORIES = templatePersonalityBuilder()
+ .setName("OWL2-QL")
+ .addPersonality(STANDARD_PERSONALITY)
+ // the base ontology object:
+ .add(OntObject.class, OWL2ObjectFactories.ANY_OBJECT)
+
+ // ont-id:
+ .add(OntID.class, OWL2ObjectFactories.ID)
+
+ // annotation object:
+ .add(OntAnnotation.class, OWL2ObjectFactories.ANNOTATION)
+
+ // entities:
+ .add(OntClass.Named.class, OWL2ObjectFactories.NAMED_CLASS)
+ .add(OntDataRange.Named.class, OWL2ObjectFactories.NAMED_DATARANGE)
+ .add(OntIndividual.Named.class, OWL2ObjectFactories.NAMED_INDIVIDUAL)
+ .add(OntObjectProperty.Named.class, OWL2ObjectFactories.NAMED_OBJECT_PROPERTY)
+ .add(OntDataProperty.class, OWL2ObjectFactories.DATATYPE_PROPERTY)
+ .add(OntAnnotationProperty.class, OWL2ObjectFactories.ANNOTATION_PROPERTY)
+ .add(OntEntity.class, OWL2ObjectFactories.ANY_ENTITY)
+
+ // individuals:
+ .add(OntIndividual.Anonymous.class, OWL2ObjectFactories.ANONYMOUS_INDIVIDUAL)
+ .add(OntIndividual.class, OWL2ObjectFactories.QL_ANY_INDIVIDUAL)
+
+ // property expressions:
+ .add(OntObjectProperty.Inverse.class, OWL2ObjectFactories.INVERSE_OBJECT_PROPERTY)
+ .add(OntObjectProperty.class, OWL2ObjectFactories.OBJECT_PROPERTY)
+ .add(OntRelationalProperty.class, OWL2ObjectFactories.ANY_DATA_OR_OBJECT_PROPERTY)
+ .add(OntNamedProperty.class, OWL2ObjectFactories.ANY_NAMED_PROPERTY)
+ .add(OntProperty.class, OWL2ObjectFactories.ANY_PROPERTY)
+
+ // class expressions:
+ .add(OntClass.ObjectSomeValuesFrom.class, OWL2ObjectFactories.QL_OBJECT_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.DataSomeValuesFrom.class, OWL2ObjectFactories.QL_DATA_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.IntersectionOf.class, OWL2ObjectFactories.QL_INTERSECTION_OF_CLASS)
+ .add(OntClass.ComplementOf.class, OWL2ObjectFactories.QL_COMPLEMENT_OF_CLASS)
+ .add(OntClass.NaryDataAllValuesFrom.class, OWL2ObjectFactories.NARY_DATA_ALL_VALUES_FROM_CLASS)
+ .add(OntClass.NaryDataSomeValuesFrom.class, OWL2ObjectFactories.NARY_DATA_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.LogicalExpression.class, OWL2ObjectFactories.QL_ANY_LOGICAL_CLASS)
+ .add(OntClass.CollectionOf.class, OWL2ObjectFactories.QL_ANY_COLLECTION_OF_CLASS)
+ .add(OntClass.ValueRestriction.class, OWL2ObjectFactories.QL_ANY_VALUE_RESTRICTION_CLASS)
+ .add(OntClass.ComponentRestriction.class, OWL2ObjectFactories.QL_ANY_COMPONENT_RESTRICTION_CLASS)
+ .add(OntClass.UnaryRestriction.class, OWL2ObjectFactories.QL_ANY_UNARY_RESTRICTION_CLASS)
+ .add(OntClass.Restriction.class, OWL2ObjectFactories.QL_ANY_RESTRICTION_CLASS)
+ .add(OntClass.class, OWL2ObjectFactories.QL_ANY_CLASS)
+
+ // data ranges:
+ .add(OntDataRange.IntersectionOf.class, OWL2ObjectFactories.INTERSECTION_OF_DATARANGE)
+ .add(OntDataRange.Combination.class, OWL2ObjectFactories.QL_ANY_COMPONENTS_DATARANGE)
+ .add(OntDataRange.class, OWL2ObjectFactories.QL_ANY_DATARANGE)
+
+ // disjoint anonymous collections:
+ .add(OntDisjoint.Classes.class, OWL2ObjectFactories.CLASSES_DISJOINT)
+ .add(OntDisjoint.Individuals.class, OWL2ObjectFactories.DIFFERENT_INDIVIDUALS_DISJOINT)
+ .add(OntDisjoint.ObjectProperties.class, OWL2ObjectFactories.OBJECT_PROPERTIES_DISJOINT)
+ .add(OntDisjoint.DataProperties.class, OWL2ObjectFactories.DATA_PROPERTIES_DISJOINT)
+ .add(OntDisjoint.Properties.class, OWL2ObjectFactories.ANY_PROPERTIES_DISJOINT)
+ .add(OntDisjoint.class, OWL2ObjectFactories.ANY_DISJOINT);
+
+ /**
+ * Default personality builder for OWL2 RL. Private access since this constant is mutable.
+ */
+ private static final OntObjectPersonalityBuilder OWL2_RL_OBJECT_FACTORIES = templatePersonalityBuilder()
+ .setName("OWL2-RL")
+ .addPersonality(STANDARD_PERSONALITY)
+ // the base ontology object:
+ .add(OntObject.class, OWL2ObjectFactories.ANY_OBJECT)
+
+ // ont-id:
+ .add(OntID.class, OWL2ObjectFactories.ID)
+
+ // annotation object:
+ .add(OntAnnotation.class, OWL2ObjectFactories.ANNOTATION)
+
+ // entities:
+ .add(OntClass.Named.class, OWL2ObjectFactories.RL_NAMED_CLASS)
+ .add(OntDataRange.Named.class, OWL2ObjectFactories.NAMED_DATARANGE)
+ .add(OntIndividual.Named.class, OWL2ObjectFactories.NAMED_INDIVIDUAL)
+ .add(OntObjectProperty.Named.class, OWL2ObjectFactories.NAMED_OBJECT_PROPERTY)
+ .add(OntDataProperty.class, OWL2ObjectFactories.DATATYPE_PROPERTY)
+ .add(OntAnnotationProperty.class, OWL2ObjectFactories.ANNOTATION_PROPERTY)
+ .add(OntEntity.class, OWL2ObjectFactories.RL_ANY_ENTITY)
+
+ // individuals:
+ .add(OntIndividual.Anonymous.class, OWL2ObjectFactories.ANONYMOUS_INDIVIDUAL)
+ .add(OntIndividual.class, OWL2ObjectFactories.ANY_INDIVIDUAL)
+
+ // property expressions:
+ .add(OntObjectProperty.Inverse.class, OWL2ObjectFactories.INVERSE_OBJECT_PROPERTY)
+ .add(OntObjectProperty.class, OWL2ObjectFactories.OBJECT_PROPERTY)
+ .add(OntRelationalProperty.class, OWL2ObjectFactories.ANY_DATA_OR_OBJECT_PROPERTY)
+ .add(OntNamedProperty.class, OWL2ObjectFactories.ANY_NAMED_PROPERTY)
+ .add(OntProperty.class, OWL2ObjectFactories.ANY_PROPERTY)
+
+ // class expressions:
+ .add(OntClass.ObjectSomeValuesFrom.class, OWL2ObjectFactories.RL_OBJECT_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.DataSomeValuesFrom.class, OWL2ObjectFactories.RL_DATA_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.ObjectAllValuesFrom.class, OWL2ObjectFactories.RL_OBJECT_ALL_VALUES_FROM_CLASS)
+ .add(OntClass.DataAllValuesFrom.class, OWL2ObjectFactories.RL_DATA_ALL_VALUES_FROM_CLASS)
+ .add(OntClass.ObjectHasValue.class, OWL2ObjectFactories.OBJECT_HAS_VALUE_CLASS)
+ .add(OntClass.DataHasValue.class, OWL2ObjectFactories.DATA_HAS_VALUE_CLASS)
+ .add(OntClass.ObjectMaxCardinality.class, OWL2ObjectFactories.RL_OBJECT_MAX_CARDINALITY_CLASS)
+ .add(OntClass.DataMaxCardinality.class, OWL2ObjectFactories.RL_DATA_MAX_CARDINALITY_CLASS)
+ .add(OntClass.UnionOf.class, OWL2ObjectFactories.RL_UNION_OF_CLASS)
+ .add(OntClass.OneOf.class, OWL2ObjectFactories.RL_ONE_OF_CLASS)
+ .add(OntClass.IntersectionOf.class, OWL2ObjectFactories.RL_INTERSECTION_OF_CLASS)
+ .add(OntClass.ComplementOf.class, OWL2ObjectFactories.RL_COMPLEMENT_OF_CLASS)
+ .add(OntClass.LogicalExpression.class, OWL2ObjectFactories.RL_ANY_LOGICAL_CLASS)
+ .add(OntClass.CollectionOf.class, OWL2ObjectFactories.RL_ANY_COLLECTION_OF_CLASS)
+ .add(OntClass.ValueRestriction.class, OWL2ObjectFactories.RL_ANY_VALUE_RESTRICTION_CLASS)
+ .add(OntClass.CardinalityRestriction.class, OWL2ObjectFactories.RL_ANY_CARDINALITY_RESTRICTION_CLASS)
+ .add(OntClass.ComponentRestriction.class, OWL2ObjectFactories.RL_ANY_COMPONENT_RESTRICTION_CLASS)
+ .add(OntClass.UnaryRestriction.class, OWL2ObjectFactories.RL_ANY_UNARY_RESTRICTION_CLASS)
+ .add(OntClass.Restriction.class, OWL2ObjectFactories.RL_ANY_RESTRICTION_CLASS)
+ .add(OntClass.class, OWL2ObjectFactories.RL_ANY_CLASS)
+
+ // data ranges:
+ .add(OntDataRange.IntersectionOf.class, OWL2ObjectFactories.INTERSECTION_OF_DATARANGE)
+ .add(OntDataRange.Combination.class, OWL2ObjectFactories.RL_ANY_COMPONENTS_DATARANGE)
+ .add(OntDataRange.class, OWL2ObjectFactories.RL_ANY_DATARANGE)
+
+ // negative property assertions:
+ .add(OntNegativeAssertion.WithObjectProperty.class, OWL2ObjectFactories.OBJECT_NEGATIVE_PROPERTY_ASSERTION)
+ .add(OntNegativeAssertion.WithDataProperty.class, OWL2ObjectFactories.DATA_NEGATIVE_PROPERTY_ASSERTION)
+ .add(OntNegativeAssertion.class, OWL2ObjectFactories.ANY_NEGATIVE_PROPERTY_ASSERTION)
+
+ // disjoint anonymous collections:
+ .add(OntDisjoint.Classes.class, OWL2ObjectFactories.CLASSES_DISJOINT)
+ .add(OntDisjoint.Individuals.class, OWL2ObjectFactories.DIFFERENT_INDIVIDUALS_DISJOINT)
+ .add(OntDisjoint.ObjectProperties.class, OWL2ObjectFactories.OBJECT_PROPERTIES_DISJOINT)
+ .add(OntDisjoint.DataProperties.class, OWL2ObjectFactories.DATA_PROPERTIES_DISJOINT)
+ .add(OntDisjoint.Properties.class, OWL2ObjectFactories.ANY_PROPERTIES_DISJOINT)
+ .add(OntDisjoint.class, OWL2ObjectFactories.ANY_DISJOINT);
+ /**
+ * For OWL1.1 Ontologies, limited functionality.
+ */
+ private static final OntObjectPersonalityBuilder OWL1_OBJECT_FACTORIES = templatePersonalityBuilder()
+ .setName("OWL1")
+ .addPersonality(STANDARD_PERSONALITY)
+ // the base ontology object:
+ .add(OntObject.class, OWL1ObjectFactories.ANY_OBJECT)
+
+ // ont-id:
+ .add(OntID.class, OWL1ObjectFactories.ID)
+
+ // entities:
+ .add(OntClass.Named.class, OWL1ObjectFactories.NAMED_CLASS)
+ .add(OntDataRange.Named.class, OWL1ObjectFactories.NAMED_DATARANGE)
+ .add(OntIndividual.Named.class, OWL1ObjectFactories.NAMED_INDIVIDUAL)
+ .add(OntObjectProperty.Named.class, OWL1ObjectFactories.NAMED_OBJECT_PROPERTY)
+ .add(OntDataProperty.class, OWL1ObjectFactories.DATATYPE_PROPERTY)
+ .add(OntAnnotationProperty.class, OWL1ObjectFactories.ANNOTATION_PROPERTY)
+ .add(OntEntity.class, OWL1ObjectFactories.ANY_ENTITY)
+
+ // individuals:
+ .add(OntIndividual.Anonymous.class, OWL1ObjectFactories.ANONYMOUS_INDIVIDUAL)
+ .add(OntIndividual.class, OWL1ObjectFactories.ANY_INDIVIDUAL)
+
+ // properties:
+ .add(OntObjectProperty.class, OWL1ObjectFactories.OBJECT_PROPERTY)
+ .add(OntRelationalProperty.class, OWL1ObjectFactories.ANY_DATA_OR_OBJECT_PROPERTY)
+ .add(OntNamedProperty.class, OWL1ObjectFactories.ANY_NAMED_PROPERTY)
+ .add(OntProperty.class, OWL1ObjectFactories.ANY_PROPERTY)
+
+ // class expressions:
+ .add(OntClass.ObjectSomeValuesFrom.class, OWL1ObjectFactories.OBJECT_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.DataSomeValuesFrom.class, OWL1ObjectFactories.DATA_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.ObjectAllValuesFrom.class, OWL1ObjectFactories.OBJECT_ALL_VALUES_FROM_CLASS)
+ .add(OntClass.DataAllValuesFrom.class, OWL1ObjectFactories.DATA_ALL_VALUES_FROM_CLASS)
+ .add(OntClass.ObjectHasValue.class, OWL1ObjectFactories.OBJECT_HAS_VALUE_CLASS)
+ .add(OntClass.DataHasValue.class, OWL1ObjectFactories.DATA_HAS_VALUE_CLASS)
+ .add(OntClass.ObjectMinCardinality.class, OWL1ObjectFactories.OBJECT_MIN_CARDINALITY_CLASS)
+ .add(OntClass.DataMinCardinality.class, OWL1ObjectFactories.DATA_MIN_CARDINALITY_CLASS)
+ .add(OntClass.ObjectMaxCardinality.class, OWL1ObjectFactories.OBJECT_MAX_CARDINALITY_CLASS)
+ .add(OntClass.DataMaxCardinality.class, OWL1ObjectFactories.DATA_MAX_CARDINALITY_CLASS)
+ .add(OntClass.ObjectCardinality.class, OWL1ObjectFactories.OBJECT_CARDINALITY_CLASS)
+ .add(OntClass.DataCardinality.class, OWL1ObjectFactories.DATA_CARDINALITY_CLASS)
+ .add(OntClass.UnionOf.class, OWL1ObjectFactories.UNION_OF_CLASS)
+ .add(OntClass.OneOf.class, OWL1ObjectFactories.ONE_OF_CLASS)
+ .add(OntClass.IntersectionOf.class, OWL1ObjectFactories.INTERSECTION_OF_CLASS)
+ .add(OntClass.ComplementOf.class, OWL1ObjectFactories.COMPLEMENT_OF_CLASS)
+ .add(OntClass.LogicalExpression.class, OWL1ObjectFactories.ANY_LOGICAL_CLASS_FULL)
+ .add(OntClass.CollectionOf.class, OWL1ObjectFactories.ANY_COLLECTION_OF_CLASS_FULL)
+ .add(OntClass.ValueRestriction.class, OWL1ObjectFactories.ANY_VALUE_RESTRICTION_CLASS_FULL)
+ .add(OntClass.CardinalityRestriction.class, OWL1ObjectFactories.ANY_CARDINALITY_RESTRICTION_CLASS)
+ .add(OntClass.ComponentRestriction.class, OWL1ObjectFactories.ANY_COMPONENT_RESTRICTION_CLASS)
+ .add(OntClass.UnaryRestriction.class, OWL1ObjectFactories.ANY_UNARY_RESTRICTION_CLASS)
+ .add(OntClass.Restriction.class, OWL1ObjectFactories.ANY_RESTRICTION_CLASS_FULL)
+ .add(OntClass.class, OWL1ObjectFactories.ANY_CLASS_FULL)
+
+ // data ranges:
+ .add(OntDataRange.OneOf.class, OWL1ObjectFactories.ONE_OF_DATARANGE)
+ .add(OntDataRange.Combination.class, OWL1ObjectFactories.ANY_COMPONENTS_DATARANGE)
+ .add(OntDataRange.class, OWL1ObjectFactories.ANY_DATARANGE)
+
+ .add(OntDisjoint.Individuals.class, OWL1ObjectFactories.DIFFERENT_INDIVIDUALS_DISJOINT)
+ .add(OntDisjoint.class, OWL1ObjectFactories.ANY_DISJOINT);
+
+ /**
+ * For OWL1.1 Lite Ontologies, limited functionality.
+ *
+ * @see <a href="https://www.w3.org/TR/2004/REC-owl-features-20040210/#s3>Language Description of OWL Lite</a>
+ */
+ private static final OntObjectPersonalityBuilder OWL1_LITE_OBJECT_FACTORIES = templatePersonalityBuilder()
+ .setName("OWL1-LITE")
+ .addPersonality(STANDARD_PERSONALITY)
+ // the base ontology object:
+ .add(OntObject.class, OWL1ObjectFactories.ANY_OBJECT)
+
+ // ont-id:
+ .add(OntID.class, OWL1ObjectFactories.ID)
+
+ // entities:
+ .add(OntClass.Named.class, OWL1ObjectFactories.NAMED_CLASS)
+ .add(OntDataRange.Named.class, OWL1ObjectFactories.NAMED_DATARANGE)
+ .add(OntIndividual.Named.class, OWL1ObjectFactories.NAMED_INDIVIDUAL)
+ .add(OntObjectProperty.Named.class, OWL1ObjectFactories.NAMED_OBJECT_PROPERTY)
+ .add(OntDataProperty.class, OWL1ObjectFactories.DATATYPE_PROPERTY)
+ .add(OntAnnotationProperty.class, OWL1ObjectFactories.ANNOTATION_PROPERTY)
+ .add(OntEntity.class, OWL1ObjectFactories.ANY_ENTITY)
+
+ // individuals:
+ .add(OntIndividual.Anonymous.class, OWL1ObjectFactories.ANONYMOUS_INDIVIDUAL)
+ .add(OntIndividual.class, OWL1ObjectFactories.ANY_INDIVIDUAL)
+
+ // properties:
+ .add(OntObjectProperty.class, OWL1ObjectFactories.OBJECT_PROPERTY)
+ .add(OntRelationalProperty.class, OWL1ObjectFactories.ANY_DATA_OR_OBJECT_PROPERTY)
+ .add(OntNamedProperty.class, OWL1ObjectFactories.ANY_NAMED_PROPERTY)
+ .add(OntProperty.class, OWL1ObjectFactories.ANY_PROPERTY)
+
+ // class expressions:
+ .add(OntClass.ObjectSomeValuesFrom.class, OWL1ObjectFactories.OBJECT_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.DataSomeValuesFrom.class, OWL1ObjectFactories.DATA_SOME_VALUES_FROM_CLASS)
+ .add(OntClass.ObjectAllValuesFrom.class, OWL1ObjectFactories.OBJECT_ALL_VALUES_FROM_CLASS)
+ .add(OntClass.DataAllValuesFrom.class, OWL1ObjectFactories.DATA_ALL_VALUES_FROM_CLASS)
+ .add(OntClass.ObjectMinCardinality.class, OWL1ObjectFactories.OBJECT_MIN_CARDINALITY_CLASS)
+ .add(OntClass.DataMinCardinality.class, OWL1ObjectFactories.DATA_MIN_CARDINALITY_CLASS)
+ .add(OntClass.ObjectMaxCardinality.class, OWL1ObjectFactories.OBJECT_MAX_CARDINALITY_CLASS)
+ .add(OntClass.DataMaxCardinality.class, OWL1ObjectFactories.DATA_MAX_CARDINALITY_CLASS)
+ .add(OntClass.ObjectCardinality.class, OWL1ObjectFactories.OBJECT_CARDINALITY_CLASS)
+ .add(OntClass.DataCardinality.class, OWL1ObjectFactories.DATA_CARDINALITY_CLASS)
+ .add(OntClass.IntersectionOf.class, OWL1ObjectFactories.INTERSECTION_OF_CLASS)
+ .add(OntClass.LogicalExpression.class, OWL1ObjectFactories.ANY_LOGICAL_CLASS_LITE)
+ .add(OntClass.CollectionOf.class, OWL1ObjectFactories.ANY_COLLECTION_OF_CLASS_LITE)
+ .add(OntClass.ValueRestriction.class, OWL1ObjectFactories.ANY_VALUE_RESTRICTION_CLASS_LITE)
+ .add(OntClass.CardinalityRestriction.class, OWL1ObjectFactories.ANY_CARDINALITY_RESTRICTION_CLASS)
+ .add(OntClass.ComponentRestriction.class, OWL1ObjectFactories.ANY_COMPONENT_RESTRICTION_CLASS)
+ .add(OntClass.UnaryRestriction.class, OWL1ObjectFactories.ANY_UNARY_RESTRICTION_CLASS)
+ .add(OntClass.Restriction.class, OWL1ObjectFactories.ANY_RESTRICTION_CLASS_LITE)
+ .add(OntClass.class, OWL1ObjectFactories.ANY_CLASS_LITE)
+
+ .add(OntDisjoint.Individuals.class, OWL1ObjectFactories.DIFFERENT_INDIVIDUALS_DISJOINT)
+ .add(OntDisjoint.class, OWL1ObjectFactories.ANY_DISJOINT);
+
+ /**
+ * Creates (mutable) {@link OntObjectPersonalityBuilder} for RDFS Ontologies.
+ *
+ * @return {@link OntObjectPersonalityBuilder}
+ */
+ public static OntObjectPersonalityBuilder RDFS_ONT_PERSONALITY() {
+ return RDFS_OBJECT_FACTORIES.copy()
+ .setBuiltins(OntPersonalities.RDFS_BUILTINS)
+ .setReserved(OntPersonalities.RDFS_RESERVED)
+ .setPunnings(OntPersonalities.RDFS_NO_PUNNINGS)
+ .setConfig(OntConfigs.RDFS_CONFIG);
+ }
+
+ /**
+ * Creates (mutable) {@link OntObjectPersonalityBuilder} for OWL2 Ontologies.
+ *
+ * @return {@link OntObjectPersonalityBuilder}
+ */
+ public static OntObjectPersonalityBuilder OWL2_ONT_PERSONALITY() {
+ return OWL2_OBJECT_FACTORIES
+ .copy()
+ .setBuiltins(OntPersonalities.OWL2_FULL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_NO_PUNNINGS)
+ .setConfig(OntConfigs.OWL2_CONFIG);
+ }
+
+ /**
+ * Creates (mutable) {@link OntObjectPersonalityBuilder} for OWL2 EL Ontologies.
+ *
+ * @return {@link OntObjectPersonalityBuilder}
+ */
+ public static OntObjectPersonalityBuilder OWL2_EL_ONT_PERSONALITY() {
+ return OWL2_EL_OBJECT_FACTORIES
+ .copy()
+ .setBuiltins(OntPersonalities.OWL2_EL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_DL2_PUNNINGS)
+ .setConfig(OntConfigs.OWL2_EL_CONFIG);
+ }
+
+ /**
+ * Creates (mutable) {@link OntObjectPersonalityBuilder} for OWL2 QL Ontologies.
+ *
+ * @return {@link OntObjectPersonalityBuilder}
+ */
+ public static OntObjectPersonalityBuilder OWL2_QL_ONT_PERSONALITY() {
+ return OWL2_QL_OBJECT_FACTORIES
+ .copy()
+ .setBuiltins(OntPersonalities.OWL2_QL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_DL2_PUNNINGS)
+ .setConfig(OntConfigs.OWL2_QL_CONFIG);
+ }
+
+ /**
+ * Creates (mutable) {@link OntObjectPersonalityBuilder} for OWL2 RL Ontologies.
+ *
+ * @return {@link OntObjectPersonalityBuilder}
+ */
+ public static OntObjectPersonalityBuilder OWL2_RL_ONT_PERSONALITY() {
+ return OWL2_RL_OBJECT_FACTORIES
+ .copy()
+ .setBuiltins(OntPersonalities.OWL2_RL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_DL2_PUNNINGS)
+ .setConfig(OntConfigs.OWL2_RL_CONFIG);
+ }
+
+ /**
+ * Creates (mutable) {@link OntObjectPersonalityBuilder} for OWL1 Ontologies.
+ *
+ * @return {@link OntObjectPersonalityBuilder}
+ */
+ public static OntObjectPersonalityBuilder OWL1_ONT_PERSONALITY() {
+ return OWL1_OBJECT_FACTORIES.copy()
+ .setBuiltins(OntPersonalities.OWL2_FULL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_NO_PUNNINGS)
+ .setConfig(OntConfigs.OWL1_CONFIG);
+ }
+
+ /**
+ * Creates (mutable) {@link OntObjectPersonalityBuilder} for OWL1 LITE Ontologies.
+ *
+ * @return {@link OntObjectPersonalityBuilder}
+ */
+ public static OntObjectPersonalityBuilder OWL1_LITE_ONT_PERSONALITY() {
+ return OWL1_LITE_OBJECT_FACTORIES.copy()
+ .setBuiltins(OntPersonalities.OWL2_FULL_BUILTINS)
+ .setReserved(OntPersonalities.OWL2_RESERVED)
+ .setPunnings(OntPersonalities.OWL_DL1_PUNNINGS)
+ .setConfig(OntConfigs.OWL1_CONFIG);
+ }
+
+ private static OntObjectPersonalityBuilder templatePersonalityBuilder() {
+ return new OntObjectPersonalityBuilder() {
+
+ @Override
+ public OntPersonality build() throws IllegalStateException {
+ throw new IllegalStateException("Should not be call");
+ }
+ };
+ }
+
+ /**
+ * @param personality {@link OntPersonality}
+ * @return {@code true} if the specified {@link OntPersonality} has name "RDFS"
+ */
+ public static boolean isRDFS(OntPersonality personality) {
+ return personality.getName() != null && personality.getName().startsWith("RDFS");
+ }
+
+ /**
+ * @param personality {@link OntPersonality}
+ * @return {@code true} if the specified {@link OntPersonality} supports {@code owl:Thing}
+ */
+ public static boolean supportsOWLThing(OntPersonality personality) {
+ return personality.getBuiltins().getNamedClasses().contains(OWL.Thing.asNode());
+ }
+
+ /**
+ * Creates a {@link OntPersonality.Builtins builtins personality vocabulary}
+ * from the given {@link OntVocabulary system vocabulary}.
+ *
+ * @param voc {@link OntVocabulary}, not {@code null}
+ * @return {@link OntPersonality.Builtins}
+ */
+ public static OntPersonality.Builtins createBuiltinsVocabulary(OntVocabulary voc) {
+ Objects.requireNonNull(voc);
+ Map<Class<? extends OntObject>, Set<Node>> res = new HashMap<>();
+ res.put(OntAnnotationProperty.class, StdModels.asUnmodifiableNodeSet(voc.getBuiltinAnnotationProperties()));
+ res.put(OntDataProperty.class, StdModels.asUnmodifiableNodeSet(voc.getBuiltinDatatypeProperties()));
+ res.put(OntObjectProperty.Named.class, StdModels.asUnmodifiableNodeSet(voc.getBuiltinObjectProperties()));
+ res.put(OntDataRange.Named.class, StdModels.asUnmodifiableNodeSet(voc.getBuiltinDatatypes()));
+ res.put(OntClass.Named.class, StdModels.asUnmodifiableNodeSet(voc.getBuiltinClasses()));
+ res.put(OntSWRL.Builtin.class, StdModels.asUnmodifiableNodeSet(voc.getBuiltinSWRLs()));
+ res.put(OntIndividual.Named.class, Collections.emptySet());
+ Set<Property> ontProperties = new HashSet<>();
+ ontProperties.addAll(voc.getBuiltinAnnotationProperties());
+ ontProperties.addAll(voc.getBuiltinDatatypeProperties());
+ ontProperties.addAll(voc.getBuiltinObjectProperties());
+ Set<Resource> ontEntities = new HashSet<>();
+ ontEntities.addAll(ontProperties);
+ ontEntities.addAll(voc.getBuiltinClasses());
+ ontEntities.addAll(voc.getBuiltinDatatypes());
+ res.put(OntProperty.class, StdModels.asUnmodifiableNodeSet(ontProperties));
+ res.put(OntEntity.class, StdModels.asUnmodifiableNodeSet(ontEntities));
+ return new ResourceVocabularyImpl.BuiltinsImpl(res);
+ }
+
+ /**
+ * Creates a {@link OntPersonality.Reserved reserved personality vocabulary}
+ * from the given {@link OntVocabulary system vocabulary}.
+ *
+ * @param voc {@link OntVocabulary}, not {@code null}
+ * @return {@link OntPersonality.Reserved}
+ */
+ public static OntPersonality.Reserved createReservedVocabulary(OntVocabulary voc) {
+ Objects.requireNonNull(voc);
+ Map<Class<? extends Resource>, Set<Node>> res = new HashMap<>();
+ res.put(Resource.class, StdModels.asUnmodifiableNodeSet(voc.getSystemResources()));
+ res.put(Property.class, StdModels.asUnmodifiableNodeSet(voc.getSystemProperties()));
+ return new ResourceVocabularyImpl.ReservedIml(Map.copyOf(res));
+ }
+
+ /**
+ * Creates a {@link OntPersonality.Punnings punnings personality vocabulary} according to {@link PunningsMode}.
+ *
+ * @param mode {@link PunningsMode}, not {@code null}
+ * @return {@link OntPersonality.Punnings}
+ */
+ private static OntPersonality.Punnings createPunningsVocabulary(PunningsMode mode) {
+ return new ResourceVocabularyImpl.PunningsImpl(PunningsMode.toMap(mode));
+ }
+
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntPersonality.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntPersonality.java
new file mode 100644
index 0000000000..eddb01a2ba
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntPersonality.java
@@ -0,0 +1,333 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.ontapi.model.OntAnnotationProperty;
+import org.apache.jena.ontapi.model.OntClass;
+import org.apache.jena.ontapi.model.OntDataProperty;
+import org.apache.jena.ontapi.model.OntDataRange;
+import org.apache.jena.ontapi.model.OntEntity;
+import org.apache.jena.ontapi.model.OntIndividual;
+import org.apache.jena.ontapi.model.OntModel;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.ontapi.model.OntObjectProperty;
+import org.apache.jena.ontapi.model.OntProperty;
+import org.apache.jena.ontapi.vocabulary.OWL;
+import org.apache.jena.ontapi.vocabulary.RDF;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.enhanced.Personality;
+import org.apache.jena.graph.Node;
+import org.apache.jena.rdf.model.Property;
+import org.apache.jena.rdf.model.RDFNode;
+import org.apache.jena.rdf.model.Resource;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * A {@link OntModel Ontology RDF Model} configuration object
+ * that serves for the following purposes:
+ * <ul>
+ * <li>Defines a set of permitted mappings from [interface] Class objects
+ * to {@link EnhNodeFactory OWL Ontology Object factory}
+ * that can generate instances of the facet represented by the Class.</li>
+ * <li>Defines a set of builtin {@link OntEntity OWL entities}</li>
+ * <li>Defines a set of OWL punnings</li>
+ * <li>Defines a set of reserved {@link Resource}s and {@link Property}s, that cannot be used as OWL Entities</li>
+ * </ul>
+ * <b>NOTE</b>: The instance of this interface must also extend {@link Personality Jena Personality}
+ * with a generic type {@link RDFNode RDFNode}.
+ * <p>
+ * Instances of this class must be unmodifiable and
+ * the {@link OntObjectPersonalityBuilder builder} should be used to create instances with different settings.
+ * <p>
+ * Created by @szz on 15.01.2019.
+ */
+@SuppressWarnings("unused")
+public interface OntPersonality {
+
+ /**
+ * Represents the given {@code OntPersonality} configuration as
+ * a {@link Personality Jena Personality} with a generic type {@link RDFNode}.
+ *
+ * @param p {@link OntPersonality}
+ * @return {@link Personality}
+ * @throws OntJenaException in case the conversion is not possible
+ * @see EnhNodeFactory#asJenaImplementation(EnhNodeFactory)
+ * @see OntEnhGraph#asPersonalityModel(EnhGraph)
+ */
+ @SuppressWarnings("unchecked")
+ static Personality<RDFNode> asJenaPersonality(OntPersonality p) throws OntJenaException {
+ if (p instanceof Personality) {
+ return (Personality<RDFNode>) p;
+ }
+ throw new OntJenaException.IllegalArgument("The given OntPersonality is not an instance of Jena Personality.");
+ }
+
+ /**
+ * Lists all object-types, which are supported by this personality configuration.
+ * Each of the class-types are associated with either {@link EnhNodeFactory} (if it is {@link OntObject} type)
+ * or with {@link org.apache.jena.enhanced.Implementation} (if it is a standard jena resource object).
+ *
+ * @return Stream of {@code Class}es, subclasses of {@link RDFNode}.
+ */
+ Stream<Class<? extends RDFNode>> types();
+
+ /**
+ * Gets the implementation-factory for the specified object type,
+ * returning {@code null} if there isn't one available.
+ *
+ * @param type a class-type of {@link OntObject}
+ * @return {@link EnhNodeFactory} a factory to create an instance of the given type, not {@code null}
+ */
+ EnhNodeFactory getObjectFactory(Class<? extends RDFNode> type);
+
+ /**
+ * Answers if a type is supported.
+ *
+ * @param type {@code Class}
+ * @return {@code boolean}
+ */
+ boolean supports(Class<? extends RDFNode> type);
+
+ /**
+ * Makes a full copy of this configuration.
+ *
+ * @return {@link OntPersonality} a new instance identical to this
+ */
+ OntPersonality copy();
+
+ /**
+ * Returns personality name, language profile.
+ *
+ * @return String
+ */
+ String getName();
+
+ /**
+ * Returns the config.
+ * Config holds various settings to control model behaviour.
+ *
+ * @return {@link OntConfig}
+ */
+ OntConfig getConfig();
+
+ /**
+ * Returns a punnings' vocabulary.
+ *
+ * @return {@link Punnings}
+ */
+ Punnings getPunnings();
+
+ /**
+ * Returns a builtins vocabulary.
+ *
+ * @return {@link Builtins}
+ */
+ Builtins getBuiltins();
+
+ /**
+ * Returns a reserved vocabulary.
+ *
+ * @return {@link Reserved}
+ */
+ Reserved getReserved();
+
+ /**
+ * Gets system resources for the specified type.
+ * An entity of the given {@code type} cannot be created with any of the URIs, which this method returns.
+ *
+ * @param type {@link OntObject}
+ * @return Set of URIs
+ */
+ Set<String> forbidden(Class<? extends OntObject> type);
+
+ /**
+ * Lists all object-types encapsulated by this config, that extend the specified object-type.
+ *
+ * @param type {@code Class}-type of {@link OntObject}
+ * @param <T> any subtype of {@link OntObject}
+ * @return Stream of all types where each element extends {@link T} inclusive
+ */
+ @SuppressWarnings("unchecked")
+ default <T extends OntObject> Stream<Class<? extends T>> types(Class<T> type) {
+ Objects.requireNonNull(type);
+ return types()
+ .filter(c -> c == type || Arrays.stream(c.getInterfaces())
+ .anyMatch(type::isAssignableFrom))
+ .map(x -> (Class<? extends T>) x);
+ }
+
+ /**
+ * A punnings' vocabulary.
+ * For a given {@link OntEntity} type it returns a {@code Set} of forbidden types
+ * (the right part of SPO with the (@code rdf:type) predicate).
+ * A {@link OntModel model}, that holds this configuration,
+ * cannot contain entities which have intersection in {@link RDF#type rdf:type}
+ * that are determined by this vocabulary.
+ * <p>
+ * For example, for the {@link PunningsMode#DL_WEAK} and for the {@link PunningsMode#DL2}
+ * configurations, the expression {@code voc.get(OntClass.class)}, where {@code voc} is an instance of this class,
+ * should return a {@code Set}
+ * containing {@link org.apache.jena.vocabulary.RDFS#Datatype rdfs:Datatype} in the form of {@link Node},
+ * since {@code OntDT <-> OntClass} is illegal punning.
+ * <p>
+ * Each node obtained from this class must be IRI (i.e. {@code node.isURI() = true}).
+ *
+ * @see <a href='https://www.w3.org/TR/owl2-new-features/#F12:_Punning'>Punnings</a>
+ * @see OntEntity#types()
+ */
+ interface Punnings extends ResourceVocabulary<OntObject> {
+ default Set<Node> getNamedClasses() {
+ return get(OntClass.Named.class);
+ }
+
+ default Set<Node> getDatatypes() {
+ return get(OntDataRange.Named.class);
+ }
+
+ default Set<Node> getObjectProperties() {
+ return get(OntObjectProperty.Named.class);
+ }
+
+ default Set<Node> getDatatypeProperties() {
+ return get(OntDataProperty.class);
+ }
+
+ default Set<Node> getAnnotationProperties() {
+ return get(OntAnnotationProperty.class);
+ }
+
+ default Set<Node> getNamedIndividuals() {
+ return get(OntIndividual.Named.class);
+ }
+ }
+
+ /**
+ * A vocabulary of reserved IRIs.
+ * A {@link OntModel model}, that holds this configuration,
+ * cannot contain entities with the IRIs from this vocabulary.
+ * <p>
+ * Example of such a forbidden {@link Property} returned by this vocabulary is
+ * {@link OWL#sameAs owl:sameAs},
+ * since it is used by a model to build individual equality and, therefore, it cannot be used in other cases.
+ * An {@link OntModel ontology model} cannot contain an OWL entity with this IRI.
+ * All these things are customizable, and vocabularies may contain more or less restrictions.
+ * <p>
+ * Each node obtained from this class must be IRI (i.e. {@code node.isURI() = true}).
+ */
+ interface Reserved extends ResourceVocabulary<Resource> {
+
+ /**
+ * Gets all reserved IRIs, which are most likely used as an object in SPO of some schema graph.
+ *
+ * @return Set of IRI-{@link Node node}s
+ */
+ default Set<Node> getResources() {
+ return get(Resource.class);
+ }
+
+ /**
+ * Gets all reserved IRIs, which are most likely used as a predicate in SPO of some schema graph.
+ *
+ * @return Set of IRI-{@link Node node}s
+ */
+ default Set<Node> getProperties() {
+ return get(Property.class);
+ }
+
+ /**
+ * Resources + Properties
+ * @return Set of IRI-{@link Node node}s
+ */
+ default Set<Node> getAllResources() {
+ return Stream.of(getResources(), getProperties()).flatMap(Collection::stream).collect(Collectors.toUnmodifiableSet());
+ }
+
+ }
+
+ /**
+ * A vocabulary of built-in {@link OntEntity ONT Entities}.
+ * A {@link OntModel model}, that holds this configuration,
+ * can contain entities without explicit declarations, if their IRIs are determined by this vocabulary.
+ * <p>
+ * For example, the OWL standard vocabulary determines
+ * {@link OWL#Thing owl:Thing} as a built-in OWL class.
+ * To describe this case the expression {@code voc.get(OntClass.class)},
+ * where {@code voc} is an instance of this class,
+ * should return a {@code Set} containing {@code owl:Thing} in the form of {@link Node}.
+ * <p>
+ * Each node obtained from this class must be IRI (i.e. {@code node.isURI() = true}).
+ *
+ * @see OntEntity#types()
+ */
+ interface Builtins extends ResourceVocabulary<OntObject> {
+
+ default Set<Class<? extends OntObject>> supportedTypes() {
+ return Set.of(
+ OntClass.Named.class,
+ OntDataRange.Named.class,
+ OntObjectProperty.Named.class,
+ OntDataProperty.class,
+ OntAnnotationProperty.class,
+ OntProperty.class,
+ OntEntity.class
+ );
+ }
+
+ default Set<Node> getNamedClasses() {
+ return get(OntClass.Named.class);
+ }
+
+ default Set<Node> getDatatypes() {
+ return get(OntDataRange.Named.class);
+ }
+
+ default Set<Node> getObjectProperties() {
+ return get(OntObjectProperty.Named.class);
+ }
+
+ default Set<Node> getDatatypeProperties() {
+ return get(OntDataProperty.class);
+ }
+
+ default Set<Node> getAnnotationProperties() {
+ return get(OntAnnotationProperty.class);
+ }
+
+ default Set<Node> getNamedIndividuals() {
+ return get(OntIndividual.Named.class);
+ }
+
+ /**
+ * Returns a {@code Set} of all OWL builtin properties
+ * (annotation, datatype and object named property expressions)
+ *
+ * @return Set of IRI-{@link Node node}s
+ */
+ default Set<Node> getOntProperties() {
+ return get(OntProperty.class);
+ }
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntPersonalityImpl.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntPersonalityImpl.java
new file mode 100644
index 0000000000..d7b499d56a
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntPersonalityImpl.java
@@ -0,0 +1,169 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.enhanced.Implementation;
+import org.apache.jena.enhanced.Personality;
+import org.apache.jena.graph.Node;
+import org.apache.jena.rdf.model.RDFNode;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * A default implementation of {@link OntPersonality}.
+ * Mappings from [interface] Class objects of RDFNode to {@link Implementation} factories.
+ */
+@SuppressWarnings({"WeakerAccess", "unused"})
+public class OntPersonalityImpl extends Personality<RDFNode> implements OntPersonality {
+ private final String name;
+ private final OntConfig config;
+ private final Punnings punnings;
+ private final Builtins builtins;
+ private final Reserved reserved;
+ private final Map<Class<? extends OntObject>, Set<String>> forbidden;
+
+ public OntPersonalityImpl(String name,
+ OntConfig config,
+ Punnings punnings,
+ Builtins builtins,
+ Reserved reserved) {
+ this.name = name;
+ this.config = Objects.requireNonNull(config, "Null config");
+ this.builtins = Objects.requireNonNull(builtins, "Null builtins vocabulary");
+ this.punnings = Objects.requireNonNull(punnings, "Null punnings vocabulary");
+ this.reserved = Objects.requireNonNull(reserved, "Null reserved vocabulary");
+ this.forbidden = collectForbiddenResources(reserved, builtins);
+ }
+
+ private static Map<Class<? extends OntObject>, Set<String>> collectForbiddenResources(Reserved reserved, Builtins builtins) {
+ Map<Class<? extends OntObject>, Set<String>> forbidden = new HashMap<>();
+ Set<Node> reservedResources = reserved.getAllResources();
+ builtins.supportedTypes().forEach(type -> {
+ Set<Node> allowedResources = builtins.get(type);
+ Set<String> forbiddenResources = reservedResources.stream()
+ .filter(it -> it.isURI() && !allowedResources.contains(it))
+ .map(Node::getURI)
+ .collect(Collectors.toUnmodifiableSet());
+ forbidden.put(type, forbiddenResources);
+ });
+ return forbidden;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public Builtins getBuiltins() {
+ return builtins;
+ }
+
+ @Override
+ public Punnings getPunnings() {
+ return punnings;
+ }
+
+ @Override
+ public Reserved getReserved() {
+ return reserved;
+ }
+
+ @Override
+ public OntConfig getConfig() {
+ return config;
+ }
+
+ @Override
+ public Set<String> forbidden(Class<? extends OntObject> type) {
+ return forbidden.getOrDefault(type, Set.of());
+ }
+
+ /**
+ * Registers new OntObject if needed
+ *
+ * @param type Interface (OntObject)
+ * @param factory Factory to crete object
+ */
+ public void register(Class<? extends OntObject> type, EnhNodeFactory factory) {
+ register(type, EnhNodeFactory.asJenaImplementation(factory));
+ }
+
+ public void register(Class<? extends RDFNode> type, Implementation factory) {
+ super.add(Objects.requireNonNull(type, "Null type."), factory);
+ }
+
+ /**
+ * Removes the factory.
+ *
+ * @param view Interface (OntObject)
+ */
+ public void unregister(Class<? extends OntObject> view) {
+ getMap().remove(view);
+ }
+
+ @Override
+ public Stream<Class<? extends RDFNode>> types() {
+ return getMap().keySet().stream();
+ }
+
+ /**
+ * Gets factory for {@link OntObject}.
+ *
+ * @param type Interface (OntObject type)
+ * @return {@link EnhNodeFactory} factory
+ */
+ @Override
+ public EnhNodeFactory getObjectFactory(Class<? extends RDFNode> type) {
+ Implementation implementation = getImplementation(type);
+ OntJenaException.checkSupported(implementation != null,
+ "Profile " + name + " does not support language construct " + OntEnhNodeFactories.viewAsString(type)
+ );
+ if (implementation instanceof EnhNodeFactory) {
+ return (EnhNodeFactory) implementation;
+ }
+ return OntJenaException.TODO("Not implemented yet");
+ }
+
+ @Override
+ public boolean supports(Class<? extends RDFNode> type) {
+ return getMap().containsKey(type);
+ }
+
+ @Override
+ public OntPersonalityImpl add(Personality<RDFNode> other) {
+ super.add(other);
+ return this;
+ }
+
+ @Override
+ public OntPersonalityImpl copy() {
+ OntPersonalityImpl res = new OntPersonalityImpl(getName(), getConfig(), getPunnings(), getBuiltins(), getReserved());
+ res.add(this);
+ return res;
+ }
+
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntVocabulary.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntVocabulary.java
new file mode 100644
index 0000000000..52314a3188
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/OntVocabulary.java
@@ -0,0 +1,716 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.ontapi.vocabulary.OWL;
+import org.apache.jena.ontapi.vocabulary.RDF;
+import org.apache.jena.ontapi.vocabulary.SWRL;
+import org.apache.jena.ontapi.vocabulary.SWRLB;
+import org.apache.jena.ontapi.vocabulary.XSD;
+import org.apache.jena.datatypes.BaseDatatype;
+import org.apache.jena.datatypes.RDFDatatype;
+import org.apache.jena.datatypes.TypeMapper;
+import org.apache.jena.rdf.model.Property;
+import org.apache.jena.rdf.model.Resource;
+import org.apache.jena.rdf.model.ResourceFactory;
+import org.apache.jena.vocabulary.DC;
+import org.apache.jena.vocabulary.RDFS;
+import org.apache.jena.vocabulary.SKOS;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * An Ontology Vocabulary.
+ * This is a generic interface that simply maps an {@code uri}-key to a {@code Set} of
+ * {@link Resource RDF Resources} or {@link Property RDF Properties},
+ * that are defined in vocabulary schemas and represent some family determined by that key.
+ * A schema is a java class containing public static final constants.
+ * Schemas are usually located inside the packages
+ * {@code org.apache.jena.ontapi.vocabulary} and {@code org.apache.jena.vocabulary}.
+ * There are two kinds of property/resources described by this vocabulary: system and builtin.
+ * A system resource/property is simply a URI defined in any scheme.
+ * A builtin resource/property is a URI with a known type that does not require explicit declaration.
+ * Note that all methods of this interface return unmodifiable {@code Set}s.
+ *
+ * @see Impls
+ */
+public interface OntVocabulary {
+
+ OntVocabulary EMPTY = new Impls.BaseImpl(Map.of());
+ OntVocabulary RDFS = new Impls.RDFSImpl();
+ OntVocabulary OWL2_FULL = new Impls.OWL2Impl(Impls.OWL2Impl.Type.FULL);
+ OntVocabulary OWL2_EL = new Impls.OWL2Impl(Impls.OWL2Impl.Type.EL);
+ OntVocabulary OWL2_QL = new Impls.OWL2Impl(Impls.OWL2Impl.Type.QL);
+ OntVocabulary OWL2_RL = new Impls.OWL2Impl(Impls.OWL2Impl.Type.RL);
+ OntVocabulary OWL1_FULL = new Impls.OWL1Impl(Impls.OWL1Impl.Type.FULL);
+ OntVocabulary OWL1_LITE = new Impls.OWL1Impl(Impls.OWL1Impl.Type.LITE);
+ OntVocabulary DC = new Impls.DCImpl();
+ OntVocabulary SKOS = new Impls.SKOSImpl();
+ OntVocabulary SWRL = new Impls.SWRLImpl();
+
+ /**
+ * Answers a {@code Set} of system/builtin {@link Resource}s for the specified URI-{@code key}.
+ * A URI-{@code key} - is a schema URI that determines a family of desired resources.
+ * For example, to get all resources a key {@link RDFS#Resource rdfs:Resource} should be used,
+ * because it is a supertype of everything.
+ *
+ * @param key String, not {@code null}
+ * @return a {@code Set} of {@link Resource}s (possibly empty)
+ */
+ Set<? extends Resource> get(String key);
+
+ /**
+ * Answers a {@code Set} of system/builtin {@link Resource}s for the specified URI-key.
+ *
+ * @param uri a URI-{@link Resource}, not {@code null}
+ * @param <X> either {@link Resource} or {@link Property}
+ * @return a {@code Set} of {@link X}s, not {@code null} but possibly empty
+ */
+ @SuppressWarnings("unchecked")
+ default <X extends Resource> Set<X> get(Resource uri) {
+ return (Set<X>) get(Objects.requireNonNull(uri.getURI()));
+ }
+
+ /**
+ * Returns a collection of all built-in properties
+ * with implicit {@code rdf:type} equal to {@link OWL#AnnotationProperty owl:AnnotationProperty}.
+ *
+ * @return {@code Set} of {@link Property Properties}
+ */
+ default Set<Property> getBuiltinAnnotationProperties() {
+ return get(OWL.AnnotationProperty);
+ }
+
+ /**
+ * Returns a collection of all built-in properties
+ * with implicit {@code rdf:type} equal to {@link OWL#DatatypeProperty owl:DatatypeProperty}.
+ *
+ * @return {@code Set} of {@link Property Properties}
+ */
+ default Set<Property> getBuiltinDatatypeProperties() {
+ return get(OWL.DatatypeProperty);
+ }
+
+ /**
+ * Returns a collection of all built-in properties
+ * with implicit {@code rdf:type} equal to {@link OWL#ObjectProperty owl:ObjectProperty}.
+ *
+ * @return {@code Set} of {@link Property Properties}
+ */
+ default Set<Property> getBuiltinObjectProperties() {
+ return get(OWL.ObjectProperty);
+ }
+
+ /**
+ * Returns a collection of all built-in uri-resources
+ * with implicit {@code rdf:type} equal to {@link RDFS#Datatype rdfs:Datatype}.
+ *
+ * @return {@code Set} of {@link Resource Resources}
+ */
+ default Set<Resource> getBuiltinDatatypes() {
+ return get(org.apache.jena.vocabulary.RDFS.Datatype);
+ }
+
+ /**
+ * Returns a collection of all built-in uri resources
+ * with implicit {@code rdf:type} equal to {@link OWL#Class owl:Class}.
+ *
+ * @return {@code Set} of {@link Resource Resources}
+ */
+ default Set<Resource> getBuiltinClasses() {
+ return get(OWL.Class);
+ }
+
+ /**
+ * Returns a collection of all built-in uri resources
+ * with implicit {@code rdf:type} equal to {@link SWRL#Builtin swrl:Builtin}.
+ *
+ * @return {@code Set} of {@link Resource Resources}
+ */
+ default Set<Resource> getBuiltinSWRLs() {
+ return get(org.apache.jena.ontapi.vocabulary.SWRL.Builtin);
+ }
+
+ /**
+ * Returns all reserved resources:
+ * OWL entities cannot have an uri belonging to the return collection.
+ *
+ * @return {@code Set} of {@link Resource Resources}
+ */
+ default Set<Resource> getSystemResources() {
+ return get(org.apache.jena.vocabulary.RDFS.Resource);
+ }
+
+ /**
+ * Returns all reserved properties:
+ * OWL2 ontology cannot contain assertion with predicate belonging to the return collection.
+ *
+ * @return {@code Set} of {@link Property Properties}
+ */
+ default Set<Property> getSystemProperties() {
+ return get(RDF.Property);
+ }
+
+ /**
+ * Creates a new instance of {@code OntVocabulary}, combining this and the given vocabularies.
+ *
+ * @param other {@link OntVocabulary}, not {@code null}
+ * @return {@link OntVocabulary}
+ */
+ default OntVocabulary and(OntVocabulary other) {
+ return Impls.create(this, Objects.requireNonNull(other));
+ }
+
+ /**
+ * A factory-helper to work with {@link OntVocabulary} instances, that wrap constant-holders
+ * from the packages {@code org.apache.jena.ontapi.vocabulary}
+ * and {@code org.apache.jena.vocabulary} (such as {@link OWL}).
+ * <p>
+ * In ONT-API, a {@link OntVocabulary} singleton is used
+ * to build {@link OntPersonality}
+ * and, also, in {@code com.github.owlcs.ontapi.transforms} subsystem.
+ */
+ final class Impls {
+
+ /**
+ * Creates a fresh union vocabulary that combines the given ones.
+ *
+ * @param vocabularies an {@code Array} of {@link OntVocabulary}s
+ * @return {@link OntVocabulary}
+ * @see #create(String, Collection)
+ */
+ public static OntVocabulary create(OntVocabulary... vocabularies) {
+ return new BaseImpl(Arrays.stream(vocabularies)
+ .map(Impls::asMap)
+ .flatMap(x -> x.entrySet().stream())
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> {
+ Set<Resource> res = new HashSet<>(a);
+ res.addAll(b);
+ return res;
+ })));
+ }
+
+ /**
+ * Creates a {@link OntVocabulary} that contains the specified mapping ({@code key -> Set}).
+ *
+ * @param key a URI-{@link Resource}, not {@code null}
+ * @param values an {@code Array} with {@link Resource}s to map, not {@code null}
+ * @return a {@link OntVocabulary} with single (specified) mapping
+ */
+ public static OntVocabulary create(Resource key, Resource... values) {
+ return create(key, Arrays.stream(values).collect(Collectors.toUnmodifiableSet()));
+ }
+
+ /**
+ * Creates a {@link OntVocabulary} that contains the specified mapping ({@code key -> Set}).
+ *
+ * @param key a URI-{@link Resource}, not {@code null}
+ * @param values a {@code Collection} of {@link Resource}s to map, not {@code null}
+ * @return a {@link OntVocabulary} with single (specified) mapping
+ */
+ public static OntVocabulary create(Resource key, Collection<? extends Resource> values) {
+ return create(Objects.requireNonNull(key).getURI(), values);
+ }
+
+ /**
+ * Creates a {@link OntVocabulary} that contains the specified mapping ({@code key -> Set}).
+ *
+ * @param key {@code String}, a URI of resource-family, not {@code null}
+ * @param values a {@code Collection} of {@link Resource}s to map, not {@code null}
+ * @return a {@link OntVocabulary} with single mapping
+ * @see #create(OntVocabulary...)
+ */
+ public static OntVocabulary create(String key, Collection<? extends Resource> values) {
+ Map<String, Set<? extends Resource>> map = new HashMap<>();
+ map.put(Objects.requireNonNull(key), toUnmodifiableSet(Objects.requireNonNull(values)));
+ return new BaseImpl(map);
+ }
+
+ /**
+ * Creates a {@link OntVocabulary} with mapping for system resource/properties.
+ *
+ * @param schemas an {@code Array} of schemas
+ * - constant-holders with {@link Resource} and {@link Property} public static final fields,
+ * not {@code null}
+ * @return a {@link OntVocabulary} with mapping for system resources and properties
+ * (keys: {@link RDFS#Resource rdfs:Resource} and {@link RDF#Property rdf:Property})
+ */
+ public static OntVocabulary create(Class<?>... schemas) {
+ return new BaseImpl(getConstants(Property.class, schemas), getConstants(Resource.class, schemas));
+ }
+
+ private static Stream<Field> directFields(Class<?> vocabulary, Class<?> type) {
+ return Arrays.stream(vocabulary.getDeclaredFields())
+ .filter(x -> Modifier.isPublic(x.getModifiers()))
+ .filter(x -> Modifier.isStatic(x.getModifiers()))
+ .filter(x -> type.equals(x.getType()));
+ }
+
+ private static Stream<Field> fields(Class<?> vocabulary, Class<?> type) {
+ Stream<Field> res = directFields(vocabulary, type);
+ return vocabulary.getSuperclass() != null ? Stream.concat(res, fields(vocabulary.getSuperclass(), type)) : res;
+ }
+
+ private static <T> Stream<T> constants(Class<?> vocabulary, Class<T> type) {
+ return fields(vocabulary, type).map(x -> getValue(x, type)).filter(Objects::nonNull);
+ }
+
+ private static <T> T getValue(Field field, Class<T> type) {
+ try {
+ return type.cast(field.get(null));
+ } catch (IllegalAccessException e) {
+ throw new OntJenaException.IllegalState("Unable to get an object of the type " + type.getSimpleName() +
+ " from the field " + field.getName(), e);
+ }
+ }
+
+ private static <T> Set<T> getConstants(Class<? extends T> type, Class<?>... vocabularies) {
+ return Arrays.stream(vocabularies)
+ .flatMap(x -> constants(x, type))
+ .collect(Collectors.toUnmodifiableSet());
+ }
+
+ private static Map<String, Set<? extends Resource>> asMap(OntVocabulary voc) {
+ if (voc instanceof BaseImpl) {
+ return ((BaseImpl) voc).map;
+ }
+ Map<String, Set<? extends Resource>> res = new HashMap<>();
+ Stream.of(OWL.AnnotationProperty, OWL.DatatypeProperty, OWL.ObjectProperty,
+ org.apache.jena.vocabulary.RDFS.Datatype,
+ OWL.Class,
+ org.apache.jena.ontapi.vocabulary.SWRL.Builtin,
+ RDF.Property,
+ org.apache.jena.vocabulary.RDFS.Resource
+ )
+ .forEach(x -> res.put(x.getURI(), voc.get(x)));
+ return res;
+ }
+
+ private static <X> Set<X> toUnmodifiableSet(Collection<X> input) {
+ if (input instanceof Set && input.getClass().getName().equals("java.util.Collections$UnmodifiableSet")) {
+ return (Set<X>) input;
+ }
+ return input.stream().peek(Objects::requireNonNull).collect(Collectors.toUnmodifiableSet());
+ }
+
+ protected static class RDFSImpl extends BaseImpl {
+ public static final Set<Property> ANNOTATION_PROPERTIES = Set.of(
+ org.apache.jena.vocabulary.RDFS.label,
+ org.apache.jena.vocabulary.RDFS.comment,
+ org.apache.jena.vocabulary.RDFS.seeAlso,
+ org.apache.jena.vocabulary.RDFS.isDefinedBy
+ );
+ private static final Class<?>[] VOCABULARIES = new Class<?>[]{RDF.class, RDFS.class};
+ public static final Set<Property> PROPERTIES = getConstants(Property.class, VOCABULARIES);
+ public static final Set<Resource> RESOURCES = getConstants(Resource.class, VOCABULARIES);
+
+ protected RDFSImpl() {
+ super(
+ /* annotation properties */ ANNOTATION_PROPERTIES,
+ /* datatype properties */ null,
+ /* object properties */ null,
+ /* named classes */ null,
+ /* datatypes */ null,
+ /* swrl */ null,
+ /* system properties */ PROPERTIES,
+ /* system resources */ RESOURCES
+ );
+ }
+ }
+
+ /**
+ * Access to the {@link OWL OWL2} (including RDFS & RDF & XSD) vocabulary.
+ */
+ @SuppressWarnings("WeakerAccess")
+ protected static class OWL2Impl extends BaseImpl {
+ /**
+ * The list of datatypes from owl-2 specification (35 types)
+ * (see <a href="https://www.w3.org/TR/owl2-quick-reference/">Quick References, 3.1 Built-in Datatypes</a>).
+ * It seems it is not full:
+ */
+ public static final Set<Resource> OWL2_DATATYPES = Set.of(
+ OWL.real, OWL.rational,
+ RDF.xmlLiteral, RDF.PlainLiteral, RDF.langString,
+ org.apache.jena.vocabulary.RDFS.Literal, XSD.xstring, XSD.normalizedString,
+ XSD.token, XSD.language, XSD.Name, XSD.NCName, XSD.NMTOKEN, XSD.decimal, XSD.integer,
+ XSD.xdouble, XSD.xfloat, XSD.xboolean,
+ XSD.nonNegativeInteger, XSD.nonPositiveInteger, XSD.positiveInteger, XSD.negativeInteger,
+ XSD.xlong, XSD.xint, XSD.xshort, XSD.xbyte,
+ XSD.unsignedLong, XSD.unsignedInt, XSD.unsignedShort, XSD.unsignedByte,
+ XSD.hexBinary, XSD.base64Binary,
+ XSD.anyURI, XSD.dateTime, XSD.dateTimeStamp
+ );
+ /**
+ * @see <a href="https://www.w3.org/TR/owl2-profiles/#Entities">EL: Entities</a>
+ * @see <a href="https://www.w3.org/TR/owl2-profiles/#Entities_2">QL: Entities</a>
+ */
+ public static final Set<Resource> OWL2_EL_QL_DATATYPES = Set.of(
+ OWL.real, OWL.rational,
+ RDF.xmlLiteral, RDF.PlainLiteral, RDF.langString,
+ org.apache.jena.vocabulary.RDFS.Literal, XSD.xstring, XSD.normalizedString,
+ XSD.token, XSD.Name, XSD.NCName, XSD.NMTOKEN, XSD.decimal, XSD.integer,
+ XSD.nonNegativeInteger,
+ XSD.hexBinary, XSD.base64Binary,
+ XSD.anyURI, XSD.dateTime, XSD.dateTimeStamp
+ );
+ /**
+ * @see <a href="https://www.w3.org/TR/owl2-profiles/#Entities_3">RL: Entitites</a>
+ */
+ public static final Set<Resource> OWL2_RL_DATATYPES = Set.of(
+ RDF.xmlLiteral, RDF.PlainLiteral, RDF.langString,
+ org.apache.jena.vocabulary.RDFS.Literal, XSD.xstring, XSD.normalizedString,
+ XSD.token, XSD.language, XSD.Name, XSD.NCName, XSD.NMTOKEN, XSD.decimal, XSD.integer,
+ XSD.xdouble, XSD.xfloat, XSD.xboolean,
+ XSD.nonNegativeInteger, XSD.nonPositiveInteger, XSD.positiveInteger, XSD.negativeInteger,
+ XSD.xlong, XSD.xint, XSD.xshort, XSD.xbyte,
+ XSD.unsignedLong, XSD.unsignedInt, XSD.unsignedShort, XSD.unsignedByte,
+ XSD.hexBinary, XSD.base64Binary,
+ XSD.anyURI, XSD.dateTime, XSD.dateTimeStamp
+ );
+ public static final Set<Resource> ALL_KNOWN_DATATYPES = initOWL2BuiltInRDFDatatypes(TypeMapper.getInstance())
+ .stream()
+ .map(RDFDatatype::getURI)
+ .map(ResourceFactory::createResource)
+ .collect(Collectors.toUnmodifiableSet());
+ public static final Set<Resource> OWL2_CLASSES = Set.of(OWL.Nothing, OWL.Thing);
+ public static final Set<Property> OWL2_ANNOTATION_PROPERTIES = Set.of(
+ org.apache.jena.vocabulary.RDFS.label,
+ org.apache.jena.vocabulary.RDFS.comment,
+ org.apache.jena.vocabulary.RDFS.seeAlso,
+ org.apache.jena.vocabulary.RDFS.isDefinedBy,
+ OWL.versionInfo,
+ OWL.backwardCompatibleWith,
+ OWL.priorVersion,
+ OWL.incompatibleWith,
+ OWL.deprecated);
+ public static final Set<Property> OWL2_DATA_PROPERTIES = Set.of(OWL.topDataProperty, OWL.bottomDataProperty);
+ public static final Set<Property> OWL2_OBJECT_PROPERTIES = Set.of(OWL.topObjectProperty, OWL.bottomObjectProperty);
+ private static final Class<?>[] VOCABULARIES = new Class<?>[]{XSD.class, RDF.class, org.apache.jena.vocabulary.RDFS.class, OWL.class};
+ public static final Set<Property> PROPERTIES = getConstants(Property.class, VOCABULARIES);
+ public static final Set<Resource> RESOURCES = getConstants(Resource.class, VOCABULARIES);
+
+ protected OWL2Impl(Type type) {
+ super(
+ OWL2_ANNOTATION_PROPERTIES,
+ type == Type.RL ? Set.of() : OWL2_DATA_PROPERTIES,
+ type == Type.RL ? Set.of() : OWL2_OBJECT_PROPERTIES,
+ OWL2_CLASSES,
+ datatypes(type),
+ /*SWRL*/ null,
+ PROPERTIES,
+ RESOURCES
+ );
+ }
+
+ private static Set<Resource> datatypes(Type type) {
+ if (type == Type.DL) {
+ return OWL2_DATATYPES;
+ }
+ if (type == Type.EL || type == Type.QL) {
+ return OWL2_EL_QL_DATATYPES;
+ }
+ if (type == Type.RL) {
+ return OWL2_RL_DATATYPES;
+ }
+ return ALL_KNOWN_DATATYPES;
+ }
+
+ private static Set<RDFDatatype> initOWL2BuiltInRDFDatatypes(TypeMapper types) {
+ Stream.of(OWL.real, OWL.rational).forEach(d -> types.registerDatatype(new BaseDatatype(d.getURI())));
+ OWL2_DATATYPES.forEach(iri -> types.getSafeTypeByName(iri.getURI()));
+ Set<RDFDatatype> res = new HashSet<>();
+ types.listTypes().forEachRemaining(res::add);
+ return Collections.unmodifiableSet(res);
+ }
+
+ protected enum Type {
+ FULL, DL, EL, QL, RL,
+ }
+ }
+
+ /**
+ * Access to the {@link org.apache.jena.vocabulary.OWL OWL1} (including RDFS & RDF & XSD) vocabulary.
+ */
+ @SuppressWarnings("WeakerAccess")
+ protected static class OWL1Impl extends BaseImpl {
+ private static final Set<Resource> OWL1_DATATYPES =
+ Set.of(RDF.xmlLiteral, RDF.PlainLiteral, RDF.langString,
+ org.apache.jena.vocabulary.RDFS.Literal, XSD.xstring, XSD.normalizedString,
+ XSD.token, XSD.language, XSD.Name, XSD.NCName, XSD.NMTOKEN, XSD.decimal, XSD.integer,
+ XSD.xdouble, XSD.xfloat, XSD.xboolean,
+ XSD.nonNegativeInteger, XSD.nonPositiveInteger, XSD.positiveInteger, XSD.negativeInteger,
+ XSD.xlong, XSD.xint, XSD.xshort, XSD.xbyte,
+ XSD.unsignedLong, XSD.unsignedInt, XSD.unsignedShort, XSD.unsignedByte,
+ XSD.hexBinary, XSD.base64Binary,
+ XSD.anyURI, XSD.dateTime, XSD.dateTimeStamp
+ );
+ public static final Set<Resource> ALL_KNOWN_DATATYPES = initOWL1BuiltInRDFDatatypes(TypeMapper.getInstance())
+ .stream()
+ .map(RDFDatatype::getURI)
+ .map(ResourceFactory::createResource)
+ .collect(Collectors.toUnmodifiableSet());
+ public static final Set<Resource> OWL1_FULL_CLASSES = Set.of(
+ org.apache.jena.vocabulary.OWL.Nothing, org.apache.jena.vocabulary.OWL.Thing
+ );
+ public static final Set<Resource> OWL1_LITE_CLASSES = Set.of(
+ org.apache.jena.vocabulary.OWL.Thing
+ );
+ public static final Set<Property> OWL1_ANNOTATION_PROPERTIES = Set.of(
+ org.apache.jena.vocabulary.RDFS.label,
+ org.apache.jena.vocabulary.RDFS.comment,
+ org.apache.jena.vocabulary.RDFS.seeAlso,
+ org.apache.jena.vocabulary.RDFS.isDefinedBy,
+ org.apache.jena.vocabulary.OWL.versionInfo,
+ org.apache.jena.vocabulary.OWL.backwardCompatibleWith,
+ org.apache.jena.vocabulary.OWL.priorVersion,
+ org.apache.jena.vocabulary.OWL.incompatibleWith
+ );
+ public static final Set<Property> OWL1_DATA_PROPERTIES = Set.of();
+ public static final Set<Property> OWL1_OBJECT_PROPERTIES = Set.of();
+ private static final Class<?>[] VOCABULARIES = new Class<?>[]{
+ XSD.class,
+ RDF.class,
+ org.apache.jena.vocabulary.RDFS.class,
+ org.apache.jena.vocabulary.OWL.class};
+ public static final Set<Property> PROPERTIES = getConstants(Property.class, VOCABULARIES);
+ public static final Set<Resource> RESOURCES = getConstants(Resource.class, VOCABULARIES);
+
+ protected OWL1Impl(Type type) {
+ super(
+ OWL1_ANNOTATION_PROPERTIES,
+ OWL1_DATA_PROPERTIES,
+ OWL1_OBJECT_PROPERTIES,
+ classes(type),
+ datatypes(type),
+ /*SWRL*/ null,
+ PROPERTIES,
+ RESOURCES
+ );
+ }
+
+ private static Set<Resource> classes(Type type) {
+ if (type == Type.LITE) {
+ return OWL1_LITE_CLASSES;
+ }
+ return OWL1_FULL_CLASSES;
+ }
+
+ private static Set<Resource> datatypes(Type type) {
+ if (type == Type.FULL) {
+ return ALL_KNOWN_DATATYPES;
+ }
+ return OWL1_DATATYPES;
+ }
+
+ private static Set<RDFDatatype> initOWL1BuiltInRDFDatatypes(TypeMapper types) {
+ OWL1_DATATYPES.forEach(iri -> types.getSafeTypeByName(iri.getURI()));
+ Set<String> exclude = OWL2Impl.OWL2_DATATYPES.stream()
+ .filter(it -> !OWL1_DATATYPES.contains(it))
+ .map(Resource::getURI)
+ .collect(Collectors.toUnmodifiableSet());
+ Set<RDFDatatype> res = new HashSet<>();
+ types.listTypes().forEachRemaining(it -> {
+ if (!exclude.contains(it.getURI())) {
+ res.add(it);
+ }
+ });
+ return Collections.unmodifiableSet(res);
+ }
+
+ public enum Type {
+ FULL, DL, LITE,
+ }
+ }
+
+ /**
+ * Access to {@link DC} vocabulary.
+ */
+ protected static class DCImpl extends BaseImpl {
+ public static final Set<Property> ALL_PROPERTIES = getConstants(Property.class, org.apache.jena.vocabulary.DC.class);
+
+ protected DCImpl() {
+ super(
+ /* annotation properties */ ALL_PROPERTIES,
+ /* datatype properties */ null,
+ /* object properties */ null,
+ /* named classes */ null,
+ /* datatypes */ null,
+ /* swrl */ null,
+ /* system properties */ ALL_PROPERTIES,
+ /* system resources */ null
+ );
+ }
+ }
+
+ /**
+ * Access to {@link SKOS} vocabulary.
+ */
+ @SuppressWarnings("WeakerAccess")
+ protected static class SKOSImpl extends BaseImpl {
+ public static final Set<Property> ANNOTATION_PROPERTIES =
+ Set.of(org.apache.jena.vocabulary.SKOS.altLabel,
+ org.apache.jena.vocabulary.SKOS.changeNote, org.apache.jena.vocabulary.SKOS.definition,
+ org.apache.jena.vocabulary.SKOS.editorialNote, org.apache.jena.vocabulary.SKOS.example, org.apache.jena.vocabulary.SKOS.hiddenLabel, org.apache.jena.vocabulary.SKOS.historyNote,
+ org.apache.jena.vocabulary.SKOS.note, org.apache.jena.vocabulary.SKOS.prefLabel, org.apache.jena.vocabulary.SKOS.scopeNote);
+ public static final Set<Property> OBJECT_PROPERTIES =
+ Set.of(org.apache.jena.vocabulary.SKOS.broadMatch, org.apache.jena.vocabulary.SKOS.broader, org.apache.jena.vocabulary.SKOS.broaderTransitive,
+ org.apache.jena.vocabulary.SKOS.closeMatch, org.apache.jena.vocabulary.SKOS.exactMatch, org.apache.jena.vocabulary.SKOS.hasTopConcept, org.apache.jena.vocabulary.SKOS.inScheme,
+ org.apache.jena.vocabulary.SKOS.mappingRelation, org.apache.jena.vocabulary.SKOS.member, org.apache.jena.vocabulary.SKOS.memberList, org.apache.jena.vocabulary.SKOS.narrowMatch,
+ org.apache.jena.vocabulary.SKOS.narrower, org.apache.jena.vocabulary.SKOS.narrowerTransitive, org.apache.jena.vocabulary.SKOS.related,
+ org.apache.jena.vocabulary.SKOS.relatedMatch, org.apache.jena.vocabulary.SKOS.semanticRelation, org.apache.jena.vocabulary.SKOS.topConceptOf);
+ /**
+ * NOTE: In the OWLAPI-api {@code org.semanticweb.owlapi.vocab.SKOSVocabulary} there is also skos:TopConcept
+ * But in fact there is no such resource in the <a href="https://www.w3.org/2009/08/skos-reference/skos.htm">specification</a>.
+ */
+ public static final Set<Resource> CLASSES =
+ Set.of(org.apache.jena.vocabulary.SKOS.Collection, org.apache.jena.vocabulary.SKOS.Concept, org.apache.jena.vocabulary.SKOS.ConceptScheme, org.apache.jena.vocabulary.SKOS.OrderedCollection);
+
+ public static final Set<Property> PROPERTIES = getConstants(Property.class, org.apache.jena.vocabulary.SKOS.class);
+ public static final Set<Resource> RESOURCES = getConstants(Resource.class, org.apache.jena.vocabulary.SKOS.class);
+
+
+ protected SKOSImpl() {
+ super(
+ /* annotation properties */ ANNOTATION_PROPERTIES,
+ /* datatype properties */ null,
+ /* object properties */ OBJECT_PROPERTIES,
+ /* named classes */ CLASSES,
+ /* datatypes */ null,
+ /* swrl */ null,
+ /* system properties */ PROPERTIES,
+ /* system resources */ RESOURCES
+ );
+ }
+ }
+
+ /**
+ * For SWRL modeling.
+ *
+ * @see SWRL
+ * @see SWRLB
+ */
+ protected static class SWRLImpl extends BaseImpl {
+ public static final Set<Resource> BUILTINS = getConstants(Property.class, SWRLB.class);
+ private static final Class<?>[] VOCABULARIES = new Class<?>[]{SWRL.class, SWRLB.class};
+ public static final Set<Property> PROPERTIES = getConstants(Property.class, VOCABULARIES);
+ public static final Set<Resource> RESOURCES = getConstants(Resource.class, VOCABULARIES);
+
+ protected SWRLImpl() {
+ super(
+ /* annotation properties */ null,
+ /* datatype properties */ null,
+ /* object properties */ null,
+ /* named classes */ null,
+ /* datatypes */ null,
+ /* swrl */ BUILTINS,
+ /* system properties */ PROPERTIES,
+ /* system resources */ RESOURCES
+ );
+ }
+ }
+
+ /**
+ * The base implementation.
+ */
+ public static class BaseImpl implements OntVocabulary {
+ private final Map<String, Set<? extends Resource>> map;
+
+ private BaseImpl(Set<Property> properties,
+ Set<Resource> resources) {
+ this(
+ /* annotation properties */ null,
+ /* datatype properties */ null,
+ /* object properties */ null,
+ /* named classes */ null,
+ /* datatypes */ null,
+ /* swrl */ null,
+ /* system properties */ properties,
+ /* system resources */ resources
+ );
+ }
+
+ protected BaseImpl(Set<Property> annotationProperties,
+ Set<Property> dataProperties,
+ Set<Property> objectProperties,
+ Set<Resource> classes,
+ Set<Resource> datatypes,
+ Set<Resource> swrlBuiltins,
+ Set<Property> allProperties,
+ Set<Resource> allResources) {
+ this.map = collectBuiltIns(
+ annotationProperties,
+ dataProperties,
+ objectProperties,
+ classes,
+ datatypes,
+ swrlBuiltins,
+ allProperties,
+ allResources);
+ }
+
+ private static Map<String, Set<? extends Resource>> collectBuiltIns(Set<Property> annotationProperties,
+ Set<Property> dataProperties,
+ Set<Property> objectProperties,
+ Set<Resource> classes,
+ Set<Resource> datatypes,
+ Set<Resource> swrlBuiltins,
+ Set<Property> allProperties,
+ Set<Resource> allResources) {
+ return Stream.of(
+ pair(OWL.AnnotationProperty, annotationProperties),
+ pair(OWL.DatatypeProperty, dataProperties),
+ pair(OWL.ObjectProperty, objectProperties),
+ pair(OWL.Class, classes),
+ pair(org.apache.jena.vocabulary.RDFS.Datatype, datatypes),
+ pair(org.apache.jena.ontapi.vocabulary.SWRL.Builtin, swrlBuiltins),
+ pair(RDF.Property, allProperties),
+ pair(org.apache.jena.vocabulary.RDFS.Resource, allResources)
+ ).filter(Objects::nonNull).collect(Collectors.toUnmodifiableMap(
+ it -> it.getKey().getURI(),
+ it -> Set.copyOf(it.getValue()))
+ );
+ }
+
+ private static Map.Entry<Resource, Set<? extends Resource>> pair(Resource key, Set<? extends Resource> value) {
+ return value == null ? null : Map.entry(key, value);
+ }
+
+ protected BaseImpl(Map<String, Set<? extends Resource>> map) {
+ this.map = Map.copyOf(Objects.requireNonNull(map));
+ }
+
+ @Override
+ public Set<? extends Resource> get(String key) {
+ return map.getOrDefault(key, Collections.emptySet());
+ }
+ }
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/PunningsMode.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/PunningsMode.java
new file mode 100644
index 0000000000..3cb4aa4ac2
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/PunningsMode.java
@@ -0,0 +1,213 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntModelControls;
+import org.apache.jena.ontapi.model.OntAnnotationProperty;
+import org.apache.jena.ontapi.model.OntClass;
+import org.apache.jena.ontapi.model.OntDataProperty;
+import org.apache.jena.ontapi.model.OntDataRange;
+import org.apache.jena.ontapi.model.OntIndividual;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.ontapi.model.OntObjectProperty;
+import org.apache.jena.ontapi.vocabulary.OWL;
+import org.apache.jena.ontapi.vocabulary.RDF;
+import org.apache.jena.graph.FrontsNode;
+import org.apache.jena.graph.Node;
+import org.apache.jena.rdf.model.Resource;
+import org.apache.jena.vocabulary.RDFS;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * A standard personality mode to manage punnings.
+ *
+ * @see <a href='https://www.w3.org/TR/owl2-new-features/#F12:_Punning'>2.4.1 F12: Punning</a>
+ */
+public enum PunningsMode {
+ /**
+ * For OWL1 DL.
+ * OWL1 DL required a strict separation between the names of, e.g., classes and individuals.
+ * The difference between this mode
+ * and {@code DL1} is that declarations {@code rdfs:Class} &
+ * {@code rdfs:Datatype} considered as OntClass declarations;
+ * also, {@code owl:Restriction}
+ * is considered as prohibited declaration for entities that aren't classes (properties, datarange, named individuals).
+ * See {@link OntModelControls#USE_LEGACY_COMPATIBLE_NAMED_CLASS_FACTORY}
+ */
+ DL1_COMPATIBLE,
+ /**
+ * For OWL1 DL.
+ * OWL1 DL required a strict separation between the names of, e.g., classes and individuals.
+ *
+ */
+ DL1,
+ /**
+ * For OWL2 DL.
+ * Personality with four kinds of restriction on a {@code rdf:type} intersection (i.e. "illegal punnings"):
+ * <ul>
+ * <li>Named owl:Class <-> Named rdfs:Datatype</li>
+ * <li>Named owl:ObjectProperty <-> owl:DatatypeProperty</li>
+ * <li>Named owl:ObjectProperty <-> owl:AnnotationProperty</li>
+ * <li>owl:AnnotationProperty <-> owl:DatatypeProperty</li>
+ * </ul>
+ * each of the pairs above can't exist in the form of OWL-Entity in the same model at the same time.
+ * From specification: "OWL 2 DL imposes certain restrictions:
+ * it requires that a name cannot be used for both a class and a datatype and
+ * that a name can only be used for one kind of property."
+ */
+ DL2,
+ /**
+ * Forbidden intersections of rdf-declarations:
+ * <ul>
+ * <li>Class <-> Datatype</li>
+ * <li>ObjectProperty <-> DataProperty</li>
+ * </ul>
+ */
+ DL_WEAK,
+ /**
+ * Allow any entity type intersections.
+ */
+ FULL,
+ ;
+
+ private static final Set<Resource> OWL2_ALL_OBJECT_PROPERTIES = Set.of(
+ OWL.ObjectProperty,
+ OWL.InverseFunctionalProperty,
+ OWL.ReflexiveProperty,
+ OWL.IrreflexiveProperty,
+ OWL.SymmetricProperty,
+ OWL.AsymmetricProperty,
+ OWL.TransitiveProperty
+ );
+ private static final Set<Resource> OWL1_ALL_OBJECT_PROPERTIES = Set.of(
+ OWL.ObjectProperty,
+ OWL.InverseFunctionalProperty,
+ OWL.SymmetricProperty,
+ OWL.TransitiveProperty
+ );
+ private static final Set<Resource> OWL2_OBJECT_PROPERTIES = Set.of(
+ OWL.ObjectProperty
+ );
+ private static final Set<Resource> DATATYPE_PROPERTIES = Set.of(OWL.DatatypeProperty);
+ private static final Set<Resource> ANNOTATION_PROPERTIES = Set.of(OWL.AnnotationProperty);
+ private static final Set<Resource> RDF_PROPERTIES = Set.of(RDF.Property);
+ private static final Set<Resource> OWL2_CLASSES = Set.of(OWL.Class);
+ private static final Set<Resource> OWL1_CLASSES = Set.of(OWL.Class);
+ private static final Set<Resource> OWL1_ALL_CLASSES = Set.of(OWL.Class, OWL.Restriction, RDFS.Class, RDFS.Datatype);
+ private static final Set<Resource> OWL2_DATATYPES = Set.of(RDFS.Datatype);
+ private static final Set<Resource> OWL1_DATATYPES = Set.of(OWL.DataRange);
+ private static final Set<Resource> OWL2_INDIVIDUALS = Set.of(OWL.NamedIndividual);
+
+ static Map<Class<? extends OntObject>, Set<Node>> toMap(PunningsMode mode) {
+ Map<Class<? extends OntObject>, Set<Set<Resource>>> res;
+ if (PunningsMode.DL1_COMPATIBLE == mode) {
+ res = OWL1_DL(true);
+ } else if (PunningsMode.DL1 == mode) {
+ res = OWL1_DL(false);
+ } else if (PunningsMode.DL2 == mode) {
+ res = OWL2_DL();
+ } else if (PunningsMode.DL_WEAK == mode) {
+ res = OWL2_DL_WEAK();
+ } else if (PunningsMode.FULL == mode) {
+ res = FULL();
+ } else {
+ throw new IllegalStateException();
+ }
+ return res.entrySet().stream().collect(
+ Collectors.toUnmodifiableMap(
+ Map.Entry::getKey,
+ it -> it.getValue().stream()
+ .flatMap(Collection::stream)
+ .map(FrontsNode::asNode)
+ .collect(Collectors.toUnmodifiableSet())
+ )
+ );
+ }
+
+ private static Map<Class<? extends OntObject>, Set<Set<Resource>>> OWL1_DL(boolean compatible) {
+ Set<Resource> classes = compatible ? OWL1_ALL_CLASSES : OWL1_CLASSES;
+ return Map.of(
+ OntAnnotationProperty.class, Set.of(
+ OWL1_ALL_OBJECT_PROPERTIES, DATATYPE_PROPERTIES, classes
+ ),
+ OntObjectProperty.Named.class, Set.of(
+ DATATYPE_PROPERTIES, ANNOTATION_PROPERTIES, classes
+ ),
+ OntDataProperty.class, Set.of(
+ OWL1_ALL_OBJECT_PROPERTIES, ANNOTATION_PROPERTIES, classes
+ ),
+ OntDataRange.Named.class, Set.of(
+ OWL1_DATATYPES // no named classes but still require
+ ),
+ OntClass.Named.class, Set.of(
+ ANNOTATION_PROPERTIES, OWL1_ALL_OBJECT_PROPERTIES, DATATYPE_PROPERTIES
+ ),
+ OntIndividual.Named.class, Set.of(
+ ANNOTATION_PROPERTIES, OWL1_ALL_OBJECT_PROPERTIES, DATATYPE_PROPERTIES, classes, RDF_PROPERTIES
+ )
+ );
+ }
+
+ private static Map<Class<? extends OntObject>, Set<Set<Resource>>> OWL2_DL() {
+ return Map.of(
+ OntAnnotationProperty.class, Set.of(
+ OWL2_ALL_OBJECT_PROPERTIES, DATATYPE_PROPERTIES
+ ),
+ OntObjectProperty.Named.class, Set.of(
+ DATATYPE_PROPERTIES, ANNOTATION_PROPERTIES
+ ),
+ OntDataProperty.class, Set.of(
+ OWL2_ALL_OBJECT_PROPERTIES, ANNOTATION_PROPERTIES
+ ),
+ OntDataRange.Named.class, Set.of(
+ OWL2_CLASSES
+ ),
+ OntClass.Named.class, Set.of(
+ OWL2_DATATYPES
+ ),
+ OntIndividual.Named.class, Set.of()
+ );
+ }
+
+ private static Map<Class<? extends OntObject>, Set<Set<Resource>>> OWL2_DL_WEAK() {
+ return Map.of(
+ OntAnnotationProperty.class, Set.of(),
+ OntObjectProperty.Named.class, Set.of(DATATYPE_PROPERTIES),
+ OntDataProperty.class, Set.of(OWL2_OBJECT_PROPERTIES),
+ OntDataRange.Named.class, Set.of(OWL2_CLASSES),
+ OntClass.Named.class, Set.of(OWL2_DATATYPES),
+ OntIndividual.Named.class, Set.of()
+ );
+ }
+
+ private static Map<Class<? extends OntObject>, Set<Set<Resource>>> FULL() {
+ return Map.of(
+ OntAnnotationProperty.class, Set.of(),
+ OntObjectProperty.Named.class, Set.of(),
+ OntDataProperty.class, Set.of(),
+ OntDataRange.Named.class, Set.of(),
+ OntClass.Named.class, Set.of(),
+ OntIndividual.Named.class, Set.of()
+ );
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/ResourceVocabulary.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/ResourceVocabulary.java
new file mode 100644
index 0000000000..1412ae1842
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/ResourceVocabulary.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.graph.Node;
+import org.apache.jena.rdf.model.Resource;
+
+import java.util.Set;
+
+/**
+ * This is a resource type mapper.
+ * It is a technical interface that is included into the {@link OntPersonality}.
+ * Note: all its methods must return a IRIs (as {@code String}s), not literals or blank-nodes.
+ *
+ * @param <T> any subtype of {@link Resource}
+ * @see OntVocabulary
+ */
+public interface ResourceVocabulary<T extends Resource> {
+
+ /**
+ * Returns a {@code Set} of {@link Node Jena Graph Node}s for the given {@code Class}-type.
+ *
+ * @param type {@link Class}, any subtype of {@link T}
+ * @return Set of {@link Node node}s (immutable!), can be empty (if no mapping or type is not supported)
+ */
+ Set<Node> get(Class<? extends T> type) throws OntJenaException;
+
+ /**
+ * Answers {@code true} if the given type is supported by the vocabulary.
+ *
+ * @param type {@link Class}, any subtype of {@link T}
+ * @return boolean
+ */
+ boolean supports(Class<? extends T> type);
+
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/ResourceVocabularyImpl.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/ResourceVocabularyImpl.java
new file mode 100644
index 0000000000..123b519b83
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/ResourceVocabularyImpl.java
@@ -0,0 +1,161 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.ontapi.model.OntAnnotationProperty;
+import org.apache.jena.ontapi.model.OntClass;
+import org.apache.jena.ontapi.model.OntDataProperty;
+import org.apache.jena.ontapi.model.OntDataRange;
+import org.apache.jena.ontapi.model.OntIndividual;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.ontapi.model.OntObjectProperty;
+import org.apache.jena.graph.Node;
+import org.apache.jena.rdf.model.Property;
+import org.apache.jena.rdf.model.Resource;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * A {@link ResourceVocabulary} abstraction and a holder for some particular vocabulary {@link OntPersonality}'s implementations.
+ * Each of the impl has a simple in-memory cache to speed-up,
+ * since it is important to have quick access to desired types.
+ */
+abstract class ResourceVocabularyImpl<T extends Resource> implements ResourceVocabulary<T> {
+ private final Map<Class<? extends T>, Set<Node>> map;
+
+ ResourceVocabularyImpl(Map<Class<? extends T>, Set<Node>> map) {
+ this.map = Objects.requireNonNull(map);
+ }
+
+ @Override
+ public Set<Node> get(Class<? extends T> key) throws OntJenaException {
+ return map.getOrDefault(OntJenaException.notNull(key, "Null key"), Set.of());
+ }
+
+ @Override
+ public boolean supports(Class<? extends T> type) {
+ return map.containsKey(type);
+ }
+
+ static class BuiltinsImpl extends EntitiesImpl implements OntPersonality.Builtins {
+ BuiltinsImpl(Map<Class<? extends OntObject>, Set<Node>> map) {
+ super(map);
+ }
+ }
+
+ static class PunningsImpl extends EntitiesImpl implements OntPersonality.Punnings {
+ PunningsImpl(Map<Class<? extends OntObject>, Set<Node>> map) {
+ super(map);
+ }
+ }
+
+ static abstract class EntitiesImpl extends ResourceVocabularyImpl<OntObject> {
+ final Set<Node> classes;
+ final Set<Node> datatypes;
+ final Set<Node> objectProperties;
+ final Set<Node> datatypeProperties;
+ final Set<Node> annotationProperties;
+ final Set<Node> ontProperties;
+ final Set<Node> individuals;
+
+ EntitiesImpl(Map<Class<? extends OntObject>, Set<Node>> map) {
+ super(map);
+ this.classes = get(OntClass.Named.class);
+ this.datatypes = get(OntDataRange.Named.class);
+ this.individuals = get(OntIndividual.Named.class);
+ this.objectProperties = get(OntObjectProperty.Named.class);
+ this.datatypeProperties = get(OntDataProperty.class);
+ this.annotationProperties = get(OntAnnotationProperty.class);
+ this.ontProperties = collect(OntObjectProperty.Named.class, OntDataProperty.class, OntAnnotationProperty.class);
+ }
+
+ public Set<Node> getNamedClasses() {
+ return classes;
+ }
+
+ public Set<Node> getDatatypes() {
+ return datatypes;
+ }
+
+ public Set<Node> getObjectProperties() {
+ return objectProperties;
+ }
+
+ public Set<Node> getDatatypeProperties() {
+ return datatypeProperties;
+ }
+
+ public Set<Node> getAnnotationProperties() {
+ return annotationProperties;
+ }
+
+ public Set<Node> getNamedIndividuals() {
+ return individuals;
+ }
+
+ public Set<Node> getOntProperties() {
+ return ontProperties;
+ }
+
+ @SafeVarargs
+ private Set<Node> collect(Class<? extends OntObject>... types) {
+ return Arrays.stream(types).map(this::get)
+ .flatMap(Collection::stream)
+ .collect(Collectors.toUnmodifiableSet());
+ }
+ }
+
+ static class ReservedIml extends ResourceVocabularyImpl<Resource> implements OntPersonality.Reserved {
+ private final Map<String, Set<Node>> nodes = new HashMap<>();
+ private final Set<Node> resources;
+ private final Set<Node> properties;
+ private final Set<Node> allResources;
+
+ ReservedIml(Map<Class<? extends Resource>, Set<Node>> map) {
+ super(map);
+ this.properties = get(Property.class);
+ this.resources = get(Resource.class);
+ this.allResources = Stream.of(properties, resources)
+ .flatMap(Collection::stream).collect(Collectors.toUnmodifiableSet());
+ }
+
+ @Override
+ public Set<Node> getResources() {
+ return resources;
+ }
+
+ @Override
+ public Set<Node> getProperties() {
+ return properties;
+ }
+
+ @Override
+ public Set<Node> getAllResources() {
+ return allResources;
+ }
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/WrappedEnhNodeFactory.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/WrappedEnhNodeFactory.java
new file mode 100644
index 0000000000..22978745c1
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/common/WrappedEnhNodeFactory.java
@@ -0,0 +1,91 @@
+/*
+ * 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.jena.ontapi.common;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.enhanced.EnhNode;
+import org.apache.jena.graph.Node;
+import org.apache.jena.rdf.model.RDFNode;
+import org.apache.jena.util.iterator.ExtendedIterator;
+
+import java.util.Objects;
+
+/**
+ * A factory wrapper.
+ * It is a facility to provide implicit links between {@link EnhNodeFactory object factories}.
+ * For more details see the {@link OntEnhGraph} description and also the description for
+ * the method {@link OntObjectPersonalityBuilder#add(Class, EnhNodeFactory)}.
+ *
+ * @see OntEnhNodeFactories
+ */
+@SuppressWarnings("WeakerAccess")
+public class WrappedEnhNodeFactory extends BaseEnhNodeFactoryImpl {
+ private final Class<? extends RDFNode> type;
+
+ public WrappedEnhNodeFactory(Class<? extends RDFNode> type) {
+ this.type = Objects.requireNonNull(type);
+ }
+
+ public static WrappedEnhNodeFactory of(Class<? extends RDFNode> type) {
+ return new WrappedEnhNodeFactory(type);
+ }
+
+ /**
+ * Finds and returns the {@link EnhNodeFactory} instance for the encapsulated {@link OntObject object} type.
+ * This factory and the returned one are synonymous: both have the same behaviour.
+ *
+ * @param g {@link EnhGraph}, the model. Must be instance of {@link OntEnhGraph}
+ * @return {@link EnhNodeFactory}, not {@code null}
+ * @throws OntJenaException in case nothing is found
+ */
+ public EnhNodeFactory getDelegate(EnhGraph g) throws OntJenaException {
+ return getFactory(g);
+ }
+
+ protected EnhNodeFactory getFactory(EnhGraph g) throws OntJenaException {
+ return OntEnhGraph.asPersonalityModel(g).getOntPersonality().getObjectFactory(type);
+ }
+
+ @Override
+ public ExtendedIterator<EnhNode> iterator(EnhGraph eg) {
+ return getDelegate(eg).iterator(eg);
+ }
+
+ @Override
+ public boolean canWrap(Node node, EnhGraph eg) {
+ return getDelegate(eg).canWrap(node, eg);
+ }
+
+ @Override
+ public EnhNode createInstance(Node node, EnhGraph eg) {
+ return getDelegate(eg).createInstance(node, eg);
+ }
+
+ @Override
+ public EnhNode wrap(Node node, EnhGraph eg) {
+ return getDelegate(eg).wrap(node, eg);
+ }
+
+ @Override
+ public String toString() {
+ return String.format("Factory[%s]", OntEnhNodeFactories.viewAsString(type));
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/GraphListenerBase.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/GraphListenerBase.java
new file mode 100644
index 0000000000..f0aba9e18a
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/GraphListenerBase.java
@@ -0,0 +1,107 @@
+/*
+ * 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.jena.ontapi.impl;
+
+import org.apache.jena.graph.Graph;
+import org.apache.jena.graph.GraphListener;
+import org.apache.jena.graph.Triple;
+import org.apache.jena.graph.impl.SimpleEventManager;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.stream.Stream;
+
+/**
+ * Base implementation of {@link GraphListener}.
+ */
+public abstract class GraphListenerBase extends SimpleEventManager {
+
+ protected abstract void addTripleEvent(Graph g, Triple t);
+
+ protected abstract void deleteTripleEvent(Graph g, Triple t);
+
+ public Stream<GraphListener> listeners() {
+ return listeners.stream();
+ }
+
+ @Override
+ public void notifyAddTriple(Graph g, Triple ts) {
+ addTripleEvent(g, ts);
+ super.notifyAddTriple(g, ts);
+ }
+
+ @Override
+ public void notifyAddArray(Graph g, Triple[] ts) {
+ for (Triple t : ts) {
+ addTripleEvent(g, t);
+ }
+ super.notifyAddArray(g, ts);
+ }
+
+ @Override
+ public void notifyAddList(Graph g, List<Triple> ts) {
+ ts.forEach(t -> addTripleEvent(g, t));
+ super.notifyAddList(g, ts);
+ }
+
+ @Override
+ public void notifyAddIterator(Graph g, List<Triple> ts) {
+ ts.forEach(t -> addTripleEvent(g, t));
+ super.notifyAddIterator(g, ts);
+ }
+
+ @Override
+ public void notifyAddIterator(Graph g, Iterator<Triple> ts) {
+ ts.forEachRemaining(t -> addTripleEvent(g, t));
+ super.notifyAddIterator(g, ts);
+ }
+
+ @Override
+ public void notifyDeleteTriple(Graph g, Triple t) {
+ deleteTripleEvent(g, t);
+ super.notifyDeleteTriple(g, t);
+ }
+
+ @Override
+ public void notifyDeleteArray(Graph g, Triple[] ts) {
+ for (Triple t : ts) {
+ deleteTripleEvent(g, t);
+ }
+ super.notifyDeleteArray(g, ts);
+ }
+
+ @Override
+ public void notifyDeleteList(Graph g, List<Triple> ts) {
+ ts.forEach(t -> deleteTripleEvent(g, t));
+ super.notifyDeleteList(g, ts);
+ }
+
+ @Override
+ public void notifyDeleteIterator(Graph g, List<Triple> ts) {
+ ts.forEach(t -> deleteTripleEvent(g, t));
+ super.notifyDeleteIterator(g, ts);
+ }
+
+ @Override
+ public void notifyDeleteIterator(Graph g, Iterator<Triple> ts) {
+ ts.forEachRemaining(t -> deleteTripleEvent(g, t));
+ super.notifyDeleteIterator(g, ts);
+ }
+
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/HierarchySupport.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/HierarchySupport.java
new file mode 100644
index 0000000000..95a3586921
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/HierarchySupport.java
@@ -0,0 +1,357 @@
+/*
+ * 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.jena.ontapi.impl;
+
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.ontapi.utils.Iterators;
+import org.apache.jena.rdf.model.Resource;
+
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * Helper class to handle resource hierarchy.
+ */
+public final class HierarchySupport {
+
+ /**
+ * Answers {@code true} if the specified {@code test} node is in the closure of the specified {@code root} nodes
+ *
+ * @param root the root of tree
+ * @param test object to test
+ * @param listChildren a {@link Function} that provides {@code Stream} of child nodes for the given parent node
+ * @param direct if {@code true}, only return the direct (adjacent) values
+ * @param useBuiltinHierarchySupport if {@code true} collect a nodes' tree by traversing the graph,
+ * this parameter is used when there is no reasoner attached to the graph
+ * @param <X> any subtype of {@link OntObject}
+ * @return boolean
+ */
+ public static <X extends OntObject> boolean contains(
+ X root,
+ X test,
+ Function<X, Stream<X>> listChildren,
+ boolean direct,
+ boolean useBuiltinHierarchySupport) {
+ // TODO: optimize
+ return treeNodes(root, listChildren, direct, useBuiltinHierarchySupport).anyMatch(test::equals);
+ }
+
+ /**
+ * Lists tree nodes for the given root using {@code listChildren} function, which provides child nodes.
+ * This is an analogy of
+ * {@code org.apache.jena.ontology.impl.OntResourceImpl#listDirectPropertyValues(Property, String, Class, Property, boolean, boolean)}
+ *
+ * @param root the root of tree
+ * @param listChildren a {@link Function} that provides {@code Stream} of child nodes for the given parent node
+ * @param direct if {@code true}, only return the direct (adjacent) values
+ * @param useBuiltinHierarchySupport if {@code true} collect a nodes' tree by traversing the graph,
+ * this parameter is used when there is no reasoner attached to the graph
+ * @param <X> any subtype of {@link OntObject}
+ * @return a {@link Stream} of tree nodes
+ */
+ public static <X extends OntObject> Stream<X> treeNodes(
+ X root,
+ Function<X, Stream<X>> listChildren,
+ boolean direct,
+ boolean useBuiltinHierarchySupport) {
+ if (direct) {
+ return directNodesAsStream(root, useBuiltinHierarchySupport, listChildren);
+ }
+ if (useBuiltinHierarchySupport) {
+ return allTreeNodes(root, listChildren);
+ }
+ return listChildren.apply(root).filter(x -> !root.equals(x));
+ }
+
+ /**
+ * For the given object returns a {@code Set} of objects the same type,
+ * that are its children which is determined by the operation {@code listChildren}.
+ *
+ * @param root {@link X}
+ * @param listChildren a {@code Function} that returns {@code Iterator} for an object of type {@link X}
+ * @param <X> any subtype of {@link Resource}
+ * @return {@code Set} of {@link X}, {@code root} is not included
+ */
+ static <X extends Resource> Stream<X> allTreeNodes(X root, Function<X, Stream<X>> listChildren) {
+ return Iterators.fromSet(() -> {
+ Set<X> res = new HashSet<>();
+ Map<X, Set<X>> childrenNodesCache = new HashMap<>();
+ Function<X, Set<X>> getChildren = it -> getChildren(it, listChildren, childrenNodesCache);
+ collectIndirect(root, getChildren, res);
+ res.remove(root);
+ return res;
+ });
+ }
+
+ /**
+ * Returns a forest (collection of indirect node trees) for the given roots.
+ *
+ * @param listRoots {@code Supplier<Stream<X>>} roots provider
+ * @param listChildren {@code Function<X, Stream<X>>} called for each root
+ * @param <X> any subtype of {@link Resource}
+ * @return {@code Set} of {@code X} including roots
+ */
+ public static <X extends Resource> Set<X> allTreeNodesSetInclusive(
+ Supplier<Stream<X>> listRoots,
+ Function<X, Stream<X>> listChildren) {
+ @SuppressWarnings("DuplicatedCode") Set<X> res = new HashSet<>();
+ Map<X, Set<X>> childrenNodesCache = new HashMap<>();
+ Function<X, Set<X>> getChildren = it -> getChildren(it, listChildren, childrenNodesCache);
+ try (Stream<X> roots = listRoots.get()) {
+ roots.forEach(root -> collectIndirect(root, getChildren, res));
+ }
+ return res;
+ }
+
+ /**
+ * For the given object recursively collects all children determined by the operation {@code listChildren}.
+ *
+ * @param root {@link X}
+ * @param getChildren a {@code Function} that returns {@code Set} explicit children of an object of type {@link X}
+ * @param res {@code Set} to store result
+ * @param <X> any subtype of {@link Resource}
+ */
+ static <X extends Resource> void collectIndirect(X root,
+ Function<X, Set<X>> getChildren,
+ Set<X> res) {
+ Deque<X> queue = new ArrayDeque<>();
+ queue.add(root);
+ while (!queue.isEmpty()) {
+ X next = queue.removeFirst();
+ if (!res.add(next)) {
+ continue;
+ }
+ queue.addAll(getChildren.apply(next));
+ }
+ }
+
+ public static <X extends Resource> Stream<X> directNodesAsStream(X object,
+ boolean useBuiltinHierarchySupport,
+ Function<X, Stream<X>> listChildren) {
+ return Iterators.fromSet(() ->
+ useBuiltinHierarchySupport ? directNodesAsSetWithBuiltinInf(object, listChildren) : directNodesAsSetStandard(object, listChildren)
+ );
+ }
+
+ public static <X extends Resource> Set<X> directNodesAsSetStandard(X root,
+ Function<X, Stream<X>> listChildren) {
+ Map<X, Set<X>> childrenNodesCache = new HashMap<>();
+ Function<X, Set<X>> getChildren = it -> getChildren(it, listChildren, childrenNodesCache);
+ return getChildren.apply(root).stream()
+ .filter(x -> !equivalent(x, root, getChildren) && !hasAnotherPath(x, root, getChildren))
+ .collect(Collectors.toSet());
+ }
+
+ public static <X extends Resource> Set<X> directNodesAsSetWithBuiltinInf(X root,
+ Function<X, Stream<X>> listChildren) {
+ Map<X, Node<X>> tree = collectTree(root, listChildren);
+ Node<X> theRoot = tree.get(root);
+ return theRoot.childrenWithEquivalents()
+ .flatMap(it -> collectDirect(theRoot, it))
+ .collect(Collectors.toSet());
+ }
+
+ private static <X extends Resource> boolean hasAnotherPath(X given,
+ X root,
+ Function<X, Set<X>> getChildren) {
+ return getChildren.apply(root).stream()
+ .filter(it -> !equivalent(it, root, getChildren))
+ .flatMap(it ->
+ getChildren.apply(it).stream().filter(x -> !equivalent(x, it, getChildren))
+ )
+ .anyMatch(given::equals);
+ }
+
+ @SuppressWarnings("BooleanMethodIsAlwaysInverted")
+ private static <X extends Resource> boolean equivalent(X left, X right, Function<X, Set<X>> getChildren) {
+ return getChildren.apply(right).contains(left) && getChildren.apply(left).contains(right);
+ }
+
+ private static <X extends Resource> Stream<X> collectDirect(Node<X> rootNode, Node<X> it) {
+ Set<X> equivalents = it.equivalents();
+ if (!equivalents.contains(rootNode.node)) {
+ Set<X> siblings = new HashSet<>(equivalents);
+ siblings.remove(it.node);
+ if (it.hasMoreThanOnePathTo(rootNode, siblings)) {
+ return Stream.empty();
+ } else {
+ equivalents.add(it.node);
+ return equivalents.stream();
+ }
+ } else {
+ return Stream.empty();
+ }
+ }
+
+ private static <X extends Resource> Map<X, Node<X>> collectTree(X root, Function<X, Stream<X>> listChildren) {
+ Map<X, Set<X>> childrenNodesCache = new HashMap<>();
+ Map<X, Node<X>> res = new HashMap<>();
+ Set<X> visited = new HashSet<>();
+ Deque<X> queue = new ArrayDeque<>();
+ queue.add(root);
+ while (!queue.isEmpty()) {
+ X next = queue.removeFirst();
+ if (!visited.add(next)) {
+ continue;
+ }
+ Set<X> nextChildren = getChildren(next, listChildren, childrenNodesCache);
+ Node<X> nextNode = res.computeIfAbsent(next, Node::new);
+ nextChildren.forEach(child -> {
+ Node<X> childNode = res.computeIfAbsent(child, Node::new);
+ nextNode.children.add(childNode);
+ queue.add(child);
+ });
+ }
+ return res;
+ }
+
+ private static <X extends Resource> Set<X> getChildren(
+ X root,
+ Function<X, Stream<X>> listChildren,
+ Map<X, Set<X>> childrenNodesCache
+ ) {
+ return childrenNodesCache.computeIfAbsent(root, it -> {
+ try (Stream<X> children = listChildren.apply(it)) {
+ return children.collect(Collectors.toSet());
+ }
+ });
+ }
+
+ /**
+ * Auxiliary class, tree node that is used for builtin hierarchy support.
+ *
+ * @param <X> resource
+ */
+ private static class Node<X extends Resource> {
+ final X node;
+ final Set<Node<X>> children = new HashSet<>();
+
+ Node(X node) {
+ this.node = node;
+ }
+
+ Stream<Node<X>> childrenWithEquivalents() {
+ Set<X> equivalents = this.equivalents();
+ return children.stream().flatMap(ch -> {
+ if (equivalents.contains(ch.node)) {
+ return ch.children.stream().filter(ech -> !ech.equals(Node.this));
+ } else {
+ return Stream.of(ch);
+ }
+ });
+ }
+
+ boolean hasMoreThanOnePathTo(Node<X> given, Set<X> exclude) {
+ Deque<Node<X>> queue = new ArrayDeque<>();
+ Set<X> visited = new HashSet<>();
+ int res = 0;
+ Iterator<Node<X>> firstLevelChildren = given.childrenWithEquivalents().iterator();
+ while (firstLevelChildren.hasNext()) {
+ Node<X> child = firstLevelChildren.next();
+ if (exclude.contains(child.node)) {
+ continue;
+ }
+ if (child.node.equals(this.node)) {
+ res++;
+ } else {
+ queue.add(child);
+ }
+ }
+ while (!queue.isEmpty()) {
+ Node<X> next = queue.removeFirst();
+ if (exclude.contains(next.node)) {
+ continue;
+ }
+ if (next.node.equals(given.node)) {
+ continue;
+ }
+ if (next.node.equals(this.node)) {
+ if (++res > 1) {
+ return true;
+ }
+ }
+ if (!visited.add(next.node)) {
+ continue;
+ }
+ next.childrenWithEquivalents().forEach(queue::add);
+ }
+ return false;
+ }
+
+ Set<X> equivalents() {
+ Deque<Node<X>> queue = new ArrayDeque<>();
+ queue.add(this);
+ Set<X> visited = new HashSet<>();
+ Map<X, Set<X>> paths = new HashMap<>();
+ Set<X> res = new HashSet<>();
+ while (!queue.isEmpty()) {
+ Node<X> next = queue.removeFirst();
+ Set<X> nextPaths = paths.computeIfAbsent(next.node, it -> new HashSet<>());
+ if (!nextPaths.isEmpty() && next.node.equals(this.node)) {
+ // cycle, all nodes in cycle are equivalent
+ res.addAll(nextPaths);
+ nextPaths.forEach(p -> {
+ Set<X> other = paths.get(p);
+ if (other != null) {
+ res.addAll(other);
+ }
+ });
+ continue;
+ }
+ if (!visited.add(next.node)) {
+ continue;
+ }
+ next.children.forEach(child -> {
+ Set<X> childPaths = paths.computeIfAbsent(child.node, it -> new HashSet<>());
+ childPaths.add(next.node);
+ childPaths.addAll(nextPaths);
+ queue.add(child);
+ });
+ }
+ return res;
+ }
+
+ @Override
+ public String toString() {
+ return node.asNode().toString();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof Node)) return false;
+ return node.equals(((Node<?>) o).node);
+ }
+
+ @Override
+ public int hashCode() {
+ return node.hashCode();
+ }
+ }
+
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/OntGraphModelImpl.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/OntGraphModelImpl.java
new file mode 100644
index 0000000000..91ed0c76e3
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/OntGraphModelImpl.java
@@ -0,0 +1,1854 @@
+/*
+ * 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.jena.ontapi.impl;
+
+import org.apache.jena.ontapi.OntJenaException;
+import org.apache.jena.ontapi.OntModelControls;
+import org.apache.jena.ontapi.UnionGraph;
+import org.apache.jena.ontapi.common.EnhNodeFactory;
+import org.apache.jena.ontapi.common.OntConfig;
+import org.apache.jena.ontapi.common.OntEnhGraph;
+import org.apache.jena.ontapi.common.OntEnhNodeFactories;
+import org.apache.jena.ontapi.common.OntPersonalities;
+import org.apache.jena.ontapi.common.OntPersonality;
+import org.apache.jena.ontapi.impl.objects.OntClassImpl;
+import org.apache.jena.ontapi.impl.objects.OntDataRangeImpl;
+import org.apache.jena.ontapi.impl.objects.OntDisjointImpl;
+import org.apache.jena.ontapi.impl.objects.OntFacetRestrictionImpl;
+import org.apache.jena.ontapi.impl.objects.OntIndividualImpl;
+import org.apache.jena.ontapi.impl.objects.OntListImpl;
+import org.apache.jena.ontapi.impl.objects.OntObjectImpl;
+import org.apache.jena.ontapi.impl.objects.OntSWRLImpl;
+import org.apache.jena.ontapi.impl.objects.OntStatementImpl;
+import org.apache.jena.ontapi.model.OntAnnotationProperty;
+import org.apache.jena.ontapi.model.OntClass;
+import org.apache.jena.ontapi.model.OntDataProperty;
+import org.apache.jena.ontapi.model.OntDataRange;
+import org.apache.jena.ontapi.model.OntDisjoint;
+import org.apache.jena.ontapi.model.OntEntity;
+import org.apache.jena.ontapi.model.OntFacetRestriction;
+import org.apache.jena.ontapi.model.OntID;
+import org.apache.jena.ontapi.model.OntIndividual;
+import org.apache.jena.ontapi.model.OntList;
+import org.apache.jena.ontapi.model.OntModel;
+import org.apache.jena.ontapi.model.OntObject;
+import org.apache.jena.ontapi.model.OntObjectProperty;
+import org.apache.jena.ontapi.model.OntSWRL;
+import org.apache.jena.ontapi.model.OntStatement;
+import org.apache.jena.ontapi.utils.Graphs;
+import org.apache.jena.ontapi.utils.Iterators;
+import org.apache.jena.ontapi.utils.OntModels;
+import org.apache.jena.ontapi.utils.StdModels;
+import org.apache.jena.ontapi.vocabulary.OWL;
+import org.apache.jena.ontapi.vocabulary.RDF;
+import org.apache.jena.datatypes.BaseDatatype;
+import org.apache.jena.datatypes.RDFDatatype;
+import org.apache.jena.datatypes.TypeMapper;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.enhanced.PersonalityConfigException;
+import org.apache.jena.graph.Graph;
+import org.apache.jena.graph.GraphMemFactory;
+import org.apache.jena.graph.Node;
+import org.apache.jena.graph.NodeFactory;
+import org.apache.jena.graph.Triple;
+import org.apache.jena.rdf.model.InfModel;
+import org.apache.jena.rdf.model.Literal;
+import org.apache.jena.rdf.model.Model;
+import org.apache.jena.rdf.model.Property;
+import org.apache.jena.rdf.model.RDFList;
+import org.apache.jena.rdf.model.RDFNode;
+import org.apache.jena.rdf.model.Resource;
+import org.apache.jena.rdf.model.Statement;
+import org.apache.jena.rdf.model.StmtIterator;
+import org.apache.jena.rdf.model.impl.IteratorFactory;
+import org.apache.jena.rdf.model.impl.ModelCom;
+import org.apache.jena.reasoner.Derivation;
+import org.apache.jena.reasoner.InfGraph;
+import org.apache.jena.reasoner.Reasoner;
+import org.apache.jena.reasoner.ValidityReport;
+import org.apache.jena.shared.JenaException;
+import org.apache.jena.shared.PrefixMapping;
+import org.apache.jena.util.iterator.ExtendedIterator;
+import org.apache.jena.util.iterator.NullIterator;
+import org.apache.jena.util.iterator.WrappedIterator;
+import org.apache.jena.vocabulary.RDFS;
+import org.apache.jena.vocabulary.ReasonerVocabulary;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.Writer;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.Spliterator;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * Base model ONT-API implementation to work through jena only.
+ * This is an analogue of {@link org.apache.jena.ontology.impl.OntModelImpl} to work in accordance with OWL2 DL specification.
+ *
+ * @see UnionGraph
+ */
+@SuppressWarnings({"WeakerAccess", "SameParameterValue", "unused"})
+public class OntGraphModelImpl extends ModelCom implements OntModel, OntEnhGraph, InfModel {
+
+ // the model's types mapper
+ protected final Map<String, RDFDatatype> dtTypes = new HashMap<>();
+ // to control RDF recursion while casting a node to an RDF view, see #fetchNodeAs(Node, Class)
+ private final ThreadLocal<Set<Node>> visited = ThreadLocal.withInitial(HashSet::new);
+ // Cached deductions model
+ private Model deductionsModel = null;
+ // collection of entity types, used when list entities
+ private final Set<Class<? extends OntEntity>> supportedEntityTypes;
+ // a cache with values of arbitrary nature, which can be used for various purposes,
+ // e.g., as a storage of reserved nodes when construct OntObjects
+ public final Map<String, Object> propertyStore = new HashMap<>();
+
+ public OntGraphModelImpl(UnionGraph graph, OntPersonality personality) {
+ this((Graph) graph, personality);
+ }
+
+ public OntGraphModelImpl(InfGraph graph, OntPersonality personality) {
+ this((Graph) graph, personality);
+ }
+
+ /**
+ * This {@link OntModel} implementation wraps
+ * only {@link UnionGraph} or {@link InfGraph} which in turn wraps {@link UnionGraph}.
+ *
+ * @param graph {@link Graph}
+ * @param personality {@link OntPersonality}
+ */
+ protected OntGraphModelImpl(Graph graph, OntPersonality personality) {
+ super(makeGraph(graph), OntPersonality.asJenaPersonality(personality));
+ this.supportedEntityTypes = OntEntity.TYPES.stream().filter(personality::supports).collect(Collectors.toSet());
+ }
+
+ protected static Graph makeGraph(Graph given) {
+ Objects.requireNonNull(given);
+ if (given instanceof InfGraph) {
+ Graph raw = ((InfGraph) given).getRawGraph();
+ if (raw instanceof UnionGraph) {
+ return given;
+ }
+ throw new IllegalArgumentException(
+ "The specified InfGraph does not wrap UnionGraph, instead it wraps " + raw.getClass().getSimpleName()
+ );
+ }
+ if (given instanceof UnionGraph) {
+ return given;
+ }
+ throw new IllegalArgumentException(
+ "The specified graph is not UnionGraph or InfGraph: " + given.getClass().getSimpleName()
+ );
+ }
+
+ /**
+ * Lists all {@code OntObject}s for the given {@code OntGraphModelImpl}.
+ *
+ * @param m {@link OntGraphModelImpl} the impl to cache
+ * @param type {@link Class} the type of {@link OntObject}, not null
+ * @param <M> a subtype of {@link EnhGraph} and {@link OntEnhGraph}
+ * @param <O> subtype of {@link OntObject}
+ * @return an {@link ExtendedIterator Extended Iterator} of {@link OntObject}s
+ */
+ @SuppressWarnings("unchecked")
+ public static <M extends EnhGraph & OntEnhGraph, O extends OntObject> ExtendedIterator<O> listOntObjects(
+ M m,
+ Class<? extends O> type) {
+ OntPersonality p = m.getOntPersonality();
+ if (p.supports(type)) {
+ ExtendedIterator<?> res = p.getObjectFactory(type).iterator(m);
+ return (ExtendedIterator<O>) res;
+ } else {
+ return NullIterator.instance();
+ }
+ }
+
+ /**
+ * Filters {@code OntIndividual}s from the specified {@code ExtendedIterator}.
+ *
+ * @param model {@link M}, not {@code null}
+ * @param reserved a {@code Set} of forbidden URIs,
+ * that cannot be treated as {@link OntClass Ontology Class}es, not {@code null}
+ * @param assertions {@link ExtendedIterator} of {@link Triple}s
+ * with the {@link RDF#type rdf:type} as predicate, not {@code null}
+ * @param <M> a subtype of {@link OntModel} and {@link OntEnhGraph}
+ * @return {@link ExtendedIterator} of {@link OntIndividual}s that are attached to the {@code model}
+ */
+ public static <M extends OntModel & OntEnhGraph> ExtendedIterator<OntIndividual> listIndividuals(M model,
+ Set<String> reserved,
+ ExtendedIterator<Triple> assertions) {
+ Set<Triple> seen = new HashSet<>();
+ boolean useSimplifiedClassChecking = model.getOntPersonality()
+ .getConfig().getBoolean(OntModelControls.USE_SIMPLIFIED_TYPE_CHECKING_WHILE_LIST_INDIVIDUALS);
+ boolean isRDFS = OntPersonalities.isRDFS(model.getOntPersonality());
+
+ return assertions
+ .mapWith(t -> {
+ // to speed up the process,
+ // the investigation (that includes TTO, PS, HP, GALEN, FAMILY and PIZZA ontologies),
+ // shows that the profit exists, and it is significant sometimes:
+ if (t.getObject().isURI() && reserved.contains(t.getObject().getURI())) {
+ return null;
+ }
+
+ // skip duplicates (an individual may have several class-assertions):
+ if (seen.remove(t)) {
+ return null;
+ }
+ if (!testIsClass(model, t.getObject(), useSimplifiedClassChecking, isRDFS)) {
+ return null;
+ }
+ return model.asStatement(t);
+ })
+ .filterKeep(s -> {
+ if (s == null) return false;
+ // an individual may have a factory with punning restrictions,
+ // so need to check its type also.
+ // this time does not cache in a model
+ OntIndividual i = s.getSubject().getAs(OntIndividual.class);
+ if (i == null) return false;
+
+ // update the set with duplicates to ensure the stream is distinct
+ ((OntIndividualImpl) i).listClasses()
+ .forEachRemaining(x -> {
+ if (s.getObject().equals(x)) {
+ // skip this statement, otherwise all individuals fall into memory
+ return;
+ }
+ seen.add(Triple.create(i.asNode(), RDF.Nodes.type, x.asNode()));
+ });
+ return true;
+ })
+ .mapWith(s -> s.getSubject(OntIndividual.class));
+ }
+
+ private static <M extends OntModel & OntEnhGraph> boolean testIsClass(
+ M model,
+ Node candidate,
+ boolean simpleCheck,
+ boolean isRDFS
+ ) {
+ if (simpleCheck) {
+ if (isRDFS) {
+ return testIsRDFSClass(model, candidate);
+ }
+ return testIsOWLClass(model, candidate);
+ }
+ OntClass clazz = model.safeFindNodeAs(candidate, OntClass.class);
+ return clazz != null && clazz.asAssertionClass() != null;
+ }
+
+ private static <M extends OntModel & OntEnhGraph> boolean testIsOWLClass(M model, Node candidate) {
+ if (model.getOntPersonality().getPunnings().getNamedClasses().contains(candidate)) {
+ return false;
+ }
+ if (model.getOntPersonality().getBuiltins().getNamedClasses().contains(candidate)) {
+ return true;
+ }
+ return Graphs.hasOneOfType(candidate, model.getGraph(), Set.of(OWL.Class.asNode(), OWL.Restriction.asNode()));
+ }
+
+ private static boolean testIsRDFSClass(Model model, Node candidate) {
+ return model.getGraph().contains(candidate, RDF.type.asNode(), RDFS.Class.asNode());
+ }
+
+ /**
+ * Creates a {@code Stream} for a graph.
+ *
+ * @param graph {@link Graph} to test
+ * @param it {@code ExtendedIterator} obtained from the {@code graph}
+ * @param withSize if {@code true} attempts to include graph size as an estimated size of a future {@code Stream}
+ * @param <X> type of stream items
+ * @return {@code Stream} of {@link X}s
+ */
+ private static <X> Stream<X> asStream(Graph graph,
+ ExtendedIterator<X> it,
+ boolean withSize) {
+ int characteristics = Graphs.getSpliteratorCharacteristics(graph);
+ long size = -1;
+ if (withSize && Graphs.isSized(graph)) {
+ size = Graphs.size(graph);
+ characteristics = characteristics | Spliterator.SIZED;
+ }
+ return Iterators.asStream(it, size, characteristics);
+ }
+
+ public static void checkFeature(OntModel m, OntModelControls setting, String featureName) {
+ OntJenaException.checkSupported(configValue(m, setting),
+ "Feature " + featureName + " is disabled. " +
+ "Profile " + OntEnhGraph.asPersonalityModel(m).getOntPersonality().getName());
+ }
+
+ public static boolean configValue(OntModel m, OntModelControls setting) {
+ OntConfig config = OntModels.config(m);
+ return config != null && config.getBoolean(setting);
+ }
+
+ @Override
+ public OntPersonality getOntPersonality() {
+ return (OntPersonality) super.getPersonality();
+ }
+
+ /**
+ * Returns {@code UnionGraph}.
+ * This implementation requires that the underlying graph is union-graph or inf-graph.
+ *
+ * @return {@link UnionGraph}
+ */
+ public UnionGraph getUnionGraph() {
+ Graph graph = super.getGraph();
+ if (graph instanceof InfGraph) {
+ Graph raw = ((InfGraph) graph).getRawGraph();
+ if (raw instanceof UnionGraph) {
+ return ((UnionGraph) raw);
+ }
+ throw new IllegalStateException(
+ "The encapsulated InfGraph does not wrap UnionGraph, instead it wraps " + raw.getClass().getSimpleName()
+ );
+ }
+ if (graph instanceof UnionGraph) {
+ return ((UnionGraph) graph);
+ }
+ throw new IllegalStateException(
+ "The model wraps " + graph.getClass().getSimpleName() + ", that is illegal"
+ );
+ }
+
+ @Override
+ public Graph getBaseGraph() {
+ return getUnionGraph().getBaseGraph();
+ }
+
+ @Override
+ public Model getBaseModel() {
+ return new ModelCom(getBaseGraph());
+ }
+
+ @Override
+ public OntID getID() {
+ checkType(OntID.class);
+ Optional<OntID> id = id();
+ if (id.isEmpty() && !configValue(this, OntModelControls.USE_GENERATE_ONTOLOGY_HEADER_IF_ABSENT_STRATEGY)) {
+ throw new OntJenaException.IllegalState("No ontology header found, use OntModel#setID method instead");
+ }
+ return id.orElseGet(() -> setID(null));
+ }
+
+ @Override
+ public OntIndividual createIndividual(String uri, OntClass type) {
+ if (uri == null) {
+ checkFeature(this, OntModelControls.ALLOW_ANONYMOUS_INDIVIDUALS, "anonymous-individuals");
+ }
+ return OntModel.super.createIndividual(uri, type);
+ }
+
+ @Override
+ public Optional<OntID> id() {
+ checkType(OntID.class);
+ return Graphs.ontologyNode(
+ getBaseGraph(), configValue(this, OntModelControls.USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY)
+ ).map(x -> getNodeAs(x, OntID.class));
+ }
+
+ @Override
+ public OntID setID(String uri) {
+ checkType(OntID.class);
+ UnionGraph ug = getUnionGraph();
+ UnionGraph.EventManager em = ug.getEventManager();
+ em.notifyEvent(ug, OntModelEvent.startChangeIDEvent());
+ Node id = Graphs.createOntologyHeaderNode(getBaseGraph(), uri);
+ OntID res = getNodeAs(id, OntID.class);
+ em.notifyEvent(ug, OntModelEvent.finishChangeIDEvent());
+ return res;
+ }
+
+ @Override
+ public OntGraphModelImpl addImport(OntModel m) {
+ checkType(OntID.class);
+ if (Objects.requireNonNull(m, "Null model specified.").getID().isAnon()) {
+ throw new OntJenaException.IllegalArgument("Anonymous sub models are not allowed.");
+ }
+ String importsURI = m.id().map(OntID::getImportsIRI)
+ .orElseThrow(() -> new IllegalArgumentException("Attempt to import unnamed ontology"));
+ if (importsURI.equals(getID().getURI())) {
+ throw new OntJenaException.IllegalArgument("Attempt to import ontology with the same name: " + importsURI);
+ }
+ if (hasImport(importsURI)) {
+ throw new OntJenaException.IllegalArgument("Ontology <" + importsURI + "> is already in imports.");
+ }
+ Graph g = m.getGraph();
+ if (g instanceof InfGraph) {
+ g = ((InfGraph) g).getRawGraph();
+ }
+ if (g instanceof UnionGraph && !Graphs.isOntUnionGraph((UnionGraph) g,
+ configValue(this, OntModelControls.USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY))) {
+ throw new OntJenaException.IllegalArgument("Ontology <" + importsURI + "> has wrong structure.");
+ }
+ addImportModel(g, importsURI);
+ return this;
+ }
+
+ @Override
+ public boolean hasImport(OntModel m) {
+ Objects.requireNonNull(m);
+ return findImportAsRawModel(x -> Graphs.isSameBase(x.getGraph(), m.getGraph())).isPresent();
+ }
+
+ @Override
+ public boolean hasImport(String uri) {
+ return findImportAsRawModel(x -> Objects.equals(x.getID().getImportsIRI(), uri)).isPresent();
+ }
+
+ @Override
+ public OntGraphModelImpl removeImport(OntModel m) {
+ Objects.requireNonNull(m);
+ Graph g = m.getGraph();
+ Graph data;
+ if (g instanceof InfGraph) {
+ data = ((InfGraph) g).getRawGraph();
+ } else {
+ data = g;
+ }
+ findImportAsRawModel(it -> Graphs.isSameBase(it.getGraph(), data))
+ .ifPresent(it -> removeImportModel(it.getGraph(), it.getID().getImportsIRI()));
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl removeImport(String uri) {
+ findImportAsRawModel(x -> Objects.equals(uri, x.getID().getImportsIRI()))
+ .ifPresent(x -> removeImportModel(x.getGraph(), x.getID().getImportsIRI()));
+ return this;
+ }
+
+ @Override
+ public Stream<OntModel> imports() {
+ return imports(getOntPersonality());
+ }
+
+ /**
+ * Lists all top-level sub-models built with the given {@code personality}.
+ *
+ * @param personality {@link OntPersonality}, not {@code null}
+ * @return {@code Stream} of {@link OntModel}s
+ */
+ public Stream<OntModel> imports(OntPersonality personality) {
+ return Iterators.asStream(listImportModels(personality, getReasoner()));
+ }
+
+ /**
+ * Finds a model impl from the internals using the given {@code filter}.
+ * The returned model has no reasoner attached.
+ *
+ * @param filter {@code Predicate} to filter {@link OntGraphModelImpl}s
+ * @return {@code Optional} around {@link OntGraphModelImpl}
+ */
+ protected Optional<OntGraphModelImpl> findImportAsRawModel(Predicate<OntGraphModelImpl> filter) {
+ return Iterators.findFirst(listImportModels(getOntPersonality(), null).filterKeep(filter));
+ }
+
+ /**
+ * Adds the graph-uri pair into the internals.
+ *
+ * @param graph {@link Graph}, not {@code null}
+ * @param uri String, not {@code null}
+ */
+ protected void addImportModel(Graph graph, String uri) {
+ getUnionGraph().addSubGraph(graph);
+ getID().addImport(uri);
+ rebind();
+ }
+
+ /**
+ * Removes the graph-uri pair from the internals.
+ *
+ * @param graph {@link Graph}, not {@code null}
+ * @param uri String, not {@code null}
+ */
+ protected void removeImportModel(Graph graph, String uri) {
+ getUnionGraph().removeSubGraph(graph);
+ getID().removeImport(uri);
+ rebind();
+ }
+
+ /**
+ * Lists {@link OntGraphModelImpl model impl}s with the specified {@code personality}
+ * from the top tier of the imports' hierarchy.
+ *
+ * @param personality {@link OntPersonality}, not {@code null}
+ * @param reasoner {@link Reasoner}, can be {@code null}
+ * @return <b>non-distinct</b> {@code ExtendedIterator} of {@link OntGraphModelImpl}s
+ */
+ public final ExtendedIterator<OntGraphModelImpl> listImportModels(OntPersonality personality, Reasoner reasoner) {
+ return listImportGraphs().mapWith(u -> {
+ Graph g;
+ if (reasoner != null) {
+ g = reasoner.bind(u);
+ } else {
+ g = u;
+ }
+ return new OntGraphModelImpl(g, personality);
+ });
+ }
+
+ /**
+ * Lists all top-level {@link UnionGraph}s of the model's {@code owl:import} hierarchy.
+ * This model graph is not included.
+ *
+ * @return {@code ExtendedIterator} of {@link UnionGraph}s
+ */
+ protected final ExtendedIterator<UnionGraph> listImportGraphs() {
+ UnionGraph u = getUnionGraph();
+ ExtendedIterator<Graph> subGraphs;
+ if (u instanceof UnionGraphImpl) {
+ subGraphs = ((UnionGraphImpl) u).getSubGraphs().listGraphs();
+ } else {
+ subGraphs = WrappedIterator.create(u.subGraphs().iterator());
+ }
+ Set<String> imports = Graphs.getImports(u.getBaseGraph(),
+ configValue(this, OntModelControls.USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY));
+ return subGraphs
+ .filterKeep(x -> x instanceof UnionGraph)
+ .mapWith(x -> (UnionGraph) x)
+ .filterKeep(it -> Graphs.findOntologyNameNode(it.getBaseGraph(),
+ configValue(this, OntModelControls.USE_CHOOSE_MOST_SUITABLE_ONTOLOGY_HEADER_STRATEGY))
+ .filter(Node::isURI)
+ .map(Node::getURI)
+ .filter(imports::contains)
+ .isPresent()
+ );
+ }
+
+ /**
+ * Gets the top-level {@link OntGraphModelImpl Ontology Graph Model impl}.
+ * The returned model may contain import declarations, but cannot contain sub-models.
+ * Be warned: any listeners, attached on the {@link #getGraph()}
+ *
+ * @return {@link OntGraphModelImpl}
+ * @see #getBaseModel()
+ */
+ public OntGraphModelImpl getTopModel() {
+ if (independent()) {
+ return this;
+ }
+ OntPersonality personality = getOntPersonality();
+ return new OntGraphModelImpl(new UnionGraphImpl(getBaseGraph(), false), personality);
+ }
+
+ /**
+ * Determines whether this model is independent.
+ *
+ * @return {@code true} if this model is independent of others
+ */
+ @Override
+ public boolean independent() {
+ return !getUnionGraph().hasSubGraph();
+ }
+
+ /**
+ * Answers {@code true} if the given entity is built-in.
+ *
+ * @param e {@link OntEntity} object impl
+ * @param <E> subtype of {@link OntObjectImpl} and {@link OntEntity}
+ * @return boolean
+ */
+ public <E extends OntObjectImpl & OntEntity> boolean isBuiltIn(E e) {
+ return getOntPersonality().getBuiltins()
+ .get(e.objectType())
+ .contains(e.asNode());
+ }
+
+ /**
+ * Retrieves the stream of {@link OntObject Ontology Object}s.
+ * The result object will be cached inside the model.
+ * Note: this method may return non-distinct results,
+ * this is determined by the reasoner and nature of the underlying graph;
+ * for non-inference the standard memory graph implementation the result Stream is distinct.
+ *
+ * @param type {@link Class} the type of {@link OntObject}, not null
+ * @param <O> subtype of {@link OntObject}
+ * @return {@code Stream} of {@link OntObject}s
+ */
+ @Override
+ public <O extends OntObject> Stream<O> ontObjects(Class<? extends O> type) {
+ return Iterators.asStream(listOntObjects(type), Graphs.getSpliteratorCharacteristics(getGraph()));
+ }
+
+ /**
+ * Lists all {@link OntObject Ontology Object}s and caches them inside this model.
+ *
+ * @param type {@link Class} the type of {@link OntObject}, not null
+ * @param <O> subtype of {@link OntObject}
+ * @return an {@link ExtendedIterator Extended Iterator} of {@link OntObject}s
+ */
+ public <O extends OntObject> ExtendedIterator<O> listOntObjects(Class<? extends O> type) {
+ return listOntObjects(this, type);
+ }
+
+ /**
+ * The same as {@link OntGraphModelImpl#listOntObjects(Class)}, but for the base graph.
+ *
+ * @param type {@link Class} the type of {@link OntObject}, not null
+ * @param <O> subtype of {@link OntObject}
+ * @return {@link ExtendedIterator Extended Iterator} of {@link OntObject}s
+ */
+ public <O extends OntObject> ExtendedIterator<O> listLocalOntObjects(Class<? extends O> type) {
+ return listOntObjects(getTopModel(), type);
+ }
+
+ @Override
+ public Stream<OntEntity> ontEntities() {
+ return supportedEntityTypes.stream().flatMap(this::ontObjects);
+ }
+
+ /**
+ * Lists all Ontology Entities.
+ * Built-ins are not included.
+ *
+ * @return {@link ExtendedIterator Extended Iterator} of {@link OntEntity}s
+ * @see #listLocalOntEntities()
+ */
+ public ExtendedIterator<OntEntity> listOntEntities() {
+ return Iterators.flatMap(Iterators.create(supportedEntityTypes), this::listOntObjects);
+ }
+
+ /**
+ * The same as {@link #listOntEntities()} but for the base graph.
+ *
+ * @return {@link ExtendedIterator Extended Iterator} of {@link OntEntity}s
+ * @see #listOntEntities()
+ */
+ public ExtendedIterator<OntEntity> listLocalOntEntities() {
+ return Iterators.flatMap(Iterators.create(supportedEntityTypes), this::listLocalOntObjects);
+ }
+
+ /**
+ * Gets 'punnings', i.e. the {@link OntEntity}s which have not only a single type.
+ *
+ * @param withImports if it false takes into account only the base model
+ * @return {@code Stream} of {@link OntEntity}s.
+ */
+ public Stream<OntEntity> ambiguousEntities(boolean withImports) {
+ return ontEntities().filter(e -> withImports || e.isLocal()).filter(e -> supportedEntityTypes.stream()
+ .filter(view -> e.canAs(view) && (withImports || e.as(view).isLocal())).count() > 1);
+ }
+
+ @Override
+ public Stream<OntIndividual> individuals() {
+ return Iterators.asStream(listIndividuals(), Graphs.getSpliteratorCharacteristics(getGraph()));
+ }
+
+ /**
+ * Returns an {@code ExtendedIterator} over all individuals
+ * that participate in class assertion statement {@code a rdf:type C}.
+ * <b>Note:</b> this method behaves differently than
+ * the method {@link org.apache.jena.ontology.impl.OntModelImpl#listIndividuals()}!
+ * The Jena's method does not verify that the right side of the class-assertion is indeed a valid class expression;
+ * it checks only several well-known cases.
+ *
+ * @return {@link ExtendedIterator} of {@link OntIndividual}s
+ */
+ public ExtendedIterator<OntIndividual> listIndividuals() {
+ OntPersonality personality = getOntPersonality();
+ boolean isRDFS = OntPersonalities.isRDFS(personality);
+ boolean withOWLThing = OntPersonalities.supportsOWLThing(personality);
+ if (!isRDFS && withOWLThing) {
+ Model capabilities = getReasonerCapabilities();
+ if (capabilities != null &&
+ capabilities.contains(null, ReasonerVocabulary.supportsP, ReasonerVocabulary.individualAsThingP)) {
+ return listStatements(null, RDF.type, OWL.Thing).mapWith(it -> it.getSubject().as(OntIndividual.class));
+ }
+ }
+ return listIndividuals(this,
+ personality.forbidden(OntClass.Named.class),
+ getGraph().find(Node.ANY, RDF.Nodes.type, Node.ANY));
+ }
+
+ @Override
+ public Stream<OntClass> hierarchyRoots() {
+ return Iterators.asStream(listHierarchyRoots(), Graphs.getSpliteratorCharacteristics(getGraph()));
+ }
+
+ public ExtendedIterator<OntClass> listHierarchyRoots() {
+ if (OntPersonalities.supportsOWLThing(getOntPersonality())) {
+ Model capabilities = getReasonerCapabilities();
+ if (capabilities != null && capabilities.contains(null, ReasonerVocabulary.supportsP, ReasonerVocabulary.directSubClassOf)) {
+ return listStatements(null, ReasonerVocabulary.directSubClassOf, OWL.Thing).mapWith(it -> it.getSubject().as(OntClass.class));
+ }
+ }
+ Set<Node> reserved = getOntPersonality().getReserved().getAllResources();
+ return listOntObjects(OntClass.class)
+ .filterDrop(c -> reserved.contains(c.asNode()))
+ .filterKeep(OntClass::isHierarchyRoot);
+ }
+
+ @Override
+ public <E extends OntEntity> E getOntEntity(Class<E> type, String uri) {
+ return findNodeAs(NodeFactory.createURI(OntJenaException.notNull(uri, "Null uri.")), type);
+ }
+
+ @Override
+ public <T extends OntEntity> T createOntEntity(Class<T> type, String iri) {
+ try {
+ return createOntObject(type, iri);
+ } catch (OntJenaException.Creation ex) {
+ // illegal punning ?
+ throw new OntJenaException.Creation(
+ String.format("Creation of %s <%s> is not allowed by the configuration. Profile: %s",
+ OntEnhNodeFactories.viewAsString(type), iri, getOntPersonality().getName()),
+ ex);
+ }
+ }
+
+ /**
+ * Creates and caches an ontology object resource by the given type and uri.
+ *
+ * @param type Class, object type
+ * @param uri String, URI (IRI), can be {@code null} for anonymous resource
+ * @param <T> class-type of {@link OntObject}
+ * @return {@link OntObject}, new instance
+ * @throws OntJenaException.Unsupported profile mismatch
+ */
+ public <T extends OntObject> T createOntObject(Class<T> type, String uri) {
+ OntPersonality personality = getOntPersonality();
+ OntJenaException.checkSupported(personality.supports(type),
+ "Attempt to create resource <" + uri + ">. Profile " + personality.getName() +
+ " does not support language construct " + OntEnhNodeFactories.viewAsString(type));
+ Node node = Graphs.createNode(uri);
+ EnhNodeFactory factory = personality.getObjectFactory(type);
+ return factory.createInGraph(node, this).as(type);
+ }
+
+ @Override
+ public OntGraphModelImpl removeOntObject(OntObject obj) {
+ obj.clearAnnotations().content()
+ .peek(OntStatement::clearAnnotations)
+ .collect(Collectors.toSet()).forEach(this::remove);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl removeOntStatement(OntStatement statement) {
+ return remove(statement.clearAnnotations());
+ }
+
+ @Override
+ public Stream<OntStatement> statements() {
+ Graph g = getGraph();
+ return asStream(g, g.find().mapWith(this::asStatement), true);
+ }
+
+ @Override
+ public Stream<OntStatement> statements(Resource s, Property p, RDFNode o) {
+ return asStream(getGraph(), listOntStatements(s, p, o), StdModels.isANY(s, p, o));
+ }
+
+ @Override
+ public Stream<OntStatement> localStatements(Resource s, Property p, RDFNode o) {
+ return asStream(getBaseGraph(), listLocalStatements(s, p, o), StdModels.isANY(s, p, o));
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @param s {@link Resource} the subject sought, can be {@code null}
+ * @param p {@link Property} the predicate sought, can be {@code null}
+ * @param o {@link RDFNode} the object sought, can be {@code null}
+ * @return {@link StmtIterator} of {@link OntStatement}s
+ */
+ @Override
+ public StmtIterator listStatements(Resource s, Property p, RDFNode o) {
+ return StdModels.createStmtIterator(getGraph().find(asNode(s), asNode(p), asNode(o)), this::asStatement);
+ }
+
+ /**
+ * Returns an {@link ExtendedIterator extended iterator} over all the statements in the model that match a pattern.
+ * The statements selected are those whose subject matches the {@code s} argument,
+ * whose predicate matches the {@code p} argument
+ * and whose object matches the {@code o} argument.
+ * If an argument is {@code null} it matches anything.
+ * The method is equivalent to the expression {@code listStatements(s, p, o).mapWith(OntStatement.class::cast)}.
+ *
+ * @param s {@link Resource} the subject sought, can be {@code null}
+ * @param p {@link Property} the predicate sought, can be {@code null}
+ * @param o {@link RDFNode} the object sought, can be {@code null}
+ * @return {@link ExtendedIterator} of {@link OntStatement}s
+ * @see #listStatements(Resource, Property, RDFNode)
+ */
+ public ExtendedIterator<OntStatement> listOntStatements(Resource s, Property p, RDFNode o) {
+ return Iterators.create(getGraph().find(asNode(s), asNode(p), asNode(o)).mapWith(this::asStatement));
+ }
+
+ /**
+ * Lists all statements in the <b>base</b> model that match a pattern
+ * in the form of {@link ExtendedIterator Extended Iterator}.
+ * The method is equivalent to the expression
+ * {@code listStatements(s, p, o).mapWith(OntStatement.class::cast).filterKeep(OntStatement::isLocal)}.
+ *
+ * @param s {@link Resource} the subject sought, can be {@code null}
+ * @param p {@link Property} the predicate sought, can be {@code null}
+ * @param o {@link RDFNode} the object sought, can be {@code null}
+ * @return {@link ExtendedIterator} of {@link OntStatement}s, which are local to the base graph
+ * @see #listStatements(Resource, Property, RDFNode)
+ */
+ public ExtendedIterator<OntStatement> listLocalStatements(Resource s, Property p, RDFNode o) {
+ return Iterators.create(getBaseGraph().find(asNode(s), asNode(p), asNode(o)).mapWith(this::asStatement));
+ }
+
+ @Override
+ public OntStatementImpl createStatement(Resource s, Property p, RDFNode o) {
+ return OntStatementImpl.createOntStatementImpl(s, p, o, this);
+ }
+
+ @Override
+ public OntStatementImpl asStatement(Triple triple) {
+ return OntStatementImpl.createOntStatementImpl(triple, this);
+ }
+
+ /**
+ * Determines if the given {@code (s, p, o)} pattern is present in the base graph,
+ * with {@code null} allowed to represent a wildcard match.
+ *
+ * @param s - {@link Resource} - the subject of the statement tested ({@code null} as wildcard)
+ * @param p - {@link Property} - the predicate of the statement tested ({@code null} as wildcard)
+ * @param o - {@link RDFNode} - the object of the statement tested ({@code null} as wildcard)
+ * @return boolean
+ * @see Model#contains(Resource, Property, RDFNode)
+ */
+ public boolean containsLocal(Resource s, Property p, RDFNode o) {
+ return getBaseGraph().contains(asNode(s), asNode(p), asNode(o));
+ }
+
+ /**
+ * Wraps the existing given {@link RDFList []-list} as {@link OntList ONT-list}.
+ *
+ * @param list {@link RDFList}, not {@code null}
+ * @param subject {@link OntObject}, not {@code null}
+ * @param predicate {@link Property}, not {@code null}
+ * @param type a {@code Class}-type for list element {@link E}, not {@code null}
+ * @param <E> any {@link RDFNode}
+ * @return {@code OntList}
+ */
+ public <E extends RDFNode> OntListImpl<E> asOntList(RDFList list,
+ OntObject subject,
+ Property predicate,
+ Class<E> type) {
+ return asOntList(list, subject, predicate, false, null, type);
+ }
+
+ /**
+ * Wraps the existing given {@link RDFList []-list} as {@link OntList ONT-list}.
+ *
+ * @param list {@link RDFList}, not {@code null}
+ * @param subject {@link OntObject}, not {@code null}
+ * @param predicate {@link Property}, not {@code null}
+ * @param checkRecursions boolean, if {@code true} more careful and expensive checking for list content is performed
+ * @param listType an uri-{@link Resource}, used as an archaic RDF-type, usually this parameter should be {@code null}
+ * @param elementType a {@code Class}-type for list element {@link E}, not {@code null}
+ * @param <E> any {@link RDFNode}
+ * @return {@code OntList}
+ */
+ public <E extends RDFNode> OntListImpl<E> asOntList(RDFList list,
+ OntObject subject,
+ Property predicate,
+ boolean checkRecursions,
+ Resource listType,
+ Class<E> elementType) {
+ OntListImpl.checkRequiredInputs(subject, predicate, list, listType, elementType);
+ return checkRecursions ?
+ OntListImpl.asSafeOntList(list, this, subject, predicate, listType, elementType) :
+ OntListImpl.asOntList(list, this, subject, predicate, listType, elementType);
+ }
+
+ /**
+ * Creates ONT-List with given elements and other settings.
+ *
+ * @param subject {@link OntObject}, not {@code null}
+ * @param predicate {@link Property}, not {@code null}
+ * @param type a {@code Class}-type for element {@link E}, not {@code null}
+ * @param elements and {@code Iterator} of {@link E}-elements (the order is preserved), not {@code null}
+ * @param <E> any {@link RDFNode}
+ * @return {@code OntList}
+ */
+ public <E extends RDFNode> OntListImpl<E> createOntList(OntObject subject,
+ Property predicate,
+ Class<E> type,
+ Iterator<E> elements) {
+ return createOntList(subject, predicate, null, type, elements);
+ }
+
+ /**
+ * Creates ONT-List with given elements and other settings.
+ *
+ * @param subject {@link OntObject}, not {@code null}
+ * @param predicate {@link Property}, not {@code null}
+ * @param listType an uri-{@link Resource}, used as an archaic RDF-type, usually this parameter should be {@code null}
+ * @param elementType a {@code Class}-type for element {@link E}, not {@code null}
+ * @param elements and {@code Iterator} of {@link E}-elements (the order is preserved), not {@code null}
+ * @param <E> any {@link RDFNode}
+ * @return {@code OntList}
+ */
+ public <E extends RDFNode> OntListImpl<E> createOntList(OntObject subject,
+ Property predicate,
+ Resource listType,
+ Class<E> elementType,
+ Iterator<E> elements) {
+ OntListImpl.checkRequiredInputs(subject, predicate, listType, elementType);
+ return OntListImpl.create(this, subject, predicate, listType, elementType, Iterators.create(elements));
+ }
+
+ /**
+ * Lists all (bulk) annotation anonymous resources for the given {@code rdf:type} and SPO.
+ *
+ * @param t {@link Resource} either {@link OWL#Axiom owl:Axiom} or {@link OWL#Annotation owl:Annotation}
+ * @param s {@link Resource} subject
+ * @param p {@link Property} predicate
+ * @param o {@link RDFNode} object
+ * @return {@link ExtendedIterator} of annotation {@link Resource resource}s
+ */
+ public ExtendedIterator<Resource> listAnnotations(Resource t, Resource s, Property p, RDFNode o) {
+ return getGraph().find(Node.ANY, OWL.annotatedSource.asNode(), s.asNode())
+ .mapWith(this::asStatement)
+ .filterKeep(x -> (OWL.Axiom == t ? x.belongsToOWLAxiom() : x.belongsToOWLAnnotation())
+ && x.hasAnnotatedProperty(p) && x.hasAnnotatedTarget(o))
+ .mapWith(Statement::getSubject);
+ }
+
+ /**
+ * Deletes the specified {@code OntList} including its annotations.
+ *
+ * @param subject {@link OntObject} the subject of the OntList root statement
+ * @param predicate {@link Property} the predicate of the OntList root statement
+ * @param object {@link OntList} to be deleted
+ * @return this model instance
+ */
+ @SuppressWarnings("UnusedReturnValue")
+ public OntGraphModelImpl deleteOntList(OntObject subject, Property predicate, OntList<?> object) {
+ Objects.requireNonNull(subject);
+ Objects.requireNonNull(predicate);
+ OntJenaException.notNull(object, "Null list for subject " + subject + " and predicate " + predicate);
+ boolean hasNil = !object.isNil() && contains(subject, predicate, RDF.nil);
+ object.getMainStatement().clearAnnotations();
+ object.clear(); // now it is nil-list
+ if (!hasNil) {
+ return remove(subject, predicate, object);
+ }
+ return this;
+ }
+
+ @Override
+ public OntDisjoint.Classes createDisjointClasses(Collection<OntClass> classes) {
+ checkType(OntDisjoint.Classes.class);
+ return OntDisjointImpl.createDisjointClasses(this, classes.stream());
+ }
+
+ @Override
+ public OntDisjoint.Individuals createDifferentIndividuals(Collection<OntIndividual> individuals) {
+ checkType(OntDisjoint.Individuals.class);
+ return OntDisjointImpl.createDifferentIndividuals(this, individuals.stream());
+ }
+
+ @Override
+ public OntDisjoint.ObjectProperties createDisjointObjectProperties(Collection<OntObjectProperty> properties) {
+ checkType(OntDisjoint.ObjectProperties.class);
+ return OntDisjointImpl.createDisjointObjectProperties(this, properties.stream());
+ }
+
+ @Override
+ public OntDisjoint.DataProperties createDisjointDataProperties(Collection<OntDataProperty> properties) {
+ checkType(OntDisjoint.DataProperties.class);
+ return OntDisjointImpl.createDisjointDataProperties(this, properties.stream());
+ }
+
+ @Override
+ public <T extends OntFacetRestriction> T createFacetRestriction(Class<T> view, Literal literal) {
+ checkType(OntFacetRestriction.class);
+ return OntFacetRestrictionImpl.create(this, view, literal);
+ }
+
+ @Override
+ public OntDataRange.OneOf createDataOneOf(Collection<Literal> values) {
+ checkType(OntDataRange.OneOf.class);
+ return checkCreate(model -> OntDataRangeImpl.createOneOf(model, values.stream()), OntDataRange.OneOf.class);
+ }
+
+ @Override
+ public OntDataRange.Restriction createDataRestriction(OntDataRange.Named datatype, Collection<OntFacetRestriction> values) {
+ checkType(OntDataRange.Restriction.class);
+ return OntDataRangeImpl.createRestriction(this, datatype, values.stream());
+ }
+
+ @Override
+ public OntDataRange.ComplementOf createDataComplementOf(OntDataRange other) {
+ checkType(OntDataRange.ComplementOf.class);
+ return OntDataRangeImpl.createComplementOf(this, other);
+ }
+
+ @Override
+ public OntDataRange.UnionOf createDataUnionOf(Collection<OntDataRange> values) {
+ checkType(OntDataRange.UnionOf.class);
+ return OntDataRangeImpl.createUnionOf(this, values.stream());
+ }
+
+ @Override
+ public OntDataRange.IntersectionOf createDataIntersectionOf(Collection<OntDataRange> values) {
+ checkType(OntDataRange.IntersectionOf.class);
+ return OntDataRangeImpl.createIntersectionOf(this, values.stream());
+ }
+
+ @Override
+ public OntClass.ObjectSomeValuesFrom createObjectSomeValuesFrom(OntObjectProperty property, OntClass ce) {
+ checkType(OntClass.ObjectSomeValuesFrom.class);
+ return checkCreate(model -> OntClassImpl.createComponentRestrictionCE(model,
+ OntClass.ObjectSomeValuesFrom.class, property, ce, OWL.someValuesFrom), OntClass.ObjectSomeValuesFrom.class);
+ }
+
+ @Override
+ public OntClass.DataSomeValuesFrom createDataSomeValuesFrom(OntDataProperty property, OntDataRange dr) {
+ checkType(OntClass.DataSomeValuesFrom.class);
+ return checkCreate(model -> OntClassImpl.createComponentRestrictionCE(model,
+ OntClass.DataSomeValuesFrom.class, property, dr, OWL.someValuesFrom), OntClass.DataSomeValuesFrom.class);
+ }
+
+ @Override
+ public OntClass.ObjectAllValuesFrom createObjectAllValuesFrom(OntObjectProperty property, OntClass ce) {
+ checkType(OntClass.ObjectAllValuesFrom.class);
+ return checkCreate(model -> OntClassImpl.createComponentRestrictionCE(model,
+ OntClass.ObjectAllValuesFrom.class, property, ce, OWL.allValuesFrom), OntClass.ObjectAllValuesFrom.class);
+ }
+
+ @Override
+ public OntClass.DataAllValuesFrom createDataAllValuesFrom(OntDataProperty property, OntDataRange dr) {
+ checkType(OntClass.DataAllValuesFrom.class);
+ return OntClassImpl.createComponentRestrictionCE(this,
+ OntClass.DataAllValuesFrom.class, property, dr, OWL.allValuesFrom);
+ }
+
+ @Override
+ public OntClass.ObjectHasValue createObjectHasValue(OntObjectProperty property, OntIndividual individual) {
+ checkType(OntClass.ObjectHasValue.class);
+ return OntClassImpl.createComponentRestrictionCE(this,
+ OntClass.ObjectHasValue.class, property, individual, OWL.hasValue);
+ }
+
+ @Override
+ public OntClass.DataHasValue createDataHasValue(OntDataProperty property, Literal literal) {
+ checkType(OntClass.DataHasValue.class);
+ return OntClassImpl.createComponentRestrictionCE(this, OntClass.DataHasValue.class, property, literal, OWL.hasValue);
+ }
+
+ @Override
+ public OntClass.ObjectMinCardinality createObjectMinCardinality(OntObjectProperty property, int cardinality, OntClass ce) {
+ checkType(OntClass.ObjectMinCardinality.class);
+ return OntClassImpl.createCardinalityRestrictionCE(this,
+ OntClass.ObjectMinCardinality.class, property, cardinality, ce);
+ }
+
+ @Override
+ public OntClass.DataMinCardinality createDataMinCardinality(OntDataProperty property, int cardinality, OntDataRange dr) {
+ checkType(OntClass.DataMinCardinality.class);
+ return OntClassImpl.createCardinalityRestrictionCE(this,
+ OntClass.DataMinCardinality.class, property, cardinality, dr);
+ }
+
+ @Override
+ public OntClass.ObjectMaxCardinality createObjectMaxCardinality(OntObjectProperty property, int cardinality, OntClass ce) {
+ checkType(OntClass.ObjectMaxCardinality.class);
+ return checkCreate(model -> OntClassImpl.createCardinalityRestrictionCE(model,
+ OntClass.ObjectMaxCardinality.class, property, cardinality, ce), OntClass.ObjectMaxCardinality.class);
+ }
+
+ @Override
+ public OntClass.DataMaxCardinality createDataMaxCardinality(OntDataProperty property, int cardinality, OntDataRange dr) {
+ checkType(OntClass.DataMaxCardinality.class);
+ return checkCreate(model -> OntClassImpl.createCardinalityRestrictionCE(model,
+ OntClass.DataMaxCardinality.class, property, cardinality, dr), OntClass.DataMaxCardinality.class);
+ }
+
+ @Override
+ public OntClass.ObjectCardinality createObjectCardinality(OntObjectProperty property, int cardinality, OntClass ce) {
+ checkType(OntClass.ObjectCardinality.class);
+ return OntClassImpl.createCardinalityRestrictionCE(this,
+ OntClass.ObjectCardinality.class, property, cardinality, ce);
+ }
+
+ @Override
+ public OntClass.DataCardinality createDataCardinality(OntDataProperty property, int cardinality, OntDataRange dr) {
+ checkType(OntClass.DataCardinality.class);
+ return OntClassImpl.createCardinalityRestrictionCE(this, OntClass.DataCardinality.class, property, cardinality, dr);
+ }
+
+ @Override
+ public OntClass.UnionOf createObjectUnionOf(Collection<OntClass> classes) {
+ checkType(OntClass.UnionOf.class);
+ return checkCreate(model ->
+ OntClassImpl.createComponentsCE(model, OntClass.UnionOf.class, OntClass.class, OWL.unionOf, classes.stream()),
+ OntClass.UnionOf.class);
+ }
+
+ @Override
+ public OntClass.IntersectionOf createObjectIntersectionOf(Collection<OntClass> classes) {
+ checkType(OntClass.IntersectionOf.class);
+ return checkCreate(model -> OntClassImpl.createComponentsCE(model,
+ OntClass.IntersectionOf.class, OntClass.class, OWL.intersectionOf, classes.stream()), OntClass.IntersectionOf.class);
+ }
+
+ @Override
+ public OntClass.OneOf createObjectOneOf(Collection<OntIndividual> individuals) {
+ checkType(OntClass.OneOf.class);
+ return checkCreate(model -> OntClassImpl.createComponentsCE(model,
+ OntClass.OneOf.class, OntIndividual.class, OWL.oneOf, individuals.stream()), OntClass.OneOf.class);
+ }
+
+ @Override
+ public OntClass.HasSelf createHasSelf(OntObjectProperty property) {
+ checkType(OntClass.HasSelf.class);
+ return OntClassImpl.createHasSelf(this, property);
+ }
+
+ @Override
+ public OntClass.NaryDataAllValuesFrom createDataAllValuesFrom(Collection<OntDataProperty> properties, OntDataRange dr) {
+ checkType(OntClass.NaryDataAllValuesFrom.class);
+ return OntClassImpl.createNaryRestrictionCE(this, OntClass.NaryDataAllValuesFrom.class, dr, properties);
+ }
+
+ @Override
+ public OntClass.NaryDataSomeValuesFrom createDataSomeValuesFrom(Collection<OntDataProperty> properties, OntDataRange dr) {
+ checkType(OntClass.NaryDataSomeValuesFrom.class);
+ return OntClassImpl.createNaryRestrictionCE(this, OntClass.NaryDataSomeValuesFrom.class, dr, properties);
+ }
+
+ @Override
+ public OntClass.ComplementOf createObjectComplementOf(OntClass ce) {
+ checkType(OntClass.ComplementOf.class);
+ return checkCreate(model -> OntClassImpl.createComplementOf(model, ce), OntClass.ComplementOf.class);
+ }
+
+ @Override
+ public OntSWRL.Variable createSWRLVariable(String uri) {
+ checkType(OntSWRL.Variable.class);
+ return OntSWRLImpl.createVariable(this, uri);
+ }
+
+ @Override
+ public OntSWRL.Atom.WithBuiltin createBuiltInSWRLAtom(Resource predicate, Collection<OntSWRL.DArg> arguments) {
+ checkType(OntSWRL.Atom.WithBuiltin.class);
+ return OntSWRLImpl.createBuiltInAtom(this, predicate, arguments);
+ }
+
+ @Override
+ public OntSWRL.Atom.WithClass createClassSWRLAtom(OntClass clazz, OntSWRL.IArg arg) {
+ checkType(OntSWRL.Atom.WithClass.class);
+ return OntSWRLImpl.createClassAtom(this, clazz, arg);
+ }
+
+ @Override
+ public OntSWRL.Atom.WithDataRange createDataRangeSWRLAtom(OntDataRange range, OntSWRL.DArg arg) {
+ checkType(OntSWRL.Atom.WithDataRange.class);
+ return OntSWRLImpl.createDataRangeAtom(this, range, arg);
+ }
+
+ @Override
+ public OntSWRL.Atom.WithDataProperty createDataPropertySWRLAtom(OntDataProperty dataProperty,
+ OntSWRL.IArg firstArg,
+ OntSWRL.DArg secondArg) {
+ checkType(OntSWRL.Atom.WithDataProperty.class);
+ return OntSWRLImpl.createDataPropertyAtom(this, dataProperty, firstArg, secondArg);
+ }
+
+ @Override
+ public OntSWRL.Atom.WithObjectProperty createObjectPropertySWRLAtom(OntObjectProperty dataProperty,
+ OntSWRL.IArg firstArg,
+ OntSWRL.IArg secondArg) {
+ checkType(OntSWRL.Atom.WithObjectProperty.class);
+ return OntSWRLImpl.createObjectPropertyAtom(this, dataProperty, firstArg, secondArg);
+ }
+
+ @Override
+ public OntSWRL.Atom.WithDifferentIndividuals createDifferentIndividualsSWRLAtom(OntSWRL.IArg firstArg,
+ OntSWRL.IArg secondArg) {
+ checkType(OntSWRL.Atom.WithDifferentIndividuals.class);
+ return OntSWRLImpl.createDifferentIndividualsAtom(this, firstArg, secondArg);
+ }
+
+ @Override
+ public OntSWRL.Atom.WithSameIndividuals createSameIndividualsSWRLAtom(OntSWRL.IArg firstArg,
+ OntSWRL.IArg secondArg) {
+ checkType(OntSWRL.Atom.WithSameIndividuals.class);
+ return OntSWRLImpl.createSameIndividualsAtom(this, firstArg, secondArg);
+ }
+
+ @Override
+ public OntSWRL.Imp createSWRLImp(Collection<OntSWRL.Atom<?>> head,
+ Collection<OntSWRL.Atom<?>> body) {
+ checkType(OntSWRL.Atom.Imp.class);
+ return OntSWRLImpl.createImp(this, head, body);
+ }
+
+ /**
+ * Creates an object of type {@link X} if it is possible;
+ * otherwise throws {@link OntJenaException.Unsupported} exception.
+ *
+ * @param creator {@link Function} to create {@link X}
+ * @param type of {@link X}
+ * @param <X> {@link OntObject}
+ * @return {@link X}
+ * @throws OntJenaException.Unsupported if no possible to create an object
+ */
+ protected <X extends OntObject> X checkCreate(Function<OntGraphModelImpl, X> creator, Class<X> type) {
+ Graph thisGraph = getGraph();
+ Graph bg = GraphMemFactory.createDefaultGraph();
+ UnionGraph ug = new UnionGraphImpl(bg) {
+ @Override
+ protected void addParent(Graph graph) {
+ }
+ };
+ ug.addSubGraph(thisGraph);
+ try {
+ OntGraphModelImpl m = new OntGraphModelImpl(ug, getOntPersonality());
+ X res = creator.apply(m);
+ bg.find().forEach(thisGraph::add);
+ return res.inModel(this).as(type);
+ } catch (OntJenaException.Conversion e) {
+ throw new OntJenaException.Unsupported(
+ "Unable to create object " + OntEnhNodeFactories.viewAsString(type) +
+ "; probably, it is disallowed by profile " + getOntPersonality().getName()
+ );
+ }
+ }
+
+ public RDFDatatype getRDFDatatype(String uri) {
+ return dtTypes.computeIfAbsent(uri, u -> {
+ RDFDatatype res = TypeMapper.getInstance().getTypeByName(u);
+ return res == null ? new BaseDatatype(u) : res;
+ });
+ }
+
+ public PrefixMapping getPrefixMapping() {
+ return getGraph().getPrefixMapping();
+ }
+
+ @Override
+ public OntGraphModelImpl setNsPrefix(String prefix, String uri) {
+ getPrefixMapping().setNsPrefix(prefix, uri);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl removeNsPrefix(String prefix) {
+ getPrefixMapping().removeNsPrefix(prefix);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl clearNsPrefixMap() {
+ getPrefixMapping().clearNsPrefixMap();
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl setNsPrefixes(PrefixMapping pm) {
+ getPrefixMapping().setNsPrefixes(pm);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl setNsPrefixes(Map<String, String> map) {
+ getPrefixMapping().setNsPrefixes(map);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl withDefaultMappings(PrefixMapping other) {
+ getPrefixMapping().withDefaultMappings(other);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl lock() {
+ getPrefixMapping().lock();
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl add(Statement s) {
+ super.add(s);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl remove(Statement s) {
+ super.remove(s);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl add(Resource s, Property p, RDFNode o) {
+ super.add(s, p, o);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl remove(Resource s, Property p, RDFNode o) {
+ super.remove(s, p, o);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl add(Model data) {
+ UnionGraph ug = getUnionGraph();
+ UnionGraph.EventManager em = ug.getEventManager();
+ em.notifyEvent(ug, OntModelEvent.startAddDataGraphEvent(data.getGraph()));
+ getBaseModel().add(data);
+ em.notifyEvent(ug, OntModelEvent.finishAddDataGraphEvent(data.getGraph()));
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl remove(Model data) {
+ UnionGraph ug = getUnionGraph();
+ UnionGraph.EventManager em = ug.getEventManager();
+ em.notifyEvent(ug, OntModelEvent.startDeleteDataGraphEvent(data.getGraph()));
+ getBaseModel().remove(data);
+ em.notifyEvent(ug, OntModelEvent.finishDeleteDataGraphEvent(data.getGraph()));
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl add(StmtIterator iter) {
+ super.add(iter);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl remove(StmtIterator iter) {
+ super.remove(iter);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl add(Statement[] statements) {
+ super.add(statements);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl remove(Statement[] statements) {
+ super.remove(statements);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl add(List<Statement> statements) {
+ super.add(statements);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl remove(List<Statement> statements) {
+ super.remove(statements);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl removeAll(Resource s, Property p, RDFNode o) {
+ super.removeAll(s, p, o);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl removeAll() {
+ super.removeAll();
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl addLiteral(Resource s, Property p, boolean v) {
+ super.addLiteral(s, p, v);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl addLiteral(Resource s, Property p, long v) {
+ super.addLiteral(s, p, v);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl addLiteral(Resource s, Property p, int v) {
+ super.addLiteral(s, p, v);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl addLiteral(Resource s, Property p, char v) {
+ super.addLiteral(s, p, v);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl addLiteral(Resource s, Property p, float v) {
+ super.addLiteral(s, p, v);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl addLiteral(Resource s, Property p, double v) {
+ super.addLiteral(s, p, v);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl addLiteral(Resource s, Property p, Literal o) {
+ super.addLiteral(s, p, o);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl add(Resource s, Property p, String lex) {
+ super.add(s, p, lex);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl add(Resource s, Property p, String lex, RDFDatatype datatype) {
+ super.add(s, p, lex, datatype);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl add(Resource s, Property p, String lex, String lang) {
+ super.add(s, p, lex, lang);
+ return this;
+ }
+
+
+ @Override
+ public OntGraphModelImpl read(String url) {
+ return read(it -> it.read(url));
+ }
+
+ @Override
+ public OntGraphModelImpl read(Reader reader, String base) {
+ return read(it -> it.read(reader, base));
+ }
+
+ @Override
+ public OntGraphModelImpl read(InputStream reader, String base) {
+ return read(it -> it.read(reader, base));
+ }
+
+ @Override
+ public OntGraphModelImpl read(String url, String lang) {
+ return read(it -> it.read(url, lang));
+ }
+
+ @Override
+ public OntGraphModelImpl read(String url, String base, String lang) {
+ return read(it -> it.read(url, base, lang));
+ }
+
+ @Override
+ public OntGraphModelImpl read(Reader reader, String base, String lang) {
+ return read(it -> it.read(reader, base, lang));
+ }
+
+ @Override
+ public OntGraphModelImpl read(InputStream reader, String base, String lang) {
+ return read(it -> it.read(reader, base, lang));
+ }
+
+ private OntGraphModelImpl read(Consumer<Model> reader) {
+ UnionGraph ug = getUnionGraph();
+ UnionGraph.EventManager em = ug.getEventManager();
+ em.notifyEvent(ug, OntModelEvent.startReadDataGraphEvent());
+ reader.accept(getBaseModel());
+ em.notifyEvent(ug, OntModelEvent.finishReadDataGraphEvent());
+ rebind();
+ return this;
+ }
+
+ @SuppressWarnings("deprecation")
+ @Override
+ public OntGraphModelImpl write(Writer writer) {
+ getBaseModel().write(writer);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl write(Writer writer, String lang) {
+ getBaseModel().write(writer, lang);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl write(Writer writer, String lang, String base) {
+ getBaseModel().write(writer, lang, base);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl write(OutputStream out) {
+ getBaseModel().write(out);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl write(OutputStream out, String lang) {
+ getBaseModel().write(out, lang);
+ return this;
+ }
+
+ @Override
+ public OntGraphModelImpl write(OutputStream out, String lang, String base) {
+ getBaseModel().write(out, lang, base);
+ return this;
+ }
+
+ @Override
+ public OntAnnotationProperty getRDFSComment() {
+ return findNodeAs(RDFS.Nodes.comment, OntAnnotationProperty.class);
+ }
+
+ @Override
+ public OntAnnotationProperty getRDFSLabel() {
+ return findNodeAs(RDFS.Nodes.label, OntAnnotationProperty.class);
+ }
+
+ @Override
+ public OntClass.Named getOWLThing() {
+ return findNodeAs(OWL.Thing.asNode(), OntClass.Named.class);
+ }
+
+ @Override
+ public OntDataRange.Named getRDFSLiteral() {
+ return findNodeAs(RDFS.Literal.asNode(), OntDataRange.Named.class);
+ }
+
+ @Override
+ public OntClass.Named getOWLNothing() {
+ return findNodeAs(OWL.Nothing.asNode(), OntClass.Named.class);
+ }
+
+ @Override
+ public OntObjectProperty.Named getOWLTopObjectProperty() {
+ return findNodeAs(OWL.topObjectProperty.asNode(), OntObjectProperty.Named.class);
+ }
+
+ @Override
+ public OntObjectProperty.Named getOWLBottomObjectProperty() {
+ return findNodeAs(OWL.bottomObjectProperty.asNode(), OntObjectProperty.Named.class);
+ }
+
+ @Override
+ public OntDataProperty getOWLTopDataProperty() {
+ return findNodeAs(OWL.topDataProperty.asNode(), OntDataProperty.class);
+ }
+
+ @Override
+ public OntDataProperty getOWLBottomDataProperty() {
+ return findNodeAs(OWL.bottomDataProperty.asNode(), OntDataProperty.class);
+ }
+
+ /**
+ * Returns the {@link Reasoner} which is being used to answer queries to this graph
+ * or {@code null} if reasoner is not supported by the model.
+ */
+ @Override
+ public Reasoner getReasoner() {
+ InfGraph g = getInfGraph();
+ return g != null ? g.getReasoner() : null;
+ }
+
+ /**
+ * Switches on/off derivation logging.
+ * If this option is enabled, then each time a derivation is made, that fact is recorded,
+ * and the resulting record can be accessed through a later call to getDerivation.
+ * This can take up a lot of space!
+ */
+ @Override
+ public void setDerivationLogging(boolean logOn) {
+ InfGraph graph = getInfGraph();
+ if (graph != null) {
+ graph.setDerivationLogging(logOn);
+ }
+ }
+
+ /**
+ * Returns the derivation of the given statement (which should be the result of some previous list operation).
+ * Not all reasoners support derivations.
+ *
+ * @param statement {@link Statement} to get derivation information
+ * @return an iterator over {@code Derivation} records or {@code null} if there is no derivation information
+ * available for this triple
+ * @see Derivation
+ */
+ @Override
+ public Iterator<Derivation> getDerivation(Statement statement) {
+ return (getGraph() instanceof InfGraph) ? ((InfGraph) getGraph()).getDerivation(statement.asTriple()) : null;
+ }
+
+ /**
+ * Returns {@code InfGraph} or {@code null} if no-inf model
+ *
+ * @return {@link InfGraph}
+ */
+ public InfGraph getInfGraph() {
+ return graph instanceof InfGraph ? (InfGraph) graph : null;
+ }
+
+ /**
+ * Causes the inference model to reconsult the underlying data to take into account changes.
+ * Normally, changes are made through the InfModel's, add and remove calls are will be handled appropriately.
+ * However, in some cases, changes are made behind the InfModel's back and
+ * this forces a full reconsult of the changed data.
+ */
+ @Override
+ public void rebind() {
+ InfGraph graph = getInfGraph();
+ if (graph != null) {
+ graph.rebind();
+ }
+ }
+
+ /**
+ * Performs any initial processing and caching.
+ * This call is optional.
+ * Most engines either have negligible set-up work or will perform an implicit "prepare" if necessary.
+ * The call is provided for those occasions where substantial preparation work is possible
+ * (e.g. running a forward chaining rule system)
+ * and where an application might wish greater control over when
+ * this preparation is done rather than just leaving to be done at first query time.
+ */
+ @Override
+ public void prepare() {
+ InfGraph graph = getInfGraph();
+ if (graph != null) {
+ graph.prepare();
+ }
+ }
+
+ /**
+ * Resets any internal caches.
+ * Some systems, such as the tabled backchainer, retain information after each query.
+ * A reset will wipe this information preventing unbounded memory use at the expense of more expensive future queries.
+ * A reset does not cause the raw data to be reconsulted and so is less expensive than a rebinding.
+ */
+ @Override
+ public void reset() {
+ InfGraph graph = getInfGraph();
+ if (graph != null) {
+ graph.reset();
+ }
+ }
+
+ /**
+ * Tests the consistency of the underlying data.
+ * This normally tests the validity of the bound instance data against the bound schema data.
+ *
+ * @return a {@link ValidityReport} structure
+ */
+ @Override
+ public ValidityReport validate() {
+ InfGraph graph = getInfGraph();
+ return graph != null ? graph.validate() : null;
+ }
+
+ /**
+ * Finds all the statements matching a pattern.
+ * Returns an iterator over all the statements in a model that match a pattern.
+ * <p>
+ * The SPO terms may refer to resources which are temporarily defined in the "posit" model.
+ * This allows one, for example, to query what resources are of type CE where CE is a
+ * class expression rather than a named class - put CE in the posit arg.</p>
+ *
+ * @param subject The subject sought
+ * @param predicate The predicate sought
+ * @param object The value sought
+ * @param posit Model containing additional assertions to be considered when matching statements
+ * @return an iterator over the subjects
+ */
+ @Override
+ public StmtIterator listStatements(Resource subject, Property predicate, RDFNode object, Model posit) {
+ InfGraph graph = getInfGraph();
+ if (graph != null) {
+ Graph gp = posit == null ? GraphMemFactory.createGraphMem() : posit.getGraph();
+ Iterator<Triple> iter = graph.find(asNode(subject), asNode(predicate), asNode(object), gp);
+ return IteratorFactory.asStmtIterator(iter, this);
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public InfModel asInferenceModel() {
+ if (getInfGraph() != null) {
+ return this;
+ } else {
+ throw new OntJenaException.Unsupported("No reasoner attached. Inference is not supported");
+ }
+ }
+
+ /**
+ * Returns a derivations model.
+ * The rule reasoners typically create a graph containing those triples added to the base graph due to rule firings.
+ * In some applications, it can be useful to be able to access those deductions directly,
+ * without seeing the raw data which triggered them.
+ * In particular, this allows the forward rules to be used as if they were rewrite transformation rules.
+ *
+ * @return The derivation model, if one is defined, or else {@code null}
+ */
+ @Override
+ public Model getDeductionsModel() {
+ if (deductionsModel == null) {
+ InfGraph infGraph = getInfGraph();
+ if (infGraph != null) {
+ Graph deductionsGraph = infGraph.getDeductionsGraph();
+ if (deductionsGraph != null) {
+ deductionsModel = new ModelCom(deductionsGraph);
+ }
+ }
+ } else {
+ // ensure that the cached model sees the updated changes from the underlying reasoner graph
+ Objects.requireNonNull(getInfGraph()).prepare();
+ }
+ return deductionsModel;
+ }
+
+ /**
+ * Returns the raw RDF model being processed
+ * (i.e. the argument to the {@link Reasoner#bind(Graph)} call that created this {@link InfModel}).
+ */
+ @Override
+ public Model getRawModel() {
+ return getBaseModel();
+ }
+
+ private Model getReasonerCapabilities() {
+ Reasoner reasoner = getReasoner();
+ return reasoner != null ? reasoner.getReasonerCapabilities() : null;
+ }
+
+ /**
+ * Returns a {@link RDFNode} for the given type and, if the result is present, caches it node at the model level.
+ * The method works silently: normally no exception is expected.
+ *
+ * @param node {@link Node}
+ * @param type {@link Class}-type
+ * @param <N> any subtype of {@link RDFNode}
+ * @return {@link RDFNode} or {@code null}
+ * @throws RuntimeException unexpected misconfiguration (RDF recursion, wrong input, personality mismatch, etc.)
+ * @see #getNodeAs(Node, Class)
+ */
+ @Override
+ public <N extends RDFNode> N findNodeAs(Node node, Class<N> type) {
+ try {
+ return getNodeAs(node, type);
+ } catch (OntJenaException.Conversion ignore) {
+ // ignore
+ return null;
+ }
+ }
+
+ /**
+ * Answers an enhanced node that wraps the given node and conforms to the given interface type.
+ * The returned RDF node is cached at the model-level.
+ *
+ * @param node a node (assumed to be in this graph)
+ * @param type a type denoting the enhanced facet desired
+ * @param <N> a subtype of {@link RDFNode}
+ * @return an enhanced node, cannot be {@code null}
+ * @throws OntJenaException unable to construct new RDF view for whatever reason
+ * @throws RuntimeException unexpected misconfiguration (wrong inputs, personality mismatch)
+ */
+ @Override
+ public <N extends RDFNode> N getNodeAs(Node node, Class<N> type) {
+ try {
+ return getNodeAsInternal(node, type);
+ } catch (OntJenaException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new OntJenaException.Conversion(String.format(
+ "Failed to convert node <%s> to <%s>. Profile <%s>",
+ node, OntEnhNodeFactories.viewAsString(type), getOntPersonality().getName()
+ ), e);
+ }
+ }
+
+ /**
+ * Answers an enhanced node that wraps the given node and conforms to the given interface type,
+ * taking into account possible graph recursions.
+ * For internal usage only.
+ *
+ * @param node a node (assumed to be in this graph)
+ * @param type a type denoting the enhanced facet desired
+ * @param <N> a subtype of {@link RDFNode}
+ * @return an enhanced node or {@code null} if no match found
+ * @throws OntJenaException.Recursion if a graph recursion is detected
+ * @throws RuntimeException unexpected misconfiguration
+ * @see #getNodeAs(Node, Class)
+ */
+ @Override
+ public <N extends RDFNode> N safeFindNodeAs(Node node, Class<N> type) {
+ Set<Node> nodes = visited.get();
+ try {
+ if (nodes.add(node)) {
+ return getNodeAsInternal(node, type);
+ }
+ throw new OntJenaException.Recursion("Can't cast to " + OntEnhNodeFactories.viewAsString(type) + ": " +
+ "graph contains a recursion for node <" + node + ">");
+ } catch (OntJenaException.Conversion | PersonalityConfigException r) {
+ return null;
+ } finally {
+ nodes.remove(node);
+ }
+ }
+
+ /**
+ * Answers an enhanced node that wraps the given node and conforms to the given interface type.
+ * The returned RDF node is cached at the model-level.
+ *
+ * @param node a node (assumed to be in this graph)
+ * @param type a type denoting the enhanced facet desired
+ * @param <N> a subtype of {@link RDFNode}
+ * @return an enhanced node
+ * @throws org.apache.jena.enhanced.PersonalityConfigException if personality is misconfigured
+ * or the given {@code type} is absent in it;
+ * normally this should not happen
+ * @throws NullPointerException if any input is {@code null}
+ * @throws JenaException unable to construct a new RDF view
+ */
+ protected <N extends RDFNode> N getNodeAsInternal(Node node, Class<N> type) {
+ return super.getNodeAs(Objects.requireNonNull(node, "Null node"),
+ Objects.requireNonNull(type, "Null class view."));
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/OntModelEvent.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/OntModelEvent.java
new file mode 100644
index 0000000000..9c8d4baef1
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/OntModelEvent.java
@@ -0,0 +1,93 @@
+/*
+ * 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.jena.ontapi.impl;
+
+import org.apache.jena.graph.Graph;
+import org.apache.jena.graph.GraphEvents;
+import org.apache.jena.ontapi.model.OntModel;
+
+import java.util.Objects;
+
+/**
+ * Events that called on {@link OntModel}'s level.
+ */
+public class OntModelEvent extends GraphEvents {
+ public static final String START_CHANGE_ID = "startChangeID";
+ public static final String FINISH_CHANGE_ID = "endChangeID";
+ public static final String START_ADD_DATA_GRAPH = "startAddDataGraph";
+ public static final String START_DELETE_DATA_GRAPH = "startDeleteDataGraph";
+ public static final String FINISH_ADD_DATA_GRAPH = "finishAddDataGraph";
+ public static final String FINISH_DELETE_DATA_GRAPH = "finishDeleteDataGraph";
+ public static final String START_READ_DATA_GRAPH = "startReadDataGraph";
+ public static final String FINISH_READ_DATA_GRAPH = "endReadDataGraph";
+
+ private final String type;
+
+ public OntModelEvent(String title, Object content) {
+ super(title, content);
+ this.type = title;
+ }
+
+ public static boolean isEventOfType(Object any, String type) {
+ if (any instanceof OntModelEvent) {
+ return Objects.equals(((OntModelEvent) any).type, type);
+ }
+ if (any instanceof GraphEvents) {
+ if (any == startRead && START_READ_DATA_GRAPH.equals(type)) {
+ return true;
+ }
+ if (any == finishRead && FINISH_READ_DATA_GRAPH.equals(type)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public static OntModelEvent startChangeIDEvent() {
+ return new OntModelEvent(START_CHANGE_ID, "CHANGE-ID");
+ }
+
+ public static OntModelEvent finishChangeIDEvent() {
+ return new OntModelEvent(FINISH_CHANGE_ID, "CHANGE-ID");
+ }
+
+ public static OntModelEvent startAddDataGraphEvent(Graph graph) {
+ return new OntModelEvent(START_ADD_DATA_GRAPH, graph);
+ }
+
+ public static OntModelEvent finishAddDataGraphEvent(Graph graph) {
+ return new OntModelEvent(FINISH_ADD_DATA_GRAPH, graph);
+ }
+
+ public static OntModelEvent startDeleteDataGraphEvent(Graph graph) {
+ return new OntModelEvent(START_DELETE_DATA_GRAPH, graph);
+ }
+
+ public static OntModelEvent finishDeleteDataGraphEvent(Graph graph) {
+ return new OntModelEvent(FINISH_DELETE_DATA_GRAPH, graph);
+ }
+
+ public static GraphEvents startReadDataGraphEvent() {
+ return startRead;
+ }
+
+ public static GraphEvents finishReadDataGraphEvent() {
+ return finishRead;
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/UnionGraphImpl.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/UnionGraphImpl.java
new file mode 100644
index 0000000000..24cbe1cd3a
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/UnionGraphImpl.java
@@ -0,0 +1,661 @@
+/*
+ * 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.jena.ontapi.impl;
+
+import org.apache.jena.ontapi.UnionGraph;
+import org.apache.jena.ontapi.utils.Graphs;
+import org.apache.jena.ontapi.utils.Iterators;
+import org.apache.jena.graph.Graph;
+import org.apache.jena.graph.GraphEventManager;
+import org.apache.jena.graph.GraphEvents;
+import org.apache.jena.graph.GraphListener;
+import org.apache.jena.graph.Node;
+import org.apache.jena.graph.Triple;
+import org.apache.jena.graph.compose.CompositionBase;
+import org.apache.jena.graph.impl.SimpleEventManager;
+import org.apache.jena.shared.PrefixMapping;
+import org.apache.jena.util.iterator.ExtendedIterator;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.WeakHashMap;
+import java.util.stream.Stream;
+
+/**
+ * UnionGraph.
+ * <p>
+ * It consists of two parts: a {@link #base base graph} and an {@link UnionGraphImpl.SubGraphs sub-graphs} collection.
+ * Unlike {@link org.apache.jena.graph.compose.MultiUnion MultiUnion} this implementation explicitly requires primary (base) graph.
+ * Underlying sub-graphs are only used for searching; modify operations are performed only on the base graph.
+ * This graph allows building graph hierarchy which can be used to link different models.
+ * Also, it allows recursion, that is, it can contain itself somewhere in the hierarchy.
+ * The {@link PrefixMapping} of this graph is taken from the base graph,
+ * and, therefore, any changes in it reflect both the base and this graph.
+ */
+@SuppressWarnings({"WeakerAccess"})
+public class UnionGraphImpl extends CompositionBase implements UnionGraph {
+
+ protected final Graph base;
+ protected final SubGraphs subGraphs;
+ protected final boolean distinct;
+
+ /**
+ * A set of parents, used when collecting cache {@link #descendantBases},
+ * which is used in read operations.
+ * This allows the {@code UnionGraphImpl} instance
+ * to know when the structure has changed to rebuild the cache.
+ * Items of this {@code Set} are removed automatically by GC
+ * if there are no more strong references (a graph/model is removed, i.e. there is no usage anymore).
+ */
+ protected final Set<UnionGraphImpl> parents = Collections.newSetFromMap(new WeakHashMap<>());
+ /**
+ * Internal cache to hold all data graphs with except of {@link #base},
+ * used while {@link Graph#find(Triple) #find(..)}.
+ * This {@code Set} cannot contain {@link UnionGraph}s.
+ */
+ protected Set<Graph> descendantBases;
+
+ /**
+ * Creates an instance with default settings.
+ * <p>
+ * Note: it results a distinct graph (i.e. its parameter {@link #distinct} is {@code true}).
+ * This means that the method {@link #find(Triple)} does not produce duplicates.
+ * The additional duplicate checking may lead to temporary writing
+ * the whole graph or some its part into memory in the form of {@code Set},
+ * and for huge ontologies it is unacceptable.
+ * This checking is not performed if the graph is single (the underlying part is empty).
+ * <p>
+ * Also notice, a top-level ontology view of in-memory graph is not sensitive to the distinct parameter
+ * since it uses only base graphs to collect axiomatic data.
+ *
+ * @param base {@link Graph}, not {@code null}
+ */
+ public UnionGraphImpl(Graph base) {
+ this(base, true);
+ }
+
+ /**
+ * Creates a graph for the given {@code base},
+ * which will be either distinct or non-distinct, depending on the second parameter.
+ * Other settings are default.
+ *
+ * @param base {@link Graph}, not {@code null}
+ * @param distinct if {@code true} a distinct graph is created
+ */
+ public UnionGraphImpl(Graph base, boolean distinct) {
+ this(base, new EventManagerImpl(), distinct);
+ }
+
+ /**
+ * Creates a graph for the given {@code base}.
+ *
+ * @param base {@link Graph}, not {@code null}
+ * @param eventManager {@link EventManager} or {@code null} to use default fresh event manager
+ * @param distinct if {@code true} a distinct graph is created
+ */
+ public UnionGraphImpl(Graph base, EventManager eventManager, boolean distinct) {
+ this(base, new SubGraphs(), eventManager, distinct);
+ }
+
+ /**
+ * The base constructor.
+ * A well-formed ontology {@link UnionGraph} is expected to
+ * have a plain (non-union) graph as a {@link #getBaseGraph() root}
+ * and {@code UnionGraph} as {@link #getSubGraphs() leaves}.
+ *
+ * @param base {@link Graph}, not {@code null}
+ * @param subGraphs {@link SubGraphs} or {@code null} to use default empty sub-graph container
+ * @param eventManager {@link EventManager} or {@code null} to use default fresh event manager
+ * @param distinct if {@code true}, the method {@link #find(Triple)} returns an iterator avoiding duplicates
+ * @throws NullPointerException if base graph is {@code null}
+ */
+ protected UnionGraphImpl(Graph base, SubGraphs subGraphs, EventManager eventManager, boolean distinct) {
+ this.base = Objects.requireNonNull(base, "Null base graph.");
+ this.subGraphs = Objects.requireNonNull(subGraphs, "Null SubGraphs");
+ this.gem = Objects.requireNonNull(eventManager, "Null EventManager");
+ this.distinct = distinct;
+ }
+
+ @Override
+ public PrefixMapping getPrefixMapping() {
+ return getBaseGraph().getPrefixMapping();
+ }
+
+ /**
+ * Answers the ont event manager for this graph.
+ * Override to use in {@link org.apache.jena.graph.impl.GraphBase#add(Triple)}.
+ *
+ * @return {@link GraphEventManager}, not {@code null}
+ */
+ @Override
+ public EventManager getEventManager() {
+ return (EventManager) gem;
+ }
+
+ /**
+ * Answers {@code true} iff this graph is distinct.
+ * See {@link #UnionGraphImpl(Graph)} description.
+ *
+ * @return boolean
+ */
+ @Override
+ public boolean isDistinct() {
+ return distinct;
+ }
+
+ /**
+ * Returns the base (primary) graph.
+ *
+ * @return {@link Graph}, not {@code null}
+ */
+ @Override
+ public Graph getBaseGraph() {
+ return base;
+ }
+
+ /**
+ * Returns the underlying graph, possible empty.
+ *
+ * @return {@link SubGraphs}, not {@code null}
+ */
+ public SubGraphs getSubGraphs() {
+ return subGraphs;
+ }
+
+ @Override
+ public boolean hasSubGraph() {
+ return !getSubGraphs().isEmpty();
+ }
+
+ @Override
+ public Stream<Graph> subGraphs() {
+ return getSubGraphs().graphs();
+ }
+
+ @Override
+ public Stream<UnionGraph> superGraphs() {
+ return parents.stream().map(it -> it);
+ }
+
+ @Override
+ public void performAdd(Triple t) {
+ getEventManager().onAddTriple(this, t);
+ if (!subGraphs.contains(t)) {
+ base.add(t);
+ }
+ }
+
+ @Override
+ public void performDelete(Triple t) {
+ getEventManager().onDeleteTriple(this, t);
+ base.delete(t);
+ }
+
+ @Override
+ public void remove(Node s, Node p, Node o) {
+ checkOpen();
+ Triple t = Triple.createMatch(s, p, o);
+ UnionGraph.EventManager em = getEventManager();
+ em.onDeleteTriple(this, t);
+ super.remove(s, p, o);
+ em.notifyEvent(this, GraphEvents.remove(s, p, o));
+ }
+
+ @Override
+ public void clear() {
+ checkOpen();
+ UnionGraph.EventManager em = getEventManager();
+ em.onClear(this);
+ base.clear();
+ em.notifyEvent(this, GraphEvents.removeAll);
+ }
+
+ /**
+ * Adds the specified graph to the underlying graph collection.
+ * Note: for a well-formed ontological {@code UnionGraph}
+ * the input {@code graph} must be also a {@code UnionGraph}, even it has no hierarchy structure.
+ *
+ * @param graph {@link Graph}, not {@code null}
+ * @return this instance
+ */
+ @Override
+ public UnionGraph addSubGraph(Graph graph) {
+ Objects.requireNonNull(graph);
+ checkOpen();
+ EventManager eventManager = getEventManager();
+ eventManager.onAddSubGraph(this, graph);
+ getSubGraphs().add(graph);
+ addParent(graph);
+ resetGraphsCache();
+ eventManager.notifySubGraphAdded(this, graph);
+ if (graph instanceof UnionGraph subGraph) {
+ subGraph.getEventManager().notifySuperGraphAdded(subGraph, this);
+ }
+ return this;
+ }
+
+ protected void addParent(Graph graph) {
+ if (!(graph instanceof UnionGraphImpl)) {
+ return;
+ }
+ ((UnionGraphImpl) graph).parents.add(this);
+ }
+
+ /**
+ * Removes the specified graph from the underlying graph collection.
+ *
+ * @param graph {@link Graph}, not {@code null}
+ * @return this instance
+ */
+ @Override
+ public UnionGraph removeSubGraph(Graph graph) {
+ Objects.requireNonNull(graph);
+ checkOpen();
+ EventManager eventManager = getEventManager();
+ eventManager.onRemoveSubGraph(this, graph);
+ getSubGraphs().remove(graph);
+ removeUnion(graph);
+ resetGraphsCache();
+ eventManager.notifySubGraphRemoved(this, graph);
+ return this;
+ }
+
+ protected void removeUnion(Graph graph) {
+ if (!(graph instanceof UnionGraphImpl)) {
+ return;
+ }
+ ((UnionGraphImpl) graph).parents.remove(this);
+ }
+
+ /**
+ * Clears the {@link #descendantBases cache}.
+ */
+ protected void resetGraphsCache() {
+ getAllLinkedUnionGraphs().forEach(x -> x.descendantBases = null);
+ }
+
+ /**
+ * Lists all indivisible (base) data {@code Graph}s
+ * that are encapsulated either in the hierarchy
+ * or (which is possible) inside the {@link #getBaseGraph() base} (root) graph itself.
+ *
+ * @return <b>distinct</b> {@link ExtendedIterator} of {@link Graph}s, including the base graph
+ * @see UnionGraph#getBaseGraph()
+ */
+ public ExtendedIterator<Graph> listSubGraphBases() {
+ return Iterators.create(descendantBases == null ? descendantBases = getAllBaseGraphs() : descendantBases);
+ }
+
+ /**
+ * Performs the find operation.
+ * Override {@code graphBaseFind} to return an iterator that will report when a deletion occurs.
+ *
+ * @param m {@link Triple} the matcher to match against, not {@code null}
+ * @return an {@link ExtendedIterator iterator} of all triples matching {@code m} in the union of the graphs
+ * @see org.apache.jena.graph.compose.MultiUnion#graphBaseFind(Triple)
+ */
+ @Override
+ protected final ExtendedIterator<Triple> graphBaseFind(Triple m) {
+ return SimpleEventManager.notifyingRemove(this, createFindIterator(m));
+ }
+
+ /**
+ * Answers {@code true} if the graph contains any triple matching {@code t}.
+ *
+ * @param t {@link Triple}, not {@code null}
+ * @return boolean
+ * @see org.apache.jena.graph.compose.MultiUnion#graphBaseContains(Triple)
+ */
+ @Override
+ public boolean graphBaseContains(Triple t) {
+ if (base.contains(t)) {
+ return true;
+ }
+ if (subGraphs.isEmpty()) {
+ return false;
+ }
+ Iterator<Graph> graphs = listSubGraphBases();
+ while (graphs.hasNext()) {
+ Graph g = graphs.next();
+ if (g == base) {
+ continue;
+ }
+ if (g.contains(t)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public int graphBaseSize() {
+ if (subGraphs.isEmpty()) {
+ return base.size();
+ }
+ return super.graphBaseSize();
+ }
+
+ @Override
+ public boolean isEmpty() {
+ if (subGraphs.isEmpty()) {
+ return base.isEmpty();
+ }
+ return Iterators.findFirst(find()).isEmpty();
+ }
+
+ /**
+ * Creates an extended iterator to be used in {@link Graph#find(Triple)}.
+ *
+ * @param m {@link Triple} pattern, not {@code null}
+ * @return {@link ExtendedIterator} of {@link Triple}s
+ * @see org.apache.jena.graph.compose.Union#_graphBaseFind(Triple)
+ * @see org.apache.jena.graph.compose.MultiUnion#multiGraphFind(Triple)
+ */
+ @SuppressWarnings("JavadocReference")
+ protected ExtendedIterator<Triple> createFindIterator(Triple m) {
+ if (subGraphs.isEmpty()) {
+ return base.find(m);
+ }
+ if (!distinct) {
+ return Iterators.flatMap(listSubGraphBases(), x -> x.find(m));
+ }
+ Set<Triple> seen = createSet();
+ return Iterators.flatMap(listSubGraphBases(), x -> CompositionBase.recording(rejecting(x.find(m), seen), seen));
+ }
+
+ /**
+ * Creates a {@code Set} to be used while {@link Graph#find()}.
+ * The returned set may contain a huge number of items.
+ * And that's why this method has protected access -
+ * implementations are allowed to override it for better performance.
+ *
+ * @return Set of {@link Triple}s
+ */
+ protected Set<Triple> createSet() {
+ return new HashSet<>();
+ }
+
+ /**
+ * Closes the graph including all related graphs.
+ * Caution: this is an irreversible operation,
+ * once closed, a graph cannot be reopened.
+ */
+ @Override
+ public void close() {
+ listSubGraphBases().forEachRemaining(Graph::close);
+ getAllUnderlyingUnionGraphs().forEach(x -> x.closed = true);
+ }
+
+ /**
+ * Generic dependsOn, returns {@code true} iff this graph or any sub-graphs depend on the specified graph.
+ *
+ * @param other {@link Graph}
+ * @return boolean
+ */
+ @Override
+ public boolean dependsOn(Graph other) {
+ return (other instanceof UnionGraphImpl && getAllUnderlyingUnionGraphs().contains(other))
+ || Iterators.anyMatch(listSubGraphBases(), x -> Graphs.dependsOn(x, other));
+ }
+
+ /**
+ * Calculates and returns a {@code Set} of all indivisible {@link Graph graph}s
+ * that are placed somewhere lower in the hierarchy.
+ * The method also includes in consideration a rare possibility
+ * when the {@link #getBaseGraph() base} graph is also an {@code UnionGraph}.
+ * The primary indivisible part of the base graph (which is usually a base graph itself)
+ * is added to the beginning of the returned collection.
+ *
+ * @return a {@code Set} (ordered) of {@link Graph}s
+ */
+ protected Set<Graph> getAllBaseGraphs() {
+ Set<Graph> res = new LinkedHashSet<>();
+ Set<UnionGraphImpl> visited = new HashSet<>();
+ Deque<Graph> queue = new ArrayDeque<>();
+ queue.add(this);
+ while (!queue.isEmpty()) {
+ Graph next = queue.removeFirst();
+ if (next instanceof UnionGraphImpl u) {
+ if (visited.add(u)) {
+ queue.add(u.base);
+ queue.addAll(u.subGraphs.graphs);
+ }
+ } else {
+ res.add(next);
+ }
+ }
+ return res;
+ }
+
+ /**
+ * Recursively collects a {@code Set} of all {@link UnionGraph UnionGraph}s
+ * that are related to this instance somehow,
+ * i.e. are present in the hierarchy lower or higher.
+ * This union graph instance is also included in the returned {@code Set}.
+ *
+ * @return Set of {@link UnionGraph}s
+ */
+ protected Set<UnionGraphImpl> getAllLinkedUnionGraphs() {
+ Set<UnionGraphImpl> res = new LinkedHashSet<>();
+ Deque<UnionGraphImpl> queue = new ArrayDeque<>();
+ queue.add(this);
+ while (!queue.isEmpty()) {
+ UnionGraphImpl next = queue.removeFirst();
+ if (res.add(next)) {
+ next.parents.stream().filter(res::add).forEach(queue::add);
+ next.getAllUnderlyingUnionGraphs().stream().filter(res::add).forEach(queue::add);
+ }
+ }
+ return res;
+ }
+
+ /**
+ * Recursively collects all {@link UnionGraph}s that underlies this instance, inclusive.
+ *
+ * @return Set of {@link UnionGraph}s
+ */
+ protected Set<UnionGraphImpl> getAllUnderlyingUnionGraphs() {
+ Set<UnionGraphImpl> res = new LinkedHashSet<>();
+ Deque<UnionGraphImpl> queue = new ArrayDeque<>();
+ queue.add(this);
+ while (!queue.isEmpty()) {
+ UnionGraphImpl next = queue.removeFirst();
+ if (res.add(next)) {
+ next.unionSubGraphs().forEach(queue::add);
+ }
+ }
+ return res;
+ }
+
+ private Stream<UnionGraphImpl> unionSubGraphs() {
+ return getSubGraphs().graphs()
+ .filter(g -> g instanceof UnionGraphImpl)
+ .map(u -> (UnionGraphImpl) u);
+ }
+
+ @Override
+ public String toString() {
+ // do not print the whole graph since it is expensive
+ return "UnionGraph{@" + hashCode() + "}";
+ }
+
+ /**
+ * A container to hold all sub-graphs, that make up the hierarchy.
+ * Such a representation of sub-graphs collection in the form of separate class allows
+ * sharing its instance among different {@code UnionGraph} instances
+ * to impart whole hierarchy structure when it is needed.
+ */
+ public static class SubGraphs {
+ protected final Collection<Graph> graphs;
+
+ protected SubGraphs() {
+ this(new ArrayList<>());
+ }
+
+ protected SubGraphs(Collection<Graph> graphs) {
+ this.graphs = Objects.requireNonNull(graphs);
+ }
+
+ /**
+ * Lists all sub-graphs.
+ *
+ * @return {@link ExtendedIterator} of sub-{@link Graph graph}s
+ */
+ public ExtendedIterator<Graph> listGraphs() {
+ return Iterators.create(graphs);
+ }
+
+ /**
+ * Lists all sub-graphs.
+ *
+ * @return {@code Stream} of sub-{@link Graph graph}s
+ */
+ public Stream<Graph> graphs() {
+ return graphs.stream();
+ }
+
+ /**
+ * Answers {@code true} iff this container is empty.
+ *
+ * @return boolean
+ */
+ public boolean isEmpty() {
+ return graphs.isEmpty();
+ }
+
+ /**
+ * Removes the given graph from the underlying collection.
+ * Maybe overridden to produce corresponding event.
+ *
+ * @param graph {@link Graph}
+ */
+ public void remove(Graph graph) {
+ graphs.remove(graph);
+ }
+
+ /**
+ * Adds the given graph into the underlying collection.
+ * Maybe overridden to produce corresponding event.
+ *
+ * @param graph {@link Graph}
+ */
+ public void add(Graph graph) {
+ graphs.add(Objects.requireNonNull(graph));
+ }
+
+ /**
+ * Tests if the given triple belongs to any of the sub-graphs.
+ *
+ * @param t {@link Triple} to test
+ * @return boolean
+ * @see Graph#contains(Triple)
+ */
+ protected boolean contains(Triple t) {
+ if (graphs.isEmpty()) {
+ return false;
+ }
+ for (Graph g : graphs) {
+ if (g.contains(t)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ /**
+ * An extended {@link org.apache.jena.graph.GraphEventManager Jena Graph Event Manager},
+ * a holder for {@link org.apache.jena.graph.GraphListener}s.
+ */
+ public static class EventManagerImpl extends SimpleEventManager implements EventManager {
+
+ private final List<GraphListener> inactive = new ArrayList<>();
+
+ @Override
+ public void onAddTriple(UnionGraph graph, Triple triple) {
+ listeners(Listener.class).forEach(it -> it.onAddTriple(graph, triple));
+ }
+
+ @Override
+ public void onDeleteTriple(UnionGraph graph, Triple triple) {
+ listeners(Listener.class).forEach(it -> it.onDeleteTriple(graph, triple));
+ }
+
+ @Override
+ public void onAddSubGraph(UnionGraph graph, Graph subGraph) {
+ listeners(Listener.class).forEach(it -> it.onAddSubGraph(graph, subGraph));
+ }
+
+ @Override
+ public void onClear(UnionGraph graph) {
+ listeners(Listener.class).forEach(it -> it.onClear(graph));
+ }
+
+ @Override
+ public void notifySubGraphAdded(UnionGraph graph, Graph subGraph) {
+ listeners(Listener.class).forEach(it -> it.notifySubGraphAdded(graph, subGraph));
+ }
+
+ @Override
+ public void notifySuperGraphAdded(UnionGraph graph, UnionGraph superGraph) {
+ listeners(Listener.class).forEach(it -> it.notifySuperGraphAdded(graph, superGraph));
+ }
+
+ @Override
+ public void onRemoveSubGraph(UnionGraph graph, Graph subGraph) {
+ listeners(Listener.class).forEach(it -> it.onRemoveSubGraph(graph, subGraph));
+ }
+
+ @Override
+ public void notifySubGraphRemoved(UnionGraph graph, Graph subGraph) {
+ listeners(Listener.class).forEach(it -> it.notifySubGraphRemoved(graph, subGraph));
+ }
+
+ @Override
+ public void off() {
+ inactive.addAll(listeners);
+ listeners.clear();
+ }
+
+ @Override
+ public void on() {
+ listeners.addAll(inactive);
+ inactive.clear();
+ }
+
+ /**
+ * Lists all encapsulated listeners.
+ *
+ * @return Stream of {@link GraphListener}s
+ */
+ @Override
+ public Stream<GraphListener> listeners() {
+ return listeners.stream();
+ }
+ }
+}
diff --git a/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/factories/OWL1ObjectFactories.java b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/factories/OWL1ObjectFactories.java
new file mode 100644
index 0000000000..241b12d101
--- /dev/null
+++ b/jena-ontapi/src/main/java/org/apache/jena/ontapi/impl/factories/OWL1ObjectFactories.java
@@ -0,0 +1,398 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.jena.ontapi.impl.factories;
+
+import org.apache.jena.ontapi.common.EnhNodeFactory;
+import org.apache.jena.ontapi.common.EnhNodeFilter;
+import org.apache.jena.ontapi.common.EnhNodeFinder;
+import org.apache.jena.ontapi.common.OntConfig;
+import org.apache.jena.ontapi.common.OntEnhGraph;
+import org.apache.jena.ontapi.common.OntEnhNodeFactories;
+import org.apache.jena.ontapi.impl.objects.OntClassImpl;
+import org.apache.jena.ontapi.impl.objects.OntDataRangeImpl;
+import org.apache.jena.ontapi.impl.objects.OntIDImpl;
+import org.apache.jena.ontapi.impl.objects.OntIndividualImpl;
+import org.apache.jena.ontapi.impl.objects.OntObjectImpl;
+import org.apache.jena.ontapi.model.OntClass;
+import org.apache.jena.ontapi.model.OntIndividual;
+import org.apache.jena.ontapi.utils.Iterators;
+import org.apache.jena.ontapi.vocabulary.OWL;
+import org.apache.jena.ontapi.vocabulary.RDF;
+import org.apache.jena.enhanced.EnhGraph;
+import org.apache.jena.graph.Node;
+import org.apache.jena.graph.Triple;
+import org.apache.jena.rdf.model.RDFList;
+import org.apache.jena.util.iterator.ExtendedIterator;
+
+import java.util.function.Function;
+
+public class OWL1ObjectFactories {
+
+ public static final EnhNodeFactory ANY_OBJECT = OntEnhNodeFactories.createCommon(
+ OntObjectImpl.class,
+ EnhNodeFinder.ANY_SUBJECT,
+ EnhNodeFilter.URI.or(EnhNodeFilter.ANON)
+ );
+ public static final EnhNodeFactory ID = OntEnhNodeFactories.createCommon(
... 58797 lines suppressed ...