src/main/java/net/timbusproject/dpes/prepare/JenaSparqlExample.java to src/main/java/net/timbusproject/dpes/owlmgr/Main.java
--- a/src/main/java/net/timbusproject/dpes/prepare/JenaSparqlExample.java +++ b/src/main/java/net/timbusproject/dpes/owlmgr/Main.java @@ -1,57 +1,85 @@ -package net.timbusproject.dpes.prepare; +package net.timbusproject.dpes.owlmgr; -import com.hp.hpl.jena.query.*; -import com.hp.hpl.jena.rdf.model.impl.ResourceImpl; -import com.hp.hpl.jena.sparql.engine.http.QueryEngineHTTP; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; -/** - * @author Simon Jupp - * @date 11/09/2013 - * Functional Genomics Group EMBL-EBI - * - * Example of querying the Gene Expression Atlas SPARQL endpoint from Java - * using the Jena API (http://jena.apache.org) - * - */ -public class JenaSparqlExample { - String sparqlEndpoint = "http://www.ebi.ac.uk/rdf/services/atlas/sparql"; +import org.semanticweb.owlapi.model.OWLOntologyCreationException; - // get expression values for uniprot acc Q16850 - String sparqlQuery = "" + - "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + - "PREFIX atlasterms: <http://rdf.ebi.ac.uk/terms/atlas/>" + - "SELECT distinct ?expressionValue ?pvalue \n" + - "WHERE { \n" + - "?value rdfs:label ?expressionValue . \n" + - "?value atlasterms:pValue ?pvalue . \n" + - "?value atlasterms:isMeasurementOf ?probe . \n" + - "?probe atlasterms:dbXref ?uniprotAccession .\n" + - "} \n" + - "ORDER BY ASC(?pvalue)"; +public class Main { + + public static void main(String[] args) throws OWLOntologyCreationException { + + Properties systemSettings = System.getProperties(); + systemSettings.put("http.proxyHost", "proxy-ir.intel.com"); + systemSettings.put("http.proxyPort", "911"); + systemSettings.put("https.proxyHost", "proxy-ir.intel.com"); + systemSettings.put("https.proxyPort", "912"); + System.setProperties(systemSettings); + + SSLTool.disableCertificateValidation(); + + //String ontURI="/home/theguru/downloads/wp7-oswf-characterisation-linux-hardware.owl"; + //String ontURI="http://protege.cim3.net/file/pub/ontologies/travel/travel.owl"; + //String ontURI="https://timbus.teco.edu/public/ontologies/examples/WP7-OSWF-Characterization/wp7-oswf-characterisation-linux-hardware.owl"; + //String ontURI ="https://timbus.teco.edu/public/ontologies/examples/WP7-OSWF-Characterization/wp7-oswf-characterisation-debian-software.rdf"; + String ontURI="https://timbus.teco.edu/public/ontologies/examples/WP8-CAD_CAM/wp8-cadcam-windows-dll.owl"; + OwlManager olMgr = new OwlManager(ontURI); + // =========================================================== // + +// String owlClass ="Package"; +// HashMap<String, String> clsElmt = olMgr.getElementsFromClass(owlClass, olMgr.mainOntology); +// olMgr.printHashMap(clsElmt); + +// String dataProps = olMgr.getDataPropertyFromIndividual( +// "007f333f-cafe-3604-8368-e3923ef67323", +// "http://timbus.teco.edu/ontologies/DSOs/CUDF.owl", "hasSourceLocation"); +// System.out.println("dataProps : "+dataProps); + +// String uri = olMgr.getIndividualURI("fd697ef3-cd95-3b49-82c8-e352fe63f320"); +// System.out.println("getIndividualURI : "+uri); - public JenaSparqlExample() { - // create the Jena query using the ARQ syntax (has additional support for SPARQL federated queries) - Query query = QueryFactory.create(sparqlQuery, Syntax.syntaxARQ) ; - // we want to bind the ?uniprotAccession variable in the query - // to the URI for Q16850 which is http://purl.uniprot.org/uniprot/Q16850 - QuerySolutionMap querySolutionMap = new QuerySolutionMap(); - querySolutionMap.add("uniprotAccession", new ResourceImpl("http://purl.uniprot.org/uniprot/Q16850")); - ParameterizedSparqlString parameterizedSparqlString = new ParameterizedSparqlString(query.toString(), querySolutionMap); + +// String uri = olMgr.getNameAnnotationFromId("fd697ef3-cd95-3b49-82c8-e352fe63f320"); +// System.out.println("getNameAnnotationFromId : "+uri); + +// ArrayList<String> objProp = olMgr.getMultipleObjectPropertyFromIndividualAsStrings("0047f68b-7194-354a-958a-68cda6dbb2e8", +// "http://timbus.teco.edu/ontologies/DSOs/CUDF.owl","hasDependency"); +// for( String str : objProp){ +// System.out.println("ObjectPropertyFromIndividual : "+str); +// } + +// ArrayList<OWLIndividual> objProp = olMgr.getMultipleObjectPropertyFromIndividual("0047f68b-7194-354a-958a-68cda6dbb2e8", +// "http://timbus.teco.edu/ontologies/DSOs/CUDF.owl","hasDependency"); +// System.out.println("getMultipleObjectPropertyFromIndividual : "+objProp.toString()); + + ArrayList<String> objProp = olMgr.getAllIndividualNames(); + for( String name : objProp){ + // System.out.println("getAllIndividualNames : "+name); + +// String dataProps = olMgr.getDataPropertyFromIndividual(name, +// "http://timbus.teco.edu/ontologies/DSOs/CUDF.owl", "hasSourceLocation"); +// System.out.println("dataProps->hasSourceLocation : "+dataProps); + + String dataProps = olMgr.getDataPropertyFromIndividual(name, + "http://timbus.teco.edu/ontologies/DSOs/DLLDSO.owl", "hasLocation"); + System.out.println("dataProps->hasSourceLocation : "+dataProps); + + } +// OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); +// OWLOntology ontology = manager.createOntology(IRI +// .create("http://timbusproject.net/test")); +// OWLNamedIndividual machineNode = createMachineNode(ontology, +// new MachineID().getUUID()); +// System.out.println(machineNode); + } - QueryEngineHTTP httpQuery = new QueryEngineHTTP(sparqlEndpoint,parameterizedSparqlString.asQuery()); - // execute a Select query - ResultSet results = httpQuery.execSelect(); - while (results.hasNext()) { - QuerySolution solution = results.next(); - // get the value of the variables in the select clause - String expressionValue = solution.get("expressionValue").asLiteral().getLexicalForm(); - String pValue = solution.get("pvalue").asLiteral().getLexicalForm(); - // print the output to stdout - System.out.println(expressionValue + "\t" + pValue); - } - } + private void printHashMap(HashMap<String, String> maps){ + System.out.println("Using EntrySet"); + for(Map.Entry<String, String> map : maps.entrySet()){ + System.out.println(map.getKey() +" :: "+ map.getValue()); + } + } - public static void main(String[] args) { - new JenaSparqlExample(); - } -}+}
src/main/java/net/timbusproject/dpes/prepare/SparqlExecutor.java to src/main/java/net/timbusproject/dpes/owlmgr/VPlanAccess.java
--- a/src/main/java/net/timbusproject/dpes/prepare/SparqlExecutor.java +++ b/src/main/java/net/timbusproject/dpes/owlmgr/VPlanAccess.java @@ -1,128 +1,167 @@ -package net.timbusproject.dpes.prepare; +package net.timbusproject.dpes.owlmgr; import java.io.File; - import java.io.InputStream; - import java.util.ArrayList; - import java.util.HashMap; + import java.util.Iterator; + import java.util.LinkedList; import java.util.List; - + import java.util.Set; + import org.apache.log4j.BasicConfigurator; + import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; + import org.semanticweb.owlapi.apibinding.OWLManager; + import org.semanticweb.owlapi.model.IRI; + import org.semanticweb.owlapi.model.OWLClass; + import org.semanticweb.owlapi.model.OWLDataFactory; + import org.semanticweb.owlapi.model.OWLDataPropertyExpression; + import org.semanticweb.owlapi.model.OWLIndividual; + import org.semanticweb.owlapi.model.OWLObjectPropertyExpression; + import org.semanticweb.owlapi.model.OWLOntology; + import org.semanticweb.owlapi.model.OWLOntologyCreationException; + import org.semanticweb.owlapi.model.OWLOntologyManager; + import org.semanticweb.owlapi.model.PrefixManager; + import org.semanticweb.owlapi.util.DefaultPrefixManager; + import uk.ac.manchester.cs.owl.owlapi.OWLDataPropertyImpl; + import uk.ac.manchester.cs.owl.owlapi.OWLObjectPropertyImpl; - import com.hp.hpl.jena.ontology.OntModel; - import com.hp.hpl.jena.ontology.OntModelSpec; - import com.hp.hpl.jena.query.Query; - import com.hp.hpl.jena.query.QueryExecution; - import com.hp.hpl.jena.query.QueryExecutionFactory; - import com.hp.hpl.jena.query.QueryFactory; - import com.hp.hpl.jena.query.ResultSet; - import com.hp.hpl.jena.query.ResultSetFormatter; - import com.hp.hpl.jena.rdf.model.Model; - import com.hp.hpl.jena.rdf.model.ModelFactory; - import com.hp.hpl.jena.util.FileManager; + public class VPlanAccess { - public class SparqlExecutor { + static Logger logger = LogManager.getLogger(VPlanAccess.class.getName()); + // OWL API + private static final String VPLAN = "http://timbus.teco.edu/ontologies/VPlan#"; + OWLOntology ontology; + PrefixManager vplan; + OWLOntologyManager manager; + OWLDataFactory factory; - Logger logger = LogManager.getLogger(SparqlExecutor.class.getName()); + // Mine + private static VPlanAccess vplanAccess = null; - private final File ontology; + private VPlanAccess() { + BasicConfigurator.configure(); + Logger.getRootLogger().setLevel(Level.INFO); - private OntModel model; - - final static String PREFIX = "PREFIX dio: <http://timbus.teco.edu/ontologies/DIO.owl#>\r\n" + - "PREFIX owl: <http://www.w3.org/2002/07/owl#>\r\n" + - "PREFIX vplan: <http://timbus.teco.edu/ontologies/DSOs/VPlan#>\r\n" + - "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\r\n" + - "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\r\n" + - "PREFIX janus: <http://purl.org/net/taverna/janus#>\r\n"; - - public SparqlExecutor(File ontology) { - this.ontology = ontology; - loadModel(); - } - - private void loadModel() { - model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_MICRO_RULE_INF); - InputStream in = FileManager.get().open(ontology.getAbsolutePath()); - model.read(in, null); + manager = OWLManager.createOWLOntologyManager(); + factory = manager.getOWLDataFactory(); } - protected List<String> getQueryResult(Model model, String q) { - String result = null; - Query query = QueryFactory.create(PREFIX + q); - QueryExecution qexec = QueryExecutionFactory.create(query, model); - try { - ResultSet results = qexec.execSelect(); - result = ResultSetFormatter.asXMLString(results); - } finally { - qexec.close(); + public static VPlanAccess getInstance() { + if (vplanAccess == null) { + vplanAccess = new VPlanAccess(); } - return extractPureData(result); + return vplanAccess; + } + + public void setVPlanLocation(File vplanFile) { + ontology = load(vplanFile); + vplan = new DefaultPrefixManager(VPLAN); + } + + public List<String> getMetrics() { + return getIndividualsOfClass("Metric"); } - private List<String> extractPureData(String result) { + public String getSparqlQueryByMetric(String metric) { - // this is a hack. Couldn't find any sutiable formatter in Jena. - List<String> pureDataList = new ArrayList<String>(); + // get capture process for a metric + List<String> captureProcesses = getIndividualsConnectedByObjectProperty(metric, "Metric", "hasCaptureProcess"); - if (result.contains("<literal datatype=\"http://www.w3.org/2001/XMLSchema#string\">")) { - String[] tmp = result.split("<literal datatype=\"http://www.w3.org/2001/XMLSchema#string\">"); - if (tmp.length != 1) { - for (int i = 1; i < tmp.length; i++) { - pureDataList.add(tmp[i].split("</literal>")[0]); - } - } - return pureDataList; + // we assumed that there is always one capture process + String captureProcess = null; + if (captureProcesses == null || captureProcesses.size() == 0) { + return ""; + } - } else if (result.contains("<literal datatype=\"http://www.w3.org/2001/XMLSchema#anyURI\">")) { - String[] tmp = result.split("<literal datatype=\"http://www.w3.org/2001/XMLSchema#anyURI\">"); - if (tmp.length != 1) { - for (int i = 1; i < tmp.length; i++) { - pureDataList.add(tmp[i].split("</literal>")[0]); - } - } - return pureDataList; + captureProcess = captureProcesses.get(0); + // get sparql query for a capture process + String query = getDataPropertiesConnectedByDataProperty(captureProcess, "CaptureProcess", "hasTextDescription"); - } else if (result.contains("<uri>")) { - String[] tmp = result.split("<uri>"); - if (tmp.length != 1) { - for (int i = 1; i < tmp.length; i++) { - pureDataList.add(tmp[i].split("</uri>")[0]); - } - } - return pureDataList; + if (query.equals("[]")) { + logger.error("There is an empty query for " + metric + " Have you defined in the VPlan?"); + throw new NullPointerException("There is no query defined in the VPlan for: " + metric); } - return pureDataList; + + return query.substring(2, query.length() - 2).replace("\\\"", "\""); } - public HashMap<String, List<String>> execute() { + public String getComparatorName(String metric) { + // get capture process for a metric + List<String> auxiliaryResources = getIndividualsConnectedByObjectProperty(metric, "Metric", "hasAuxiliaryResource"); - HashMap<String, List<String>> queryResults = new HashMap<String, List<String>>(); + // we assumed that there is always one auxliary resource + String auxiliaryResource = null; + if (auxiliaryResources == null || auxiliaryResources.size() == 0) { + return "DefaultComparator"; + } + auxiliaryResource = auxiliaryResources.get(0); - VPlanAccess vplanAccess = VPlanAccess.getInstance(); - List<String> metrics = vplanAccess.getMetrics(); - for (String metric : metrics) { - String query = vplanAccess.getSparqlQueryByMetric(metric); - - List<String> result = null; - if(!query.equals("")){ - result = getQueryResult(model, query); - } else { - result = new ArrayList<String>(); - result.add("Empty query"); - } - - queryResults.put(metric, result); - } - - return queryResults; + return getDataPropertiesConnectedByDataProperty(auxiliaryResource, "AuxiliaryResource", "hasTextDescription").split("\"")[1].trim(); } + /** + * Loads ontology from file location + * + * @param file + * @return + */ + private OWLOntology load(File file) { + try { + ontology = manager.loadOntologyFromOntologyDocument(file); + } catch (OWLOntologyCreationException e) { + logger.error(e.getMessage()); + } + logger.info("Loaded ontology: " + ontology); + return ontology; + } + + private List<String> getIndividualsOfClass(String className) { + OWLClass owlClass = factory.getOWLClass(className, vplan); + Set<OWLIndividual> inds = owlClass.getIndividuals(ontology); + + List<String> individuals = new LinkedList<String>(); + Iterator<OWLIndividual> iterator = inds.iterator(); + while (iterator.hasNext()) { + individuals.add(iterator.next().toStringID().split("#")[1]); + } + return individuals; + } + + private List<String> getIndividualsConnectedByObjectProperty(String indiviudal, String classType, String objectProp) { + OWLClass owlClass = factory.getOWLClass(classType, vplan); + Set<OWLIndividual> inds = owlClass.getIndividuals(ontology); + for (OWLIndividual ind : inds) { + if (ind.toString().equals("<" + ontology.getOntologyID().getOntologyIRI().toString() + "#" + indiviudal + ">")) { + OWLObjectPropertyExpression property = new OWLObjectPropertyImpl(IRI.create(VPLAN, objectProp)); + return convertToStringList(ind.getObjectPropertyValues(property, ontology)); + } + } + return null; + } + + private String getDataPropertiesConnectedByDataProperty(String indiviudal, String classType, String dataProp) { + OWLClass owlClass = factory.getOWLClass(classType, vplan); + Set<OWLIndividual> inds = owlClass.getIndividuals(ontology); + for (OWLIndividual ind : inds) { + if (ind.toString().equals("<" + ontology.getOntologyID().getOntologyIRI().toString() + "#" + indiviudal + ">")) { + OWLDataPropertyExpression property = new OWLDataPropertyImpl(IRI.create(VPLAN, dataProp)); + return ind.getDataPropertyValues(property, ontology).toString(); + } + } + return null; + } + + private List<String> convertToStringList(Set<OWLIndividual> individ) { + List<String> individuals = new LinkedList<String>(); + Iterator<OWLIndividual> iterator = individ.iterator(); + while (iterator.hasNext()) { + + individuals.add(iterator.next().toStringID().split("#")[1]); + } + return individuals; + } + } - - -
src/main/java/net/timbusproject/dpes/prepare/VPlanAccess.java to src/main/java/net/timbusproject/dpes/owlmgr/OwlManager.java
--- a/src/main/java/net/timbusproject/dpes/prepare/VPlanAccess.java +++ b/src/main/java/net/timbusproject/dpes/owlmgr/OwlManager.java @@ -1,167 +1,246 @@ -package net.timbusproject.dpes.prepare; - - import java.io.File; - import java.util.Iterator; - import java.util.LinkedList; - import java.util.List; - import java.util.Set; - import org.apache.log4j.BasicConfigurator; - import org.apache.log4j.Level; - import org.apache.log4j.LogManager; - import org.apache.log4j.Logger; - import org.semanticweb.owlapi.apibinding.OWLManager; - import org.semanticweb.owlapi.model.IRI; - import org.semanticweb.owlapi.model.OWLClass; - import org.semanticweb.owlapi.model.OWLDataFactory; - import org.semanticweb.owlapi.model.OWLDataPropertyExpression; - import org.semanticweb.owlapi.model.OWLIndividual; - import org.semanticweb.owlapi.model.OWLObjectPropertyExpression; - import org.semanticweb.owlapi.model.OWLOntology; - import org.semanticweb.owlapi.model.OWLOntologyCreationException; - import org.semanticweb.owlapi.model.OWLOntologyManager; - import org.semanticweb.owlapi.model.PrefixManager; - import org.semanticweb.owlapi.util.DefaultPrefixManager; - import uk.ac.manchester.cs.owl.owlapi.OWLDataPropertyImpl; - import uk.ac.manchester.cs.owl.owlapi.OWLObjectPropertyImpl; - - public class VPlanAccess { - - static Logger logger = LogManager.getLogger(VPlanAccess.class.getName()); - // OWL API - private static final String VPLAN = "http://timbus.teco.edu/ontologies/VPlan#"; - OWLOntology ontology; - PrefixManager vplan; - OWLOntologyManager manager; - OWLDataFactory factory; - - // Mine - private static VPlanAccess vplanAccess = null; - - private VPlanAccess() { - BasicConfigurator.configure(); - Logger.getRootLogger().setLevel(Level.INFO); - - manager = OWLManager.createOWLOntologyManager(); - factory = manager.getOWLDataFactory(); - - } - - public static VPlanAccess getInstance() { - if (vplanAccess == null) { - vplanAccess = new VPlanAccess(); - } - return vplanAccess; - } - - public void setVPlanLocation(File vplanFile) { - ontology = load(vplanFile); - vplan = new DefaultPrefixManager(VPLAN); - } - - public List<String> getMetrics() { - return getIndividualsOfClass("Metric"); - - } - - public String getSparqlQueryByMetric(String metric) { - - // get capture process for a metric - List<String> captureProcesses = getIndividualsConnectedByObjectProperty(metric, "Metric", "hasCaptureProcess"); - - // we assumed that there is always one capture process - String captureProcess = null; - if (captureProcesses == null || captureProcesses.size() == 0) { - return ""; - } - - captureProcess = captureProcesses.get(0); - // get sparql query for a capture process - String query = getDataPropertiesConnectedByDataProperty(captureProcess, "CaptureProcess", "hasTextDescription"); - - if (query.equals("[]")) { - logger.error("There is an empty query for " + metric + " Have you defined in the VPlan?"); - throw new NullPointerException("There is no query defined in the VPlan for: " + metric); - } - - return query.substring(2, query.length() - 2).replace("\\\"", "\""); - - } - - public String getComparatorName(String metric) { - // get capture process for a metric - List<String> auxiliaryResources = getIndividualsConnectedByObjectProperty(metric, "Metric", "hasAuxiliaryResource"); - - // we assumed that there is always one auxliary resource - String auxiliaryResource = null; - if (auxiliaryResources == null || auxiliaryResources.size() == 0) { - return "DefaultComparator"; - } - auxiliaryResource = auxiliaryResources.get(0); - - return getDataPropertiesConnectedByDataProperty(auxiliaryResource, "AuxiliaryResource", "hasTextDescription").split("\"")[1].trim(); - - } - - /** - * Loads ontology from file location - * - * @param file - * @return - */ - private OWLOntology load(File file) { - try { - ontology = manager.loadOntologyFromOntologyDocument(file); - } catch (OWLOntologyCreationException e) { - logger.error(e.getMessage()); - } - logger.info("Loaded ontology: " + ontology); - return ontology; - } - - private List<String> getIndividualsOfClass(String className) { - OWLClass owlClass = factory.getOWLClass(className, vplan); - Set<OWLIndividual> inds = owlClass.getIndividuals(ontology); - - List<String> individuals = new LinkedList<String>(); - Iterator<OWLIndividual> iterator = inds.iterator(); - while (iterator.hasNext()) { - individuals.add(iterator.next().toStringID().split("#")[1]); - } - return individuals; - } - - private List<String> getIndividualsConnectedByObjectProperty(String indiviudal, String classType, String objectProp) { - OWLClass owlClass = factory.getOWLClass(classType, vplan); - Set<OWLIndividual> inds = owlClass.getIndividuals(ontology); - for (OWLIndividual ind : inds) { - if (ind.toString().equals("<" + ontology.getOntologyID().getOntologyIRI().toString() + "#" + indiviudal + ">")) { - OWLObjectPropertyExpression property = new OWLObjectPropertyImpl(IRI.create(VPLAN, objectProp)); - return convertToStringList(ind.getObjectPropertyValues(property, ontology)); - } - } - return null; - } - - private String getDataPropertiesConnectedByDataProperty(String indiviudal, String classType, String dataProp) { - OWLClass owlClass = factory.getOWLClass(classType, vplan); - Set<OWLIndividual> inds = owlClass.getIndividuals(ontology); - for (OWLIndividual ind : inds) { - if (ind.toString().equals("<" + ontology.getOntologyID().getOntologyIRI().toString() + "#" + indiviudal + ">")) { - OWLDataPropertyExpression property = new OWLDataPropertyImpl(IRI.create(VPLAN, dataProp)); - return ind.getDataPropertyValues(property, ontology).toString(); - } - } - return null; - } - - private List<String> convertToStringList(Set<OWLIndividual> individ) { - List<String> individuals = new LinkedList<String>(); - Iterator<OWLIndividual> iterator = individ.iterator(); - while (iterator.hasNext()) { - - individuals.add(iterator.next().toStringID().split("#")[1]); - } - return individuals; - } - +package net.timbusproject.dpes.owlmgr; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import net.timbusproject.dpes.common.InitVariables; + +import org.semanticweb.owlapi.apibinding.OWLManager; +import org.semanticweb.owlapi.model.IRI; +import org.semanticweb.owlapi.model.OWLAnnotation; +import org.semanticweb.owlapi.model.OWLClass; +import org.semanticweb.owlapi.model.OWLClassAssertionAxiom; +import org.semanticweb.owlapi.model.OWLDataFactory; +import org.semanticweb.owlapi.model.OWLDataProperty; +import org.semanticweb.owlapi.model.OWLEntity; +import org.semanticweb.owlapi.model.OWLIndividual; +import org.semanticweb.owlapi.model.OWLLiteral; +import org.semanticweb.owlapi.model.OWLNamedIndividual; +import org.semanticweb.owlapi.model.OWLObjectProperty; +import org.semanticweb.owlapi.model.OWLOntology; +import org.semanticweb.owlapi.model.OWLOntologyCreationException; +import org.semanticweb.owlapi.model.OWLOntologyManager; + +import uk.ac.manchester.cs.owl.owlapi.OWLNamedIndividualImpl; + +public class OwlManager { + + private OWLOntology mainOntology; + private OWLOntologyManager manager; + private OWLDataFactory df; + + + public OwlManager(String ontologyPath) { + OWLManager managerManager = new OWLManager(); + manager = managerManager.buildOWLOntologyManager(); + df = manager.getOWLDataFactory(); + + IRI documentIRI = IRI.create(ontologyPath); + try { + mainOntology = manager.loadOntologyFromOntologyDocument(documentIRI); + } catch (OWLOntologyCreationException e) { + e.printStackTrace(); + } + } + + /** + * Create an {@link OWLNamedIndividual} in the namespace of the given + * {@link OWLOntology} using the identifier + */ + public static OWLNamedIndividual createMachineNode(OWLOntology ontology, + String identifier) { + OWLDataFactory dataFactory = ontology.getOWLOntologyManager() + .getOWLDataFactory(); + IRI nodeIRI = IRI.create(ontology.getOntologyID().getOntologyIRI() + + "#" + identifier); + OWLNamedIndividualImpl node = new OWLNamedIndividualImpl(nodeIRI); + // assign it to be of class Node + OWLClass nodeClass = dataFactory.getOWLClass(IRI + .create("http://timbus.teco.edu/ontologies/DIO.owl#Node")); + OWLClassAssertionAxiom classAssertion = dataFactory + .getOWLClassAssertionAxiom(nodeClass, node); + ontology.getOWLOntologyManager().addAxiom(ontology, classAssertion); + return node; } + + public HashMap<String, String> getElementsFromClass(String className, OWLOntology mainOntology ) { + HashMap<String, String> individuals = new HashMap<String, String>(); + + for (OWLEntity claz : mainOntology.getClassesInSignature()) { + String name=getIndividualNameFromURI(claz.getIRI().toString()); + if (claz.isOWLClass() && getIndividualNameFromURI(claz.getIRI().toString()).equals(className)) { + for (OWLIndividual ind : claz.asOWLClass().getIndividuals(mainOntology)) { + Object[] anot = ind.asOWLNamedIndividual().getAnnotations(mainOntology).toArray(); + if (anot != null && anot.length > 0 && ((OWLAnnotation) anot[0]).getValue() != null && ((OWLAnnotation) anot[0]).getValue().toString() != "") + individuals.put(getIndividualNameFromURI(ind.toString()), getNameFromLabel(((OWLAnnotation) anot[0]).getValue().toString())); + else + individuals.put(getIndividualNameFromURI(ind.toString()), getIndividualNameFromURI(ind.toString())); + } + break; + } + } + return individuals; + } + + public String getDataPropertyFromIndividual(String id, String prefix, String property) { + for (OWLEntity claz : mainOntology.getClassesInSignature()) { + if (claz.isOWLClass()) { + for (OWLIndividual ind : claz.asOWLClass().getIndividuals(mainOntology)) { + String cutIndividual = getIndividualNameFromURI(ind.toString()); + if (cutIndividual.equals(id)) { + OWLDataProperty prop = df.getOWLDataProperty(IRI.create(prefix + "#", property)); + + Set<OWLLiteral> props = ind.asOWLNamedIndividual().getDataPropertyValues(prop, mainOntology); + ArrayList<OWLLiteral> propss = new ArrayList<OWLLiteral>(props); + if (props.size() != 0) + return propss.get(0).getLiteral(); + else + return null; + } + } + } + } + for (OWLOntology ont : mainOntology.getImports()) + for (OWLEntity claz : ont.getClassesInSignature()) { + if (claz.isOWLClass()) { + for (OWLIndividual ind : claz.asOWLClass().getIndividuals(ont)) { + if (getIndividualNameFromURI(ind.toString()).equals(id)) { + OWLDataProperty prop = df.getOWLDataProperty(IRI.create(prefix + "#", property)); + Set<OWLLiteral> props = ind.asOWLNamedIndividual().getDataPropertyValues(prop, ont); + ArrayList<OWLLiteral> propss = new ArrayList<OWLLiteral>(props); + if (props.size() != 0) + return propss.get(0).getLiteral(); + else + return null; + } + } + } + } + return null; + } + + public String getIndividualURI(String id) { + for (OWLEntity claz : mainOntology.getClassesInSignature()) { + if (claz.isOWLClass()) { + for (OWLIndividual ind : claz.asOWLClass().getIndividuals(mainOntology)) { + if (getIndividualNameFromURI(ind.toString()).equals(id)) { + return ind.toStringID(); + } + } + } + } + for (OWLOntology ont : mainOntology.getImports()) + for (OWLEntity claz : ont.getClassesInSignature()) { + if (claz.isOWLClass()) { + for (OWLIndividual ind : claz.asOWLClass().getIndividuals(ont)) { + if (getIndividualNameFromURI(ind.toString()).equals(id)) { + return ind.toStringID(); + } + } + } + } + return null; + } + + public String getNameAnnotationFromId(String id) { + for (OWLEntity claz : mainOntology.getClassesInSignature()) { + if (claz.isOWLClass()) { + for (OWLIndividual ind : claz.asOWLClass().getIndividuals(mainOntology)) { + if (getIndividualNameFromURI(ind.toString()).equals(id)) { + OWLAnnotation anot = (OWLAnnotation) (ind.asOWLNamedIndividual().getAnnotations(mainOntology).toArray()[0]); + if (anot.getValue() != null && anot.getValue().toString() != "") + return getNameFromLabel(anot.getValue().toString()); + } + } + } + } + for (OWLOntology ont : mainOntology.getImports()) + for (OWLEntity claz : ont.getClassesInSignature()) { + if (claz.isOWLClass()) { + for (OWLIndividual ind : claz.asOWLClass().getIndividuals(ont)) { + if (getIndividualNameFromURI(ind.toString()).equals(id)) { + OWLAnnotation anot = (OWLAnnotation) (ind.asOWLNamedIndividual().getAnnotations(ont).toArray()[0]); + if (anot.getValue() != null && anot.getValue().toString() != "") + return getNameFromLabel(anot.getValue().toString()); + } + } + } + } + return null; + } + + public ArrayList<String> getMultipleObjectPropertyFromIndividualAsStrings(String id, String prefix, String property) { + ArrayList<OWLIndividual> list = getMultipleObjectPropertyFromIndividual(id, prefix, property); + ArrayList<String> stringList = new ArrayList<String>(); + if (list != null) + for (OWLIndividual ind : list) + stringList.add(getIndividualNameFromURI(ind.toString())); + return stringList; + } + + public String getObjectPropertyFromIndividual(String id, String prefix, String property) { + ArrayList<String> list = getMultipleObjectPropertyFromIndividualAsStrings(id, prefix, property); + if (list.size() != 0) + return list.get(0); + else + return null; + } + + public ArrayList<OWLIndividual> getMultipleObjectPropertyFromIndividual(String id, String prefix, String property) { + ArrayList<OWLIndividual> listt = new ArrayList<OWLIndividual>(); + for (OWLEntity claz : mainOntology.getClassesInSignature()) { + if (claz.isOWLClass()) { + for (OWLIndividual ind : claz.asOWLClass().getIndividuals(mainOntology)) { + String cutIndividual = getIndividualNameFromURI(ind.toString()); + if (cutIndividual.equals(id)) { + OWLObjectProperty prop = df.getOWLObjectProperty(IRI.create(prefix + "#", property)); + Set<OWLIndividual> props = ind.asOWLNamedIndividual().getObjectPropertyValues(prop, mainOntology); + listt.addAll(props); + } + } + } + } + for (OWLOntology ont : mainOntology.getImports()) + for (OWLEntity claz : ont.getClassesInSignature()) { + if (claz.isOWLClass()) { + for (OWLIndividual ind : claz.asOWLClass().getIndividuals(ont)) { + String cutIndividual = getIndividualNameFromURI(ind.toString()); + if (cutIndividual.equals(id)) { + OWLObjectProperty prop = df.getOWLObjectProperty(IRI.create(prefix + "#", property)); + Set<OWLIndividual> props = ind.asOWLNamedIndividual().getObjectPropertyValues(prop, ont); + listt.addAll(props); + } + } + } + } + return listt; + } + + public ArrayList<String> getAllIndividualNames() { + ArrayList<String> listt = new ArrayList<String>(); + for (OWLEntity claz : mainOntology.getClassesInSignature()) { + if (claz.isOWLClass()) { + for (OWLIndividual ind : claz.asOWLClass().getIndividuals(mainOntology)) { + String cutIndividual = getIndividualNameFromURI(ind.toString()); + listt.add(cutIndividual); + } + } + } + return listt; + } + + private String getIndividualNameFromURI(String uri) { + String temp = uri.split("#")[1]; + if (uri.endsWith(">")) + return temp.substring(0, temp.length() - 1); + else + return temp; + } + + private String getNameFromLabel(String name) { + return name.substring(1).split("\"")[0]; + } +}