org.apache.jena.vocabulary.OWL Java Examples

The following examples show how to use org.apache.jena.vocabulary.OWL. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void writeImports(IndentedWriter out, Resource ontology) {
	List<Resource> imports = JenaUtil.getResourceProperties(ontology, OWL.imports);
	Collections.sort(imports, new Comparator<Resource>() {
		@Override
		public int compare(Resource o1, Resource o2) {
			return o1.getURI().compareTo(o2.getURI());
		}
		
	});
	if(!imports.isEmpty()) {
		for(Resource imp : imports) {
			out.println("IMPORTS <" + imp.getURI() + ">");
		}
		out.println();
	}
}
 
Example #2
Source File: SHACLCTestRunner.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void runFile(File compactFile) {
	try {
		Model compactModel = JenaUtil.createMemoryModel();
		compactModel.read(new FileReader(compactFile), "urn:x-base:default", SHACLC.langName);
		compactModel.removeAll(null, OWL.imports, ResourceFactory.createResource(DASH.BASE_URI));

		File turtleFile = new File(compactFile.getParentFile(), compactFile.getName().replaceAll(".shaclc", ".ttl"));
		Model turtleModel = JenaUtil.createMemoryModel();
		turtleModel.read(new FileReader(turtleFile), "urn:x-base:default", FileUtils.langTurtle);
		
		if(compactModel.getGraph().isIsomorphicWith(turtleModel.getGraph())) {
			System.out.println("Passed test " + compactFile);
		}
		else {
			System.err.println("Failed test " + compactFile);
			System.err.println("Turtle:  " + ModelPrinter.get().print(turtleModel));
			System.err.println("Compact: " + ModelPrinter.get().print(compactModel));
		}
	}
	catch(Exception ex) {
		System.err.println("Exception during test " + compactFile + ": " + ex);
		ex.printStackTrace();
	}
}
 
Example #3
Source File: RdfStreamReaderDatasetTest.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    Model defaultModel = ModelFactory.createDefaultModel();
    defaultModel.add(
            ResourceFactory.createResource("http://rdfunit.aksw.org"),
            OWL.sameAs,
            ResourceFactory.createResource("http://dbpedia.org/resource/Cool")
    );

    Model namedModel = ModelFactory.createDefaultModel();
    namedModel.add(
            ResourceFactory.createResource("http://rdfunit.aksw.org"),
            OWL.sameAs,
            ResourceFactory.createResource("http://dbpedia.org/resource/Super")
    );
    dataset = DatasetFactory.create(defaultModel);

    dataset.addNamedModel("http://rdfunit.aksw.org", namedModel);
}
 
Example #4
Source File: PrefixUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
private static String getImportedNamespace(Resource ontology, String prefix, Set<Resource> reached) {
	reached.add(ontology);
	
	for(Resource imp : JenaUtil.getResourceProperties(ontology, OWL.imports)) {
		if(!reached.contains(imp)) {
			String ns = getNamespace(imp, prefix);
			if(ns == null) {
				ns = getImportedNamespace(imp, prefix, reached);
			}
			if(ns != null) {
				return ns;
			}
		}
	}
	
	return null;
}
 
Example #5
Source File: SHACLUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
private static void addIncludes(Graph model, String uri, Set<Graph> graphs, Set<String> reachedURIs) {
	
	graphs.add(model);
	reachedURIs.add(uri);
	
	for(Triple t : model.find(null, OWL.imports.asNode(), null).toList()) {
		if(t.getObject().isURI()) {
			String includeURI = t.getObject().getURI();
			if(!reachedURIs.contains(includeURI)) {
				Model includeModel = ARQFactory.getNamedModel(includeURI);
				if(includeModel != null) {
					Graph includeGraph = includeModel.getGraph();
					addIncludes(includeGraph, includeURI, graphs, reachedURIs);
				}
			}
		}
	}
}
 
Example #6
Source File: TestDASHTestCases.java    From shacl with Apache License 2.0 6 votes vote down vote up
private static void collectTestCases(File folder, List<TestCase> testCases) throws Exception {
	for(File f : folder.listFiles()) {
		if(f.isDirectory()) {
			collectTestCases(f, testCases);
		}
		else if(f.isFile() && f.getName().endsWith(".ttl")) {
			Model testModel = JenaUtil.createDefaultModel();
			InputStream is = new FileInputStream(f);
			testModel.read(is, "urn:dummy", FileUtils.langTurtle);
			testModel.add(SHACLSystemModel.getSHACLModel());
			Resource ontology = testModel.listStatements(null, OWL.imports, ResourceFactory.createResource(DASH.BASE_URI)).next().getSubject();
			for(TestCaseType type : TestCaseTypes.getTypes()) {
				testCases.addAll(type.getTestCases(testModel, ontology));
			}
		}
	}
}
 
Example #7
Source File: PizzaSparqlNoInf.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public void run() {
    OntModel m = getModel();
    loadData( m );
    String prefix = "prefix pizza: <" + PIZZA_NS + ">\n" +
                    "prefix rdfs: <" + RDFS.getURI() + ">\n" +
                    "prefix owl: <" + OWL.getURI() + ">\n";


    showQuery( m,
               prefix +
               "select ?pizza where {?pizza a owl:Class ; " +
               "                            rdfs:subClassOf ?restriction.\n" +
               "                     ?restriction owl:onProperty pizza:hasTopping ;" +
               "                            owl:someValuesFrom pizza:PeperoniSausageTopping" +
               "}" );
}
 
Example #8
Source File: ClassHierarchyLoader.java    From gerbil with GNU Affero General Public License v3.0 6 votes vote down vote up
protected Set<Resource> getClasses(Model readModel) {
    ResIterator iterator = readModel.listSubjectsWithProperty(RDF.type, RDFS.Class);
    Resource r;
    Set<Resource> classes = new HashSet<Resource>();
    while (iterator.hasNext()) {
        r = iterator.next();
        if (!r.isAnon()) {
            classes.add(r);
        }
    }
    iterator = readModel.listSubjectsWithProperty(RDF.type, OWL.Class);
    while (iterator.hasNext()) {
        r = iterator.next();
        if (!r.isAnon()) {
            classes.add(r);
        }
    }
    return classes;
}
 
Example #9
Source File: SimpleSubClassInferencerTest.java    From gerbil with GNU Affero General Public License v3.0 6 votes vote down vote up
private static Model createModel() {
    Model classModel = ModelFactory.createDefaultModel();
    Resource A = classModel.createResource("http://example.org/A");
    Resource B = classModel.createResource("http://example.org/B");
    Resource C = classModel.createResource("http://example.org/C");
    Resource C2 = classModel.createResource("http://example2.org/C");
    Resource C3 = classModel.createResource("http://example3.org/C");
    Resource D2 = classModel.createResource("http://example2.org/D");
    Resource D3 = classModel.createResource("http://example3.org/D");
    classModel.add(A, RDF.type, RDFS.Class);
    classModel.add(B, RDF.type, RDFS.Class);
    classModel.add(C, RDF.type, RDFS.Class);
    classModel.add(C2, RDF.type, RDFS.Class);
    classModel.add(C3, RDF.type, RDFS.Class);
    classModel.add(D2, RDF.type, RDFS.Class);
    classModel.add(D3, RDF.type, RDFS.Class);
    classModel.add(B, RDFS.subClassOf, A);
    classModel.add(C, RDFS.subClassOf, B);
    classModel.add(C, OWL.sameAs, C2);
    classModel.add(C3, OWL.equivalentClass, C);
    classModel.add(D2, RDFS.subClassOf, C2);
    classModel.add(D3, RDFS.subClassOf, C3);
    return classModel;
}
 
Example #10
Source File: BatchShapeTargetReader.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
private List<ShapeTarget> collectImplicitClassTarget(Resource resource) {
    if (resource.hasProperty(RDF.type, RDFS.Class) || resource.hasProperty(RDF.type, OWL.Class)) {
        return Collections.singletonList(
                ShapeTargetCore.create(ShapeTargetType.ClassTarget, resource
        ));
    } else {
        return Collections.emptyList();
    }
}
 
Example #11
Source File: ModelWrapper.java    From FCA-Map with GNU General Public License v3.0 5 votes vote down vote up
private void acquireClasses() {
  ResIterator it = null;

  if (m_inferred) {
    it = m_inferred_model.listResourcesWithProperty(RDF.type, OWL.Class);
  } else {
    it = m_raw_model.listResourcesWithProperty(RDF.type, OWL.Class);
  }

  m_classes = acquireResources(it);
}
 
Example #12
Source File: RDFUnitUtils.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
public static List<SchemaSource> augmentWithOwlImports(Set<SchemaSource> originalSources) {

        ImmutableList.Builder<SchemaSource> augmentedSources = ImmutableList.builder();
        augmentedSources.addAll(originalSources);

        Set<String> schemaIris = originalSources.stream().map(SchemaSource::getSchema).collect(Collectors.toSet());
        Set<SchemaSource> currentSources = new HashSet<>(originalSources);

        while (!currentSources.isEmpty()) {

            Set<SchemaSource> computedSources = currentSources.stream()
                    .map(SchemaSource::getModel)
                    .flatMap(m -> m.listObjectsOfProperty(OWL.imports).toList().stream())
                    .filter(RDFNode::isResource)
                    .map(RDFNode::asResource)
                    .map(Resource::getURI)
                    .filter(uri -> !schemaIris.contains(uri))
                    .map(SchemaService::getSourceFromUri)
                    .filter(Optional::isPresent)
                    .map(Optional::get)
                    .collect(Collectors.toSet());

            Set<String> newIris = computedSources.stream().map(SchemaSource::getSchema).collect(Collectors.toSet());
            schemaIris.addAll(newIris);

            augmentedSources.addAll(computedSources);
            currentSources = computedSources;

        }
        return augmentedSources.build();
    }
 
Example #13
Source File: ReaderTestUtils.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
public static Model createOneTripleModel() {
    Model model = ModelFactory.createDefaultModel();
    model.add(
            ResourceFactory.createResource("http://rdfunit.aksw.org"),
            OWL.sameAs,
            ResourceFactory.createResource("http://dbpedia.org/resource/Cool"));
    return model;
}
 
Example #14
Source File: DocumentInformationReducer.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Document reduceToTextAndTypedEntities(Document document) {
	 MarkingFilter<TypedNamedEntity> filter = new TypeBasedMarkingFilter<TypedNamedEntity>(false,
             RDFS.Class.getURI(), OWL.Class.getURI());
     List<TypedNamedEntity> namedEntities = document.getMarkings(TypedNamedEntity.class);
     List<Marking> markings = new ArrayList<Marking>(namedEntities.size());
     for (TypedNamedEntity tne : namedEntities) {
         if (filter.isMarkingGood(tne)) {
             markings.add(new TypedNamedEntity(tne.getStartPosition(), tne.getLength(), tne.getUris(), tne.getTypes()));
         }
     }
     return new DocumentImpl(document.getText(), document.getDocumentURI(), markings);
}
 
Example #15
Source File: DocumentInformationReducer.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Document reduceToTextAndEntities(Document document) {
    MarkingFilter<TypedNamedEntity> filter = new TypeBasedMarkingFilter<TypedNamedEntity>(false,
            RDFS.Class.getURI(), OWL.Class.getURI());
    List<TypedNamedEntity> namedEntities = document.getMarkings(TypedNamedEntity.class);
    List<Marking> markings = new ArrayList<Marking>(namedEntities.size());
    for (TypedNamedEntity tne : namedEntities) {
        if (filter.isMarkingGood(tne)) {
            markings.add(new NamedEntity(tne.getStartPosition(), tne.getLength(), tne.getUris()));
        }
    }
    return new DocumentImpl(document.getText(), document.getDocumentURI(), markings);
}
 
Example #16
Source File: DatasetBasedSameAsRetriever.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns a DatasetBasedSameAsRetriever or null if the dataset does not
 * contain any owl:sameAs relations.
 * 
 * @param dataset
 * @return
 */
public static DatasetBasedSameAsRetriever create(Dataset dataset) {
    if (dataset instanceof RdfModelContainingDataset) {
        RdfModelContainingDataset rdfDataset = (RdfModelContainingDataset) dataset;
        Model model = rdfDataset.getRdfModel();
        if (model == null) {
            return null;
        }
        if (model.contains(null, OWL.sameAs)) {
            return new DatasetBasedSameAsRetriever(model, rdfDataset);
        }
    }
    return null;
}
 
Example #17
Source File: SimpleSubClassInferencer.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addOrUpdateUri(Resource resource, ClassSet hierarchy, ClassNodeFactory<? extends ClassNode> factory,
        Set<String> alreadySeenUris) {
    String uri = resource.getURI();
    ClassNode node = hierarchy.getNode(uri);
    if (node == null) {
        node = factory.createNode(uri);
        hierarchy.addNode(node);
    } else {
        factory.updateNode(node);
    }
    alreadySeenUris.add(uri);

    StmtIterator iterator = classModel.listStatements(resource, OWL.sameAs, (RDFNode) null);
    Statement stmt;
    while (iterator.hasNext()) {
        stmt = iterator.next();
        uri = stmt.getObject().asResource().getURI();
        hierarchy.addUriToNode(node, uri);
        alreadySeenUris.add(uri);
    }
    iterator = classModel.listStatements(resource, OWL.equivalentClass, (RDFNode) null);
    while (iterator.hasNext()) {
        stmt = iterator.next();
        uri = stmt.getObject().asResource().getURI();
        hierarchy.addUriToNode(node, uri);
        alreadySeenUris.add(uri);
    }
}
 
Example #18
Source File: OWLClassPropertyMetadataPlugin.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ClassPropertyMetadata cpm, Node classNode, Graph graph) {
	ExtendedIterator<Triple> it = graph.find(classNode, RDFS.subClassOf.asNode(), Node.ANY);
	while(it.hasNext()) {
		Node superClass = it.next().getObject();
		if(superClass.isBlank() && graph.contains(superClass, OWL.onProperty.asNode(), cpm.getPredicate())) {
			if(cpm.getLocalRange() == null) {
				Node localRange = JenaNodeUtil.getObject(superClass, OWL.allValuesFrom.asNode(), graph);
				if(localRange != null) {
					cpm.setLocalRange(localRange);
					it.close();
					break;
				}
			}
			if(cpm.getMaxCount() == null) {
				Node maxCountNode = JenaNodeUtil.getObject(superClass, OWL.maxCardinality.asNode(), graph);
				if(maxCountNode == null) {
					maxCountNode = JenaNodeUtil.getObject(superClass, OWL.cardinality.asNode(), graph);
				}
				if(maxCountNode != null && maxCountNode.isLiteral()) {
					Object value = maxCountNode.getLiteralValue();
					if(value instanceof Number) {
						cpm.setMaxCount(((Number) value).intValue());
					}
				}
			}
		}
	}
}
 
Example #19
Source File: SPARQLSubstitutions.java    From shacl with Apache License 2.0 5 votes vote down vote up
private static String collectPrefixes(Resource ontology, PrefixMapping pm, Set<Resource> reached) {
	
	reached.add(ontology);
	
	for(Resource decl : JenaUtil.getResourceProperties(ontology, SH.declare)) {
		String prefix = JenaUtil.getStringProperty(decl, SH.prefix);
		String ns = JenaUtil.getStringProperty(decl, SH.namespace);
		if(prefix != null && ns != null) {
			String oldNS = pm.getNsPrefixURI(prefix);
			if(oldNS != null && !oldNS.equals(ns)) {
				return prefix;
			}
			pm.setNsPrefix(prefix, ns);
		}
	}
	
	for(Resource imp : JenaUtil.getResourceProperties(ontology, OWL.imports)) {
		if(!reached.contains(imp)) {
			String duplicate = collectPrefixes(imp, pm, reached);
			if(duplicate != null) {
				return duplicate;
			}
		}
	}
	
	return null;
}
 
Example #20
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the usual default namespaces for rdf, rdfs, owl and xsd.
 * @param prefixMapping  the Model to modify
 */
public static void initNamespaces(PrefixMapping prefixMapping) {
    ensurePrefix(prefixMapping, "rdf",  RDF.getURI());
    ensurePrefix(prefixMapping, "rdfs", RDFS.getURI());
    ensurePrefix(prefixMapping, "owl",  OWL.getURI());
    ensurePrefix(prefixMapping, "xsd",  XSD.getURI());
}
 
Example #21
Source File: SkolemizerTest.java    From Processor with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp()
{
    baseUriBuilder = UriBuilder.fromUri("http://base/");
    absolutePathBuilder = UriBuilder.fromUri("http://base/absolute/path");
    ontology = ModelFactory.createOntologyModel().createOntology("http://test/ontology");
    importedOntology = ontology.getOntModel().createOntology("http://test/ontology/import");
    ontology.addImport(importedOntology);
    skolemizer = new Skolemizer(ontology, baseUriBuilder, absolutePathBuilder);
    
    relativePathClass = ontology.getOntModel().createClass("http://test/ontology/relative-path-class");
    relativePathClass.addLiteral(LDT.path, "{identifier}").
            addProperty(RDFS.isDefinedBy, ontology);
    absolutePathClass = ontology.getOntModel().createClass("http://test/ontology/absolute-path-class");
    absolutePathClass.addLiteral(LDT.path, "/{identifier}").
            addProperty(RDFS.isDefinedBy, ontology);
    thingClass = ontology.getOntModel().createClass("http://test/ontology/thing-class");
    thingClass.addLiteral(LDT.path, "{title}").
            addProperty(LDT.fragment, "something").
            addProperty(RDFS.isDefinedBy, ontology);
    importedClass = importedOntology.getOntModel().createClass("http://test/ontology/import/thing-class");
    importedClass.addLiteral(LDT.path, "{title}").
            addProperty(LDT.fragment, "something").
            addProperty(RDFS.isDefinedBy, importedOntology);
    restrictedClass = ontology.getOntModel().createClass("http://test/ontology/restricted-class");
    restrictedClass.addLiteral(LDT.path, "{identifier}").
            addProperty(RDFS.isDefinedBy, ontology).
            addProperty(RDFS.subClassOf, restrictedClass.getOntModel().createHasValueRestriction(null, SIOC.HAS_CONTAINER, restrictedClass.getOntModel().createResource(restrictionValue)));
    restrictedClass.getOntModel().createResource(SIOC.HAS_CONTAINER.getURI()).
            addProperty(RDF.type, OWL.ObjectProperty);
    undefinedClass = ontology.getOntModel().createClass("http://test/ontology/undefined-class");
    undefinedClass.addLiteral(LDT.path, "{whateverest}"); // does not have rdfs:isDefinedBy
            
    input = ModelFactory.createDefaultModel();
    absolute = input.createResource().
            addProperty(RDF.type, absolutePathClass).
            addLiteral(DCTerms.identifier, absoluteId);
    relative = input.createResource().
            addProperty(RDF.type, relativePathClass).
            addLiteral(DCTerms.identifier, relativeId);
    thing = input.createResource().
            addProperty(RDF.type, thingClass).
            addLiteral(DCTerms.title, thingTitle);
    imported = input.createResource().
            addProperty(RDF.type, importedClass).
            addLiteral(DCTerms.title, thingTitle);
    restricted = input.createResource().
            addProperty(RDF.type, restrictedClass).
            addLiteral(DCTerms.identifier, restrictedId);
    relative.addProperty(FOAF.primaryTopic, thing);
    thing.addProperty(FOAF.isPrimaryTopicOf, relative);
}
 
Example #22
Source File: SystemTriples.java    From shacl with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the system ontology (a shared copy).
 * @return the system ontology
 */
public static synchronized Model getVocabularyModel() {
	if (vocabulary == null) {
		vocabulary = JenaUtil.createDefaultModel();
		org.topbraid.jenax.util.JenaUtil.initNamespaces(vocabulary.getGraph());
		vocabulary.setNsPrefix("xsd", XSD.getURI());
		InputStream ttl = SystemTriples.class.getResourceAsStream("/rdf/system-triples.ttl");
		vocabulary.read(ttl, "urn:x:dummy", FileUtils.langTurtle);
		ensureSuperClasses(RDFS.Class, RDFS.Resource);
		ensureSuperClasses(OWL.Class, OWL.Thing);
		
		// Remove owl imports rdfs which only causes trouble
		vocabulary.removeAll(null, OWL.imports, null); 
		
		vocabulary.add(OWL.Thing, RDFS.subClassOf, RDFS.Resource);
		vocabulary.add(OWL.inverseOf, RDF.type, OWL.SymmetricProperty);
		vocabulary.add(OWL.equivalentClass, RDF.type, OWL.SymmetricProperty);
		vocabulary.add(OWL.equivalentProperty, RDF.type, OWL.SymmetricProperty);
		vocabulary.add(OWL.equivalentProperty, RDFS.range, RDF.Property);
		vocabulary.add(OWL.differentFrom, RDF.type, OWL.SymmetricProperty);
		vocabulary.add(OWL.sameAs, RDF.type, OWL.SymmetricProperty);
		vocabulary.add(OWL.disjointWith, RDF.type, OWL.SymmetricProperty);
		Resource xml = vocabulary.getResource(XMLLiteralType.theXMLLiteralType.getURI());
		vocabulary.add(xml, RDFS.subClassOf, RDFS.Resource);
		for(String uri : JenaDatatypes.getDatatypeURIs()) {
			Resource r = vocabulary.getResource(uri);
			if (r.getProperty(RDF.type) == null) {
				vocabulary.add(r, RDF.type, RDFS.Datatype);
				vocabulary.add(r, RDFS.subClassOf, RDFS.Literal);
			}
		}
		
		vocabulary.add(RDF.HTML, RDFS.label, "HTML");
		
		// Triples were formally in OWL 1, but dropped from OWL 2
		vocabulary.add(RDFS.comment, RDF.type, OWL.AnnotationProperty);
		vocabulary.add(RDFS.label, RDF.type, OWL.AnnotationProperty);
		vocabulary.add(RDFS.isDefinedBy, RDF.type, OWL.AnnotationProperty);
		vocabulary.add(RDFS.seeAlso, RDF.type, OWL.AnnotationProperty);
		
		// Add rdfs:labels for XSD types
		for(Resource datatype : vocabulary.listSubjectsWithProperty(RDF.type, RDFS.Datatype).toList()) {
			datatype.addProperty(RDFS.label, datatype.getLocalName());
           }
		vocabulary = JenaUtil.asReadOnlyModel(vocabulary);
	}
	return vocabulary;
}