Java Code Examples for org.apache.jena.rdf.model.ModelFactory#createOntologyModel()

The following examples show how to use org.apache.jena.rdf.model.ModelFactory#createOntologyModel() . 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: Main.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main( String[] args ) {
    OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM, null );

    // we have a local copy of the wine ontology
    m.getDocumentManager().addAltEntry( "http://www.w3.org/2001/sw/WebOnt/guide-src/wine",
                                        "file:testing/reasoners/bugs/wine.owl" );
    m.getDocumentManager().addAltEntry( "http://www.w3.org/2001/sw/WebOnt/guide-src/wine.owl",
                                        "file:testing/reasoners/bugs/wine.owl" );
    m.getDocumentManager().addAltEntry( "http://www.w3.org/2001/sw/WebOnt/guide-src/food",
                                        "file:testing/reasoners/bugs/food.owl" );
    m.getDocumentManager().addAltEntry( "http://www.w3.org/2001/sw/WebOnt/guide-src/food.owl",
                                        "file:testing/reasoners/bugs/food.owl" );

    m.read( "http://www.w3.org/2001/sw/WebOnt/guide-src/wine" );

    new ClassHierarchy().showHierarchy( System.out, m );
}
 
Example 2
Source File: Main.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main( String[] args ) {
    // read the argument file, or the default
    String source = (args.length == 0) ? "http://www.w3.org/2001/sw/WebOnt/guide-src/wine" : args[0];

    OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM, null );

    // we have a local copy of the wine ontology
    addFoodWineAltPaths( m.getDocumentManager() );

    // read the source document
    m.read( source );

    DescribeClass dc = new DescribeClass();

    if (args.length >= 2) {
        // we have a named class to describe
        OntClass c = m.getOntClass( args[1] );
        dc.describeClass( System.out, c );
    }
    else {
        for (Iterator<OntClass> i = m.listClasses();  i.hasNext(); ) {
            // now list the classes
            dc.describeClass( System.out, i.next() );
        }
    }
}
 
Example 3
Source File: Validator.java    From Processor with Apache License 2.0 6 votes vote down vote up
public OntModel fixOntModel(OntModel ontModel)
    {
        if (ontModel == null) throw new IllegalArgumentException("Model cannot be null");
        
        OntModel fixedModel = ModelFactory.createOntologyModel(ontModel.getSpecification());
        Query fix = QueryFactory.create("CONSTRUCT\n" +
"{\n" +
"  ?s ?p ?o\n" +
"}\n" +
"WHERE\n" +
"{\n" +
"  ?s ?p ?o\n" +
"  FILTER (!(?p = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> && ?o = <https://www.w3.org/ns/ldt#Constraint>))\n" +
"}");
        
        try (QueryExecution qex = QueryExecutionFactory.create(fix, ontModel))
        {
            fixedModel.add(qex.execConstruct());
        }
        
        return fixedModel;
    }
 
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: ROEvoSerializer.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
public void workflowHistory(Workflow mainWorkflow, OutputStream output) throws WriterException {	
		OntModel model = ModelFactory.createOntologyModel();
		Revision revision = mainWorkflow.getCurrentRevision();
		Revision previous = revision.getPreviousRevision();
		addRevision(model, revision);
		while (previous != null) {
			addRevision(model, previous);
			addPrevious(model, revision, previous);			
			revision = previous;
			previous = revision.getPreviousRevision();
		}
		
		java.net.URI baseURI = Workflow.WORKFLOW_ROOT;
		model.setNsPrefix("roevo", "http://purl.org/wf4ever/roevo#");
		model.setNsPrefix("prov", "http://www.w3.org/ns/prov#");
		model.setNsPrefix("rdfs",
				"http://www.w3.org/2000/01/rdf-schema#");
			
		model.write(output, "Turtle", baseURI.toASCIIString());

//			throw new WriterException("Can't write to output", e);
		
		
	}
 
Example 6
Source File: ModelStorage.java    From FCA-Map with GNU General Public License v3.0 6 votes vote down vote up
private void read(InputStream in) {
  if (null == in) return;
  model = ModelFactory.createDefaultModel();
  model.read(in, null);
  ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, model);

  acquire();

  if (logger.isInfoEnabled()) {
    logger.info(String.format(infoFormat,
          filenameOrURI,
          individuals.size(),
          categories.size(),
          ontProperties.size(), dataTypeProperties.size(), objectProperties.size(),
          ontClasses.size()));
  }
}
 
Example 7
Source File: GetAllVocabLinksFromLOV.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    RDFUnitUtils.fillSchemaServiceFromLOV();
    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF, ModelFactory.createDefaultModel());
    for (SchemaSource schema : SchemaService.getSourceListAll(false,null)){
        QueryExecutionFactory qef = new QueryExecutionFactoryModel(schema.getModel());

        String queryString = PrefixNSService.getSparqlPrefixDecl() +
                " SELECT DISTINCT ?s ?p ?o WHERE { " +
                " ?s ?p ?o ." +
                " FILTER (?p IN (owl:sameAs, owl:equivalentProperty, owl:equivalentClass))" +
               // " FILTER (strStarts(?s, 'http://dbpedia.org') || strStarts(?o, 'http://dbpedia.org')))" +
                "}";

        try (QueryExecution qe = qef.createQueryExecution(queryString)) {
            qe.execSelect().forEachRemaining(qs -> {

                Resource s = qs.get("s").asResource();
                Resource p = qs.get("p").asResource();
                RDFNode o = qs.get("o");

                model.add(s, ResourceFactory.createProperty(p.getURI()), o);

                // save the data in a file to read later
            });
        }
    }

    try (OutputStream fos = new FileOutputStream("output.ttl")) {

        model.write(fos, "TURTLE");

    } catch (Exception e) {
        throw new UnsupportedOperationException("Error writing file: " + e.getMessage(), e);
    }

}
 
Example 8
Source File: DumpTestSource.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Override
protected QueryExecutionFactory initQueryFactory() {

    // When we load the referenced schemata we do rdfs reasoning to avoid false errors
    // Many ontologies skip some domain / range statements and this way we add them
    OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.RDFS_MEM_RDFS_INF, ModelFactory.createDefaultModel());
    try {

        // load the data only when the model is empty in case it is initialized with the "copy constructor"
        // This sppeds up the process on very big in-memory datasets
        if (dumpModel.isEmpty()) {
            // load the data only when the model is empty in case it is initialized with the "copy constructor"
            dumpReader.read(dumpModel);
        }

        //if (dumpModel.isEmpty()) {
        //    throw new IllegalArgumentException("Dump is empty");
        //}
        //Load all the related ontologies as well (for more consistent querying
        for (SchemaSource src : getReferencesSchemata()) {
            ontModel.add(src.getModel());
        }
        // Here we add the ontologies in the dump mode
        // Note that the ontologies have reasoning enabled but not the dump source
        dumpModel.add(ontModel);
    } catch (Exception e) {
        log.error("Cannot read dump URI: " + getUri() + " Reason: " + e.getMessage());
        throw new IllegalArgumentException("Cannot read dump URI: " + getUri() + " Reason: " + e.getMessage(), e);
    }
    return masqueradeQEF(new QueryExecutionFactoryModel(dumpModel), this);
}
 
Example 9
Source File: AbstractRdfEntityGraphConsumer.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected void processGraph(String documentSourceName, Graph graph)
    throws AnalysisEngineProcessException {

  OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, documentOntology);
  model.setNsPrefix("baleen", namespace);
  GraphTraversalSource traversal = graph.traversal();
  traversal.V().forEachRemaining(v -> addNodeToModel(model, v));
  traversal.E().forEachRemaining(e -> addRelationToModel(model, e));

  outputModel(documentSourceName, model);
}
 
Example 10
Source File: AbstractRdfDocumentGraphConsumer.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected void processGraph(String documentSourceName, Graph graph)
    throws AnalysisEngineProcessException {

  OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, documentOntology);
  model.setNsPrefix("baleen", namespace);
  GraphTraversalSource traversal = graph.traversal();
  traversal.V().forEachRemaining(v -> addNodeToModel(model, v));
  traversal.E().forEachRemaining(e -> addRelationToModel(model, e));

  outputModel(documentSourceName, model);
}
 
Example 11
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 12
Source File: OntologyProvider.java    From Processor with Apache License 2.0 5 votes vote down vote up
public OntologyProvider(final OntDocumentManager ontDocumentManager, final String ontologyURI,
        final OntModelSpec materializationSpec, final boolean materialize)
{
    super(Ontology.class);
    
    if (ontDocumentManager == null) throw new IllegalArgumentException("OntDocumentManager cannot be null");
    if (ontologyURI == null) throw new IllegalArgumentException("URI cannot be null");
    if (materializationSpec == null) throw new IllegalArgumentException("OntModelSpec cannot be null");
    
    this.ontDocumentManager = ontDocumentManager;
    this.ontologyURI = ontologyURI;
    
    // materialize OntModel inferences to avoid invoking rules engine on every request
    if (materialize && materializationSpec.getReasoner() != null)
    {
        OntModel ontModel = getOntModel(ontDocumentManager, ontologyURI, materializationSpec);
        Ontology ontology = ontModel.getOntology(ontologyURI);

        ImportCycleChecker checker = new ImportCycleChecker();
        checker.check(ontology);
        if (checker.getCycleOntology() != null)
        {
            if (log.isErrorEnabled()) log.error("Sitemap contains an ontology which forms an import cycle: {}", checker.getCycleOntology());
            throw new OntologyException("Sitemap contains an ontology which forms an import cycle: " + checker.getCycleOntology().getURI());
        }
        
        OntModel materializedModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
        materializedModel.add(ontModel);
        ontDocumentManager.addModel(ontologyURI, materializedModel, true);
    }
}
 
Example 13
Source File: Validator.java    From Processor with Apache License 2.0 5 votes vote down vote up
public List<ConstraintViolation> validate(Model model)
{
    if (model == null) throw new IllegalArgumentException("Model cannot be null");

    OntModelSpec ontModelSpec = OntModelSpec.OWL_MEM;
    OntModel tempModel = ModelFactory.createOntologyModel(ontModelSpec);
    tempModel.add(fixOntModel(getOntModel())).add(model);
    return SPINConstraints.check(tempModel, null);
}
 
Example 14
Source File: AbstractTool.java    From shacl with Apache License 2.0 5 votes vote down vote up
protected Model getShapesModel(String[] args) throws IOException {
	for(int i = 0; i < args.length - 1; i++) {
		if(SHAPES_FILE.equals(args[i])) {
			String fileName = args[i + 1];
			OntModel model = ModelFactory.createOntologyModel(spec);
			File file = new File(fileName);
			String lang = file.getName().endsWith(".shaclc") ? SHACLC.langName : FileUtils.langTurtle;
			model.read(new FileInputStream(file), "urn:x:base", lang);
			return model;
		}
	}
	return null;
}
 
Example 15
Source File: AbstractTool.java    From shacl with Apache License 2.0 5 votes vote down vote up
protected Model getDataModel(String[] args) throws IOException {
	for(int i = 0; i < args.length - 1; i++) {
		if(DATA_FILE.equals(args[i])) {
			String dataFileName = args[i + 1];
			OntModel dataModel = ModelFactory.createOntologyModel(spec);
			File file = new File(dataFileName);
			String lang = file.getName().endsWith(".shaclc") ? SHACLC.langName : FileUtils.langTurtle;
			dataModel.read(new FileInputStream(file), "urn:x:base", lang);
			return dataModel;
		}
	}
	System.err.println("Missing -datafile, e.g.: -datafile myfile.ttl");
	System.exit(0);
	return null;
}
 
Example 16
Source File: OntModelWrapper.java    From FCA-Map with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Read model from input stream and acquired the specified instances, properties and classes
 *
 * @param in input stream of model
 */
private void read(InputStream in) {
  if (null == in) return;

  clear();

  m_raw_model.read(in, null);
  m_ontology = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, m_raw_model);

  acquireInstances();

  acquireCategories();

  acquireProperties();

  // XXX: wait to improve
  acquireObjectProperties();
  acquireDatatypeProperties();
  ////////////////////////////

  acquireClasses();

  if (m_logger.isInfoEnabled()) {
    m_logger.info(String.format("# Instances: %8d, # Categories: %8d, # Properties: %8d, # DatatypeProperties: %8d, # ObjectProperties: %8d, # Classes: %8d.",
                  m_instances.size(), m_categories.size(), m_properties.size(), m_datatype_properties.size(), m_object_properties.size(), m_classes.size()));
  }
}
 
Example 17
Source File: OntologyProvider.java    From Processor with Apache License 2.0 4 votes vote down vote up
/**
 * Loads ontology by URI.
 * 
 * @param manager
 * @param ontologyURI ontology location
 * @param ontModelSpec ontology model specification
 * @return ontology model
 */
public static OntModel getOntModel(OntDocumentManager manager, String ontologyURI, OntModelSpec ontModelSpec)
{
    if (manager == null) throw new IllegalArgumentException("OntDocumentManager cannot be null");
    if (ontologyURI == null) throw new IllegalArgumentException("URI cannot be null");
    if (ontModelSpec == null) throw new IllegalArgumentException("OntModelSpec cannot be null");
    if (log.isDebugEnabled()) log.debug("Loading sitemap ontology from URI: {}", ontologyURI);

    try
    {
        OntModel ontModel = manager.getOntology(ontologyURI, ontModelSpec);

        // explicitly loading owl:imports -- workaround for Jena bug: https://issues.apache.org/jira/browse/JENA-1210
        ontModel.enterCriticalSection(Lock.WRITE);
        try
        {
            ontModel.loadImports();
        }
        finally
        {
            ontModel.leaveCriticalSection();
        }

        // lock and clone the model to avoid ConcurrentModificationExceptions
        ontModel.enterCriticalSection(Lock.READ);
        try
        {
            return ModelFactory.createOntologyModel(ontModelSpec,
                    ModelFactory.createUnion(ModelFactory.createDefaultModel(), ontModel.getBaseModel()));
        }
        finally
        {
            ontModel.leaveCriticalSection();
        }
    }
    catch (ClientHandlerException ex) // thrown by DataManager
    {
        // remove ontology from cache, so next time it will be reloaded, possibly with fixed imports
        manager.getFileManager().removeCacheModel(ontologyURI);
        
        if (log.isErrorEnabled()) log.error("Could not load ontology '{}' or its imports", ontologyURI);
        throw new OntologyException("Could not load ontology '" + ontologyURI + "' or its imports", ex);
    }
}
 
Example 18
Source File: PizzaSparqlNoInf.java    From xcurator with Apache License 2.0 4 votes vote down vote up
protected OntModel getModel() {
    return ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
}
 
Example 19
Source File: JenaUtilHelper.java    From shacl with Apache License 2.0 4 votes vote down vote up
public OntModel createOntologyModel(OntModelSpec spec, Model base) {
	return ModelFactory.createOntologyModel(spec, base);
}
 
Example 20
Source File: DumpTestSource.java    From RDFUnit with Apache License 2.0 4 votes vote down vote up
DumpTestSource(SourceConfig sourceConfig, QueryingConfig queryingConfig, Collection<SchemaSource> referenceSchemata, RdfReader dumpReader) {
    this(sourceConfig, queryingConfig, referenceSchemata, dumpReader, ModelFactory.createOntologyModel( OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel()));  //OntModelSpec.RDFS_MEM_RDFS_INF
}