org.apache.jena.ontology.OntClass Java Examples

The following examples show how to use org.apache.jena.ontology.OntClass. 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: AbstractRdfEntityGraphConsumer.java    From baleen with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private Individual addIndividual(OntModel model, Vertex v, String className) {
  OntClass ontClass = model.getOntClass(namespace + className);
  if (ontClass != null) {
    Individual individual = ontClass.createIndividual(namespace + v.id());
    Map<String, List> propertyValueMap = ElementHelper.vertexPropertyValueMap(v);
    propertyValueMap
        .entrySet()
        .forEach(
            e -> {
              Property property = model.getProperty(namespace + e.getKey());
              if (property != null) {
                e.getValue().forEach(value -> individual.addProperty(property, value.toString()));
              }
            });
    return individual;
  } else {
    getMonitor().warn("Missing ontology class {}", className);
  }
  return null;
}
 
Example #2
Source File: AbstractRdfDocumentGraphConsumer.java    From baleen with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private Individual addIndividual(OntModel model, Vertex v, String className) {
  OntClass ontClass = model.getOntClass(namespace + className);
  if (ontClass != null) {
    Individual individual = ontClass.createIndividual(namespace + v.id());
    Map<String, List> propertyValueMap = ElementHelper.vertexPropertyValueMap(v);
    propertyValueMap
        .entrySet()
        .forEach(
            e -> {
              Property property = model.getProperty(namespace + e.getKey());
              if (property != null) {
                e.getValue().forEach(value -> individual.addProperty(property, value.toString()));
              }
            });
    return individual;
  } else {
    getMonitor().warn("Missing ontology class {}", className);
  }
  return null;
}
 
Example #3
Source File: ReasoningOntology.java    From Heracles with GNU General Public License v3.0 6 votes vote down vote up
public String addClass(String lemmaURI, String... classURIs){
		HashSet<String> existingURIs = getLexicalizedConcepts(URI_Mention, lemmaURI.toLowerCase());
		if (existingURIs.size() > 0){
			return existingURIs.iterator().next();
		}
		
		String URI = NS + "#" + lemmaURI.replaceAll(" ", "");
//		if (ontology.getResource(URI) == null){
//		OntClass newClass = (OntClass) ontology.getResource(URI);
		OntClass newClass = data.createClass(URI);
		newClass.addProperty(ontology.getProperty(NS+"#lex"), lemmaURI.toLowerCase());
		for (String classURI : classURIs){
			newClass.addSuperClass(ontology.getResource(classURI));
		}
		Framework.log("Add Class: "+URI);
		this.updateInfModel();
		return newClass.getURI();
//		} else {
//			return URI;
//		}
	}
 
Example #4
Source File: OwlSchemaFactory.java    From baleen with Apache License 2.0 6 votes vote down vote up
/** Creates an entity ontology */
public OntModel createEntityOntology() {
  OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);

  OntClass entity = addType(ontModel, null, getType(ENTITY));
  OntClass event = addType(ontModel, null, getType(EVENT));

  addProperty(ontModel, entity, "value", "The value of the mention", XSD.xstring);
  addProperty(ontModel, entity, "longestValue", "The longest value of the mention", XSD.xstring);
  addProperty(
      ontModel, entity, "mostCommonValue", "The most common value of the mention", XSD.xstring);
  addProperty(ontModel, entity, "mentions", "The details of the mentions", XSD.xstring);
  addProperty(ontModel, "docId", "The docId the mention came from", XSD.xstring);

  addRelation(ontModel, entity, entity, RELATION, "A relationship between two entities");
  addRelation(ontModel, entity, event, PARTICIPANT_IN, "A participant in the event");

  return ontModel;
}
 
Example #5
Source File: Skolemizer.java    From Processor with Apache License 2.0 6 votes vote down vote up
protected String getStringValue(OntClass ontClass, Property property)
{
    if (ontClass == null) throw new IllegalArgumentException("OntClass cannot be null");
    if (property == null) throw new IllegalArgumentException("Property cannot be null");

    if (ontClass.hasProperty(property))
    {
        if (!ontClass.getPropertyValue(property).isLiteral() ||
                ontClass.getPropertyValue(property).asLiteral().getDatatype() == null ||
                !ontClass.getPropertyValue(property).asLiteral().getDatatype().equals(XSDDatatype.XSDstring))
        {
            if (log.isErrorEnabled()) log.error("Class {} property {} is not an xsd:string literal", ontClass, property);
            throw new OntologyException("Class '" + ontClass + "' property '" + property + "' is not an xsd:string literal");
        }
        
        return ontClass.getPropertyValue(property).asLiteral().getString();
    }
    
    return null;
}
 
Example #6
Source File: ModelStorage.java    From FCA-Map with GNU General Public License v3.0 5 votes vote down vote up
private void acquireOntClasses() {
  for (ExtendedIterator<OntClass> it = ontModel.listClasses(); it.hasNext(); ) {
    OntClass c = it.next();
    if (isIgnoredOntClass(c)) continue;
    ontClasses.add(c);
  }
}
 
Example #7
Source File: OwlSchemaFactory.java    From baleen with Apache License 2.0 5 votes vote down vote up
private void addFeature(OntModel ontModel, OntClass ontClass, FeatureDescription feature) {
  if (ontModel.getDatatypeProperty(namespace + feature.getName()) == null) {
    DatatypeProperty property = ontModel.createDatatypeProperty(namespace + feature.getName());
    String propertyComment = feature.getDescription();
    if (propertyComment != null) {
      property.addComment(propertyComment, EN);
    }

    property.addDomain(ontClass);
    property.addRange(getRange(feature));
  }
}
 
Example #8
Source File: OwlSchemaFactory.java    From baleen with Apache License 2.0 5 votes vote down vote up
private void addProperty(
    OntModel ontModel, OntClass domain, String name, String comment, Resource range) {
  DatatypeProperty begin = ontModel.createDatatypeProperty(namespace + name);
  begin.addComment(comment, EN);
  begin.addDomain(domain);
  begin.addRange(range);
}
 
Example #9
Source File: OwlSchemaFactory.java    From baleen with Apache License 2.0 5 votes vote down vote up
private void addRelation(
    OntModel ontModel, OntClass domain, OntClass range, String property, String comment) {
  ObjectProperty objectProperty = ontModel.createObjectProperty(namespace + property);
  objectProperty.addComment(comment, EN);
  objectProperty.setDomain(domain);
  objectProperty.setRange(range);
}
 
Example #10
Source File: OwlSchemaFactory.java    From baleen with Apache License 2.0 5 votes vote down vote up
/** Creates a document ontology */
public OntModel createDocumentOntology() {
  OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);

  OntClass document = addType(ontModel, null, getType(Document.class.getSimpleName()));
  OntClass mention = ontModel.createClass(namespace + MENTION);

  mention.addComment("Root mention type", EN);
  addProperty(ontModel, mention, "begin", "The start of the mention offset", XSD.xint);
  addProperty(ontModel, mention, "end", "The end of the mention offset", XSD.xint);
  addProperty(ontModel, mention, "value", "The value of the mention", XSD.xstring);
  addProperty(ontModel, mention, "docId", "The docId the mention came from", XSD.xstring);

  OntClass reference = addType(ontModel, null, getType(REFERENCE_TARGET));
  OntClass relation = addType(ontModel, mention, getType(RELATION));

  OntClass entity = addType(ontModel, mention, getType(ENTITY));
  OntClass event = addType(ontModel, mention, getType(EVENT));

  addRelation(ontModel, entity, entity, RELATION, "A relationship between two entities");
  addRelation(ontModel, entity, relation, SOURCE, "The source of the relationship");
  addRelation(ontModel, relation, entity, TARGET, "The target of the relationship");
  addRelation(ontModel, mention, document, MENTION_IN, "The document this is mentioned in");
  addRelation(ontModel, entity, reference, MENTION_OF, "The mention of the reference");
  addRelation(ontModel, entity, event, PARTICIPANT_IN, "A participant in the event");

  return ontModel;
}
 
Example #11
Source File: ROEvoSerializer.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
private void addPrevious(OntModel model,
		Revision revision, Revision previous) {
	OntClass VersionableResource = model.createClass("http://purl.org/wf4ever/roevo#VersionableResource");
	VersionableResource.addSuperClass(prov.Entity);
	
	Individual revisionResource = model.createIndividual(revision.getIdentifier().toASCIIString(), 
			VersionableResource);
	Individual previousResource = model.createIndividual(previous.getIdentifier().toASCIIString(), 
			VersionableResource);
	revisionResource.addProperty(prov.wasRevisionOf, previousResource);
}
 
Example #12
Source File: ROEvoSerializer.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
private void addRevision(OntModel model,
		Revision revision) {
	OntClass VersionableResource = model.createClass("http://purl.org/wf4ever/roevo#VersionableResource");
	VersionableResource.addSuperClass(prov.Entity);
	Individual revisionResource = model.createIndividual(revision.getIdentifier().toASCIIString(), 
			VersionableResource);
	revisionResource.addRDFType(prov.Entity);
}
 
Example #13
Source File: SkolemizerTest.java    From Processor with Apache License 2.0 5 votes vote down vote up
@Test(expected = OntologyException.class)
public void testGetStringValueWithNumericalPath()
{
    OntClass numericalPath = ModelFactory.createOntologyModel().createClass();
    numericalPath.addLiteral(LDT.path, 123);
    skolemizer.getStringValue(numericalPath, LDT.path);
}
 
Example #14
Source File: SkolemizerTest.java    From Processor with Apache License 2.0 5 votes vote down vote up
/**
 * Test of getStringValue method, of class Skolemizer.
 */
@Test(expected = OntologyException.class)
public void testGetStringValueWithNonLiteralPath()
{
    OntClass nonLiteralPath = ModelFactory.createOntologyModel().createClass();
    nonLiteralPath.addProperty(LDT.path, nonLiteralPath.getOntModel().createResource());
    skolemizer.getStringValue(nonLiteralPath, LDT.path);
}
 
Example #15
Source File: SkolemizerTest.java    From Processor with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetStringValueWithoutPath()
{
    OntClass classWithoutPath = ModelFactory.createOntologyModel().createClass();
    String noPathResult = skolemizer.getStringValue(classWithoutPath, LDT.path);
    assertNull(noPathResult);
}
 
Example #16
Source File: SkolemizerTest.java    From Processor with Apache License 2.0 5 votes vote down vote up
@Test(expected = OntologyException.class)
public void testBuild_Resource_OntClassInvalidPath()
{
    Ontology invalidOntology = ModelFactory.createOntologyModel().createOntology("http://test/invalid");
    OntClass invalidPathClass = invalidOntology.getOntModel().createClass("http://test/invalid/path-class");
    invalidPathClass.addLiteral(LDT.path, 123).
            addProperty(RDFS.isDefinedBy, invalidOntology);
    Resource invalid = ModelFactory.createDefaultModel().createResource();
    
    URI invalidResult = skolemizer.build(invalid, invalidPathClass);
    URI invalidExp = absolutePathBuilder.clone().path(thingTitle).fragment(thingFragment).build();
    assertEquals(invalidExp, invalidResult);
}
 
Example #17
Source File: Skolemizer.java    From Processor with Apache License 2.0 5 votes vote down vote up
public URI build(Resource resource, OntClass typeClass)
{
    if (resource == null) throw new IllegalArgumentException("Resource cannot be null");
    if (typeClass == null) throw new IllegalArgumentException("OntClass cannot be null");

    // skolemization template builds with absolute path builder (e.g. "{slug}")
    String path = getStringValue(typeClass, LDT.path);
    if (path == null)
        throw new IllegalStateException("Cannot skolemize resource of class " + typeClass + " which does not have ldt:path annotation");

    final UriBuilder builder;
    // treat paths starting with / as absolute, others as relative (to the current absolute path)
    // JAX-RS URI templates do not have this distinction (leading slash is irrelevant)
    if (path.startsWith("/"))
        builder = getBaseUriBuilder().clone();
    else
    {
        Resource parent = getParent(typeClass);
        if (parent != null) builder = UriBuilder.fromUri(parent.getURI());
        else builder = getAbsolutePathBuilder().clone();
    }

    Map<String, String> nameValueMap = getNameValueMap(resource, new UriTemplateParser(path));
    builder.path(path);

    // add fragment identifier
    String fragment = getStringValue(typeClass, LDT.fragment);
    return builder.fragment(fragment).buildFromMap(nameValueMap); // TO-DO: wrap into SkolemizationException
}
 
Example #18
Source File: Skolemizer.java    From Processor with Apache License 2.0 5 votes vote down vote up
public URI build(Resource resource)
{
    SortedSet<ClassPrecedence> matchedClasses = match(getOntology(), resource, RDF.type, 0);
    if (!matchedClasses.isEmpty())
    {
        OntClass typeClass = matchedClasses.first().getOntClass();
        if (log.isDebugEnabled()) log.debug("Skolemizing resource {} using ontology class {}", resource, typeClass);
        
        return build(resource, typeClass);
    }
    
    return null;
}
 
Example #19
Source File: Skolemizer.java    From Processor with Apache License 2.0 5 votes vote down vote up
public ClassPrecedence(OntClass ontClass, int precedence)
{
    if (ontClass == null) throw new IllegalArgumentException("OntClass cannot be null");

    this.ontClass = ontClass;
    this.precedence = precedence;
}
 
Example #20
Source File: OntModelWrapper.java    From FCA-Map with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Acquire the classes and skip the ignored one
 */
private void acquireClasses() {
  for (ExtendedIterator<OntClass> it = m_ontology.listClasses(); it.hasNext(); ) {
    OntClass c = it.next();
    if (isSkipClass(c)) continue;
    m_classes.add(c);
  }
}
 
Example #21
Source File: Skolemizer.java    From Processor with Apache License 2.0 4 votes vote down vote up
public SortedSet<ClassPrecedence> match(Ontology ontology, Resource resource, Property property, int level)
{
    if (ontology == null) throw new IllegalArgumentException("Ontology cannot be null");
    if (resource == null) throw new IllegalArgumentException("Resource cannot be null");
    if (property == null) throw new IllegalArgumentException("Property cannot be null");

    SortedSet<ClassPrecedence> matchedClasses = new TreeSet<>();
    ResIterator it = ontology.getOntModel().listResourcesWithProperty(LDT.path);
    try
    {
        while (it.hasNext())
        {
            Resource ontClassRes = it.next();
            OntClass ontClass = ontology.getOntModel().getOntResource(ontClassRes).asClass();
            // only match templates defined in this ontology - maybe reverse loops?
            if (ontClass.getIsDefinedBy() != null && ontClass.getIsDefinedBy().equals(ontology) &&
                    resource.hasProperty(property, ontClass))
            {
                ClassPrecedence precedence = new ClassPrecedence(ontClass, level * -1);
                if (log.isTraceEnabled()) log.trace("Resource {} matched OntClass {}", resource, ontClass);
                matchedClasses.add(precedence);
            } 
        }
    }
    finally
    {
        it.close();
    }

    ExtendedIterator<OntResource> imports = ontology.listImports();
    try
    {
        while (imports.hasNext())
        {
            OntResource importRes = imports.next();
            if (importRes.canAs(Ontology.class))
            {
                Ontology importedOntology = importRes.asOntology();
                // traverse imports recursively
                Set<ClassPrecedence> matchedImportClasses = match(importedOntology, resource, property, level + 1);
                matchedClasses.addAll(matchedImportClasses);
            }
        }
    }
    finally
    {
        imports.close();
    }
    
    return matchedClasses;
}
 
Example #22
Source File: Skolemizer.java    From Processor with Apache License 2.0 4 votes vote down vote up
public final OntClass getOntClass()
{
    return ontClass;
}
 
Example #23
Source File: ModelStorage.java    From FCA-Map with GNU General Public License v3.0 4 votes vote down vote up
private static final boolean isIgnoredOntClass(OntClass c) {
  return c.isAnon();
}
 
Example #24
Source File: ModelStorage.java    From FCA-Map with GNU General Public License v3.0 4 votes vote down vote up
public Set<OntClass> getOntClasses() {
  return ontClasses;
}
 
Example #25
Source File: OwlSchemaFactoryTest.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Test
public void canGenerateDocumentSchema() throws CASRuntimeException, UIMAException {

  String ns = "http://baleen.dstl.gov.uk/document/";
  OwlSchemaFactory owlTypeSystem =
      new OwlSchemaFactory(ns, typeSystem, ImmutableList.of("internalId"));
  OntModel model = owlTypeSystem.createDocumentOntology();
  model.setNsPrefix("baleen", ns);

  try {
    assertNotNull(model);
    assertNotNull(model.getOntClass(ns + Document.class.getSimpleName()));
    assertNotNull(model.getOntClass(ns + ReferenceTarget.class.getSimpleName()));
    assertNotNull(model.getOntClass(ns + Relation.class.getSimpleName()));
    OntClass entity = model.getOntClass(ns + Entity.class.getSimpleName());
    assertNotNull(entity);
    assertEquals(
        "Type to represent named entities - values that are assigned a semantic type.",
        entity.getComment("EN"));

    assertNotNull(entity.getSuperClass());
    assertEquals(getEntityChildrenCount(), Streams.stream(entity.listSubClasses()).count());

    OntClass location = model.getOntClass(ns + Location.class.getSimpleName());
    assertEquals(entity, location.getSuperClass());
    assertEquals(1, Streams.stream(location.listSubClasses()).count());

    OntClass person = model.getOntClass(ns + Person.class.getSimpleName());
    assertEquals(entity, person.getSuperClass());
    assertEquals(0, Streams.stream(person.listSubClasses()).count());
    assertEquals(2, Streams.stream(person.listDeclaredProperties(true)).count());
    assertEquals(13, Streams.stream(person.listDeclaredProperties()).count());
    Optional<OntProperty> findFirst =
        Streams.stream(person.listDeclaredProperties(true))
            .filter(p -> "gender".equals(p.getLocalName()))
            .findFirst();
    assertTrue(findFirst.isPresent());
    assertEquals(XSD.xstring, findFirst.get().getRange());

    Optional<OntProperty> mentionOf =
        Streams.stream(person.listDeclaredProperties())
            .filter(p -> DocumentGraphFactory.MENTION_OF.equals(p.getLocalName()))
            .findFirst();
    assertTrue(mentionOf.isPresent());
    assertEquals(
        ReferenceTarget.class.getSimpleName(), mentionOf.get().getRange().getLocalName());

  } finally {
    writeToConsole(model);
  }
}
 
Example #26
Source File: OwlSchemaFactoryTest.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Test
public void canGenerateEntitySchema() throws ResourceInitializationException {

  String ns = "http://baleen.dstl.gov.uk/entity/";

  OwlSchemaFactory owlTypeSystem =
      new OwlSchemaFactory(ns, typeSystem, ImmutableList.of("isNormalised", "internalId"));
  OntModel model = owlTypeSystem.createEntityOntology();
  model.setNsPrefix("baleen", ns);

  try {
    assertNotNull(model);
    assertNull(model.getOntClass(ns + Document.class.getSimpleName()));
    assertNull(model.getOntClass(ns + ReferenceTarget.class.getSimpleName()));
    assertNull(model.getOntClass(ns + Relation.class.getSimpleName()));
    OntClass entity = model.getOntClass(ns + Entity.class.getSimpleName());
    assertNotNull(entity);
    assertEquals(
        "Type to represent named entities - values that are assigned a semantic type.",
        entity.getComment("EN"));

    assertNull(entity.getSuperClass());
    assertEquals(17, Streams.stream(entity.listSubClasses()).count());

    OntClass location = model.getOntClass(ns + Location.class.getSimpleName());
    assertEquals(entity, location.getSuperClass());
    assertEquals(1, Streams.stream(location.listSubClasses()).count());

    OntClass person = model.getOntClass(ns + Person.class.getSimpleName());
    assertEquals(entity, person.getSuperClass());
    assertEquals(0, Streams.stream(person.listSubClasses()).count());
    assertEquals(2, Streams.stream(person.listDeclaredProperties(true)).count());
    assertEquals(12, Streams.stream(person.listDeclaredProperties()).count());
    Optional<OntProperty> findFirst =
        Streams.stream(person.listDeclaredProperties(true))
            .filter(p -> "gender".equals(p.getLocalName()))
            .findFirst();
    Optional<OntProperty> mentions =
        Streams.stream(person.listDeclaredProperties())
            .filter(p -> "mentions".equals(p.getLocalName()))
            .findFirst();
    assertTrue(mentions.isPresent());
    assertEquals(XSD.xstring, findFirst.get().getRange());

    Optional<OntProperty> relation =
        Streams.stream(person.listDeclaredProperties())
            .filter(p -> DocumentGraphFactory.RELATION.equals(p.getLocalName()))
            .findFirst();
    assertTrue(relation.isPresent());
    assertEquals(Entity.class.getSimpleName(), relation.get().getRange().getLocalName());
    assertEquals(Entity.class.getSimpleName(), relation.get().getDomain().getLocalName());

  } finally {
    writeToConsole(model);
  }
}
 
Example #27
Source File: OntModelWrapper.java    From FCA-Map with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Get the hash set of classes
 *
 * @return m_classes
 */
public Set<OntClass> getOntClasses() {
  return m_classes;
}
 
Example #28
Source File: OntModelWrapper.java    From FCA-Map with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Check whether the class should be skipped
 *
 * @param c class
 * @return true means the class should be ignored
 */
private static final boolean isSkipClass(OntClass c) {
  return c.isAnon();
}