com.hp.hpl.jena.ontology.OntModel Java Examples

The following examples show how to use com.hp.hpl.jena.ontology.OntModel. 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: ExportService.java    From semanticMDR with GNU General Public License v3.0 6 votes vote down vote up
@GET
public Response export(@Context Request request,
		@PathParam("exporterType") String exporterType) {

	logger.info("Exporting database");

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();

	graphStream.setModel(ontModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(exporterType));

	logger.info("Database is exported");

	String fileName = fileNames.get(exporterType);
	if (fileName == null) {
		fileName = "export.rdf";
	}

	return Response
			.ok(graphStream)
			.header("Content-Disposition",
					"attachment; filename=" + fileName).build();
}
 
Example #2
Source File: MDRDatabase.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
/**
 * MDRDatabase is based upon an ontology which keeps definitions and
 * Elements of the MetaDataRepository. Apart form backend, this ontology is
 * managed as on Jena {@link OntModel}
 * 
 * @return {@link OntModel} representation of MDR Ontology.
 */
public OntModel getOntModel() {
	if (this.ontModel == null) {
		logger.error("OntModel of the MDRDatabase is null.");
		throw new IllegalStateException(
				"OntModel of the MDRDatabase cannot be null.");
	}
	return this.ontModel;
}
 
Example #3
Source File: VirtuosoQueryFactory.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected QueryExecution createQueryExecution(String queryString,
		OntModel ontModel) {
	return VirtuosoQueryExecutionFactory.create(queryString,
			(VirtGraph) this.mdrDatabase.getJenaStore().getGraph());

}
 
Example #4
Source File: JenaUtils.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public static List<Statement> getBestMatchingStatements(OntModel ontology, StringMetric metric, String term) {
    StmtIterator iter
            = ontology.listStatements(new SimpleSelector(null, RDFS.label, (RDFNode) null));

    double maxSimilarity = Double.MIN_VALUE;
    List<Statement> bestChoices = new LinkedList<Statement>();

    while (iter.hasNext()) {
        Statement st = iter.next();
        String objectStr = st.getObject().asLiteral().getString();

        double similarity = metric.getSimilarity(term, objectStr);

        if (similarity <= 0) {
            continue;
        }

        if (similarity > maxSimilarity) {
            maxSimilarity = similarity;
            bestChoices.clear();
        } else if (similarity == maxSimilarity) {
            bestChoices.add(st);
        }
    }

    return bestChoices;
}
 
Example #5
Source File: SPARQLService.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Runs SPARQL queries
 * 
 * @param type
 *            Result Format: N3, N-TRIPLE, RDF/XML, RDF/XML-ABBREV, TURTLE
 * @param query
 *            Sparql for the query
 * @return
 */
@GET
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response selectQuery(@QueryParam("sparql") String query,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();
	Query q = null;

	try {
		query = URLDecoder.decode(query, "UTF-8");
		q = QueryFactory.create(query);
	} catch (Exception exc) {
		logger.error("Error during the creation of the SPARQL query", exc);
		return Response.serverError().build();
	}

	QueryExecution qexec = QueryExecutionFactory.create(q, ontModel);
	Model resultModel = null;
	if (q.isSelectType()) {
		ResultSet resultSet = qexec.execSelect();
		resultModel = ResultSetFormatter.toModel(resultSet);
	} else {
		throw new WebApplicationException(Status.UNAUTHORIZED);
	}
	qexec.close();

	graphStream.setModel(resultModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example #6
Source File: SerializationService.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("/dex")
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response dexSerialization(@QueryParam("id") String uuid,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();
	String queryString;

	File file = new File(
			"../web/src/main/resources/rest/dex-serialization-query.rq");
	try {
		queryString = FileUtils.readFileToString(file);
	} catch (IOException e) {
		logger.error("File with dex serialization query could not be found ");
		return Response.serverError().build();
	}

	ParameterizedSparqlString query = new ParameterizedSparqlString(
			queryString);
	query.setLiteral("uuid", ResourceFactory.createTypedLiteral(uuid));
	QueryExecution qe = QueryExecutionFactory.create(query.asQuery(),
			ontModel);
	Model resultModel = qe.execConstruct();

	graphStream.setModel(resultModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example #7
Source File: ContextService.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("/all")
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response getAllContexts(@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();

	String queryString;
	File file = new File(QUERY_FILE_GET_ALL_CONTEXTS);
	try {
		queryString = FileUtils.readFileToString(file);
	} catch (IOException e) {
		logger.error("File with context serialization query could not be found ");
		return Response.serverError().build();
	}

	ParameterizedSparqlString query = new ParameterizedSparqlString(
			queryString);
	QueryExecution qe = QueryExecutionFactory.create(query.asQuery(),
			ontModel);
	Model resultModel = qe.execConstruct();

	graphStream.setModel(resultModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example #8
Source File: ContextService.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("/{contextid}/de")
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response getDataElements(@PathParam("contextid") String contextId,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();

	String queryString;
	File file = new File(QUERY_FILE_GET_ALL_FROM_CONTEXT);
	try {
		queryString = FileUtils.readFileToString(file);
	} catch (IOException e) {
		logger.error("File with context serialization query could not be found ");
		return Response.serverError().build();
	}

	ParameterizedSparqlString query = new ParameterizedSparqlString(
			queryString);
	query.setLiteral("uuid", ResourceFactory.createTypedLiteral(contextId));
	QueryExecution qe = QueryExecutionFactory.create(query.asQuery(),
			ontModel);
	Model resultModel = qe.execConstruct();

	graphStream.setModel(resultModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example #9
Source File: SerializationService.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 
 * @param type
 *            outputFormat "N3", "N-TRIPLE", "RDF/XML-ABBREV" or
 *            "TURTLE"default: "RDF/XML".
 * @param uuid
 * @return
 */
@GET
@Path("/graph")
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response serialize(@QueryParam("id") String uuid, @QueryParam("uri") String uri,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();
	
	String query = "";
	if(uuid != null) {
		// get the uri of the resource
		query = "prefix mdr:     <http://www.salusproject.eu/iso11179-3/mdr#> "
				+ "prefix xsd:     <http://www.w3.org/2001/XMLSchema#> "
				+ "SELECT ?resource WHERE { " + "?resource ?op ?ar . "
				+ "?ar mdr:administeredItemIdentifier ?ii . "
				+ "?ii mdr:dataIdentifier \"" + uuid + "\"^^xsd:string. " + "}";

		logger.debug("Query execution: {}", query);
		Query q = QueryFactory.create(query);
		QueryExecution qe = QueryExecutionFactory.create(q, ontModel);
		ResultSet rs = qe.execSelect();

		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			uri = qs.getResource("resource").getURI();
		}
	}

	if(uri == null) {
		throw new WebApplicationException(Response.Status.BAD_REQUEST);
	}
	
	// use the uri to construct the model and return its serialization.
	query = "CONSTRUCT WHERE { <" + uri + "> ?p ?o .}";
	Query q2 = QueryFactory.create(query);
	QueryExecution qe2 = QueryExecutionFactory.create(q2, ontModel);
	Model outModel = qe2.execConstruct();

	graphStream.setModel(outModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example #10
Source File: OwlReader.java    From EventCoreference with Apache License 2.0 4 votes vote down vote up
static void readOwlFile (String pathToOwlFile) {
        OntModel ontologyModel =
                ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
        ontologyModel.read(pathToOwlFile, "RDF/XML-ABBREV");
       // OntClass myClass = ontologyModel.getOntClass("namespace+className");

        OntClass myClass = ontologyModel.getOntClass(ResourcesUri.nwr+"domain-ontology#Motion");
        System.out.println("myClass.toString() = " + myClass.toString());
        System.out.println("myClass.getSuperClass().toString() = " + myClass.getSuperClass().toString());

        //List list =
              //  namedHierarchyRoots(ontologyModel);


       Iterator i = ontologyModel.listHierarchyRootClasses()
                .filterDrop( new Filter() {
                    public boolean accept( Object o ) {
                        return ((Resource) o).isAnon();
                    }} ); ///get all top nodes and excludes anonymous classes

       // Iterator i = ontologyModel.listHierarchyRootClasses();
        while (i.hasNext()) {
            System.out.println(i.next().toString());
/*            OntClass ontClass = ontologyModel.getOntClass(i.next().toString());
            if (ontClass.hasSubClass()) {

            }*/
        }

        String q = createSparql("event", "<http://www.newsreader-project.eu/domain-ontology#Motion>");
        System.out.println("q = " + q);
        QueryExecution qe = QueryExecutionFactory.create(q,
                ontologyModel);
        for (ResultSet rs = qe.execSelect() ; rs.hasNext() ; ) {
            QuerySolution binding = rs.nextSolution();
            System.out.println("binding = " + binding.toString());
            System.out.println("Event: " + binding.get("event"));
        }

        ontologyModel.close();
    }
 
Example #11
Source File: TDBQueryFactory.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected QueryExecution createQueryExecution(String queryString,
		OntModel ontModel) {
	return QueryExecutionFactory.create(queryString,
			this.mdrDatabase.getOntModel());
}
 
Example #12
Source File: ResourceQueryFactory.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
abstract protected QueryExecution createQueryExecution(String queryString,
OntModel ontModel);
 
Example #13
Source File: MDRResourceFactory.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @return The associated {@link OntModel}.
 */
public OntModel getOntModel() {
	return this.ontModel;
}
 
Example #14
Source File: DataElementService.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
@GET
@Path("/{deid}/es")
@Produces(MediaType.APPLICATION_JSON)
public Response getExtractionSpec(
		@QueryParam("specification-format") String specificationFormat,
		@QueryParam("content-model") String contentModel,
		@PathParam("deid") String deid) {
	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();
	List<String> extractionSpecifications = new ArrayList<String>();

	if (specificationFormat == null || contentModel == null) {
		throw new WebApplicationException(Status.NOT_ACCEPTABLE);
	}

	File getExtractionFile = new File(QUERY_FILE_GET_EXTRACTIONS);
	String queryString = "";
	try {
		queryString = FileUtils.readFileToString(getExtractionFile);
	} catch (IOException e) {
		logger.error("File with context serialization query could not be found ");
		return Response.serverError().build();
	}
	ParameterizedSparqlString query = new ParameterizedSparqlString(
			queryString);
	query.setLiteral("uuid", ResourceFactory.createTypedLiteral(deid));
	query.setLiteral("specFormat",
			ResourceFactory.createTypedLiteral(specificationFormat));
	query.setLiteral("contentModel",
			ResourceFactory.createTypedLiteral(contentModel));
	QueryExecution qe = QueryExecutionFactory.create(query.asQuery(),
			ontModel);

	String spec = "";
	ResultSet rs = qe.execSelect();
	while (rs.hasNext()) {
		QuerySolution qs = rs.next();
		spec = qs.getLiteral("extractionSpec").getString();
		if (spec != null && !spec.equals("")) {
			extractionSpecifications.add(spec);
		}
	}

	return Response.ok(extractionSpecifications).build();
}
 
Example #15
Source File: JenaUtils.java    From xcurator with Apache License 2.0 4 votes vote down vote up
public static OntModel loadOntology(InputStream is) {
    OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_LITE_MEM);
    m.read(is, null);
    return m;
}
 
Example #16
Source File: WP2ModelFactory.java    From GeoTriples with Apache License 2.0 3 votes vote down vote up
/**
 * <p>
 * Answer a new ontology model which will process in-memory models of
 * ontologies expressed the default ontology language (OWL).
 * The default document manager
 * will be used to load the ontology's included documents.
 * </p>
 *
 * @param spec An ontology model specification that defines the language and reasoner to use
 * @param maker A model maker that is used to get the initial store for the ontology (unless
 * the base model is given),
 * and create addtional stores for the models in the imports closure
 * @param base The base model, which contains the contents of the ontology to be processed
 * @return A new ontology model
 * @see OntModelSpec
 */
public static OntModel createOntologyModel( OntModelSpec spec, ModelMaker maker, Model base ) {
    OntModelSpec _spec = new OntModelSpec( spec );
    _spec.setImportModelMaker( maker );

    return createOntologyModel( _spec, base );
}
 
Example #17
Source File: WP2ModelFactory.java    From GeoTriples with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Answer a new ontology model which will process in-memory models of
 * ontologies expressed the default ontology language (OWL).
 * The default document manager
 * will be used to load the ontology's included documents.
 * </p>
 * <p><strong>Note:</strong>The default model chosen for OWL and RDFS
 * includes a weak reasoner that includes some entailments (such as
 * transitive closure on the sub-class and sub-property hierarchies). Users
 * who want either no inference at all, or alternatively
 * more complete reasoning, should use
 * one of the other <code>createOntologyModel</code> methods that allow the
 * preferred OntModel specification to be stated.</p>
 * @return A new ontology model
 * @see OntModelSpec#getDefaultSpec
 * @see #createOntologyModel(OntModelSpec, Model)
 */
public static OntModel createOntologyModel() {
    return createOntologyModel( ProfileRegistry.OWL_LANG );
}
 
Example #18
Source File: WP2ModelFactory.java    From GeoTriples with Apache License 2.0 2 votes vote down vote up
/**
 * Answer a new ontology model constructed according to the specification, which includes
 * a ModelMaker which will create the necessary base model.
*/
public static OntModel createOntologyModel( OntModelSpec spec )
    { return new OntModelImpl( spec ); }
 
Example #19
Source File: WP2ModelFactory.java    From GeoTriples with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Answer a new ontology model, constructed according to the given ontology model specification,
 * and starting with the ontology data in the given model.
 * </p>
 *
 * @param spec An ontology model specification object, that will be used to construct the ontology
 * model with different options of ontology language, reasoner, document manager and storage model
 * @param base An existing model to treat as an ontology model, or null.
 * @return A new ontology model
 * @see OntModelSpec
 */
public static OntModel createOntologyModel( OntModelSpec spec, Model base ) {
    return new OntModelImpl( spec, base );
}
 
Example #20
Source File: WP2ModelFactory.java    From GeoTriples with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Answer a new ontology model which will process in-memory models of
 * ontologies in the given language.
 * The default document manager
 * will be used to load the ontology's included documents.
 * </p>
 *
 * @param languageURI The URI specifying the ontology language we want to process
 * @return A new ontology model
 * @see OntModelSpec#getDefaultSpec
 */
public static OntModel createOntologyModel( String languageURI ) {
    return createOntologyModel( OntModelSpec.getDefaultSpec( languageURI ), null );
}