From 604bc8db29f5ee9698bfdb86a8bc80e1f191ff3c Mon Sep 17 00:00:00 2001 From: Christopher Weedall <5010253+cweedall@users.noreply.github.com> Date: Thu, 9 May 2024 14:53:20 -0500 Subject: [PATCH 01/10] clean up spacing and indents for RestrictionVisitor --- .../java/edu/isi/oba/RestrictionVisitor.java | 275 +++++++++--------- 1 file changed, 141 insertions(+), 134 deletions(-) diff --git a/src/main/java/edu/isi/oba/RestrictionVisitor.java b/src/main/java/edu/isi/oba/RestrictionVisitor.java index 406dd6d..9da893b 100644 --- a/src/main/java/edu/isi/oba/RestrictionVisitor.java +++ b/src/main/java/edu/isi/oba/RestrictionVisitor.java @@ -32,7 +32,7 @@ * will be used to map the ObjectProperties its the corresponding Schema. * - propertiesFromDataRestrictions -> contains all the restricted OWLDataProperties * - propertiesFromDataRestrictions_ranges -> contains the ranges of each data property restriction - * - valuesFromDataRestrictions_ranges -> contains the range values of data restrictions. e.g. oneOf values. + * - valuesFromDataRestrictions_ranges -> contains the range values of data restrictions. e.g. oneOf values. */ public class RestrictionVisitor implements OWLObjectVisitor { @@ -56,10 +56,10 @@ public class RestrictionVisitor implements OWLObjectVisitor { processedClasses = new HashSet(); this.cls = visitedClass; this.onto = onto; - this.property_name = propertyName; - this.owlThing = owlThing; + this.property_name = propertyName; + this.owlThing = owlThing; this.propertiesFromObjectRestrictions_ranges= new HashMap<>(); - this.propertiesFromObjectRestrictions = new ArrayList<>(); + this.propertiesFromObjectRestrictions = new ArrayList<>(); this.restrictionsValuesFromClass = new HashMap<>(); this.propertiesFromDataRestrictions = new ArrayList<>(); this.propertiesFromDataRestrictions_ranges= new HashMap<>(); @@ -74,12 +74,12 @@ public void visit(OWLClass ce) { this.processedClasses.add(ce); for (OWLSubClassOfAxiom ax: this.onto.getSubClassAxiomsForSubClass(ce)) { ax.getSuperClass().accept(this); - } + } } } @Override - public void visit( OWLEquivalentClassesAxiom ce ) { + public void visit( OWLEquivalentClassesAxiom ce ) { logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); // If equivalent class axiom AND contains owl:oneOf, then we're looking at an ENUM class. @@ -109,9 +109,9 @@ public void visit(OWLObjectSomeValuesFrom ce) { Map restrictionsValues = new HashMap<>(); logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - for(OWLObjectProperty property: ce.getObjectPropertiesInSignature()) { + for (OWLObjectProperty property: ce.getObjectPropertiesInSignature()) { this.propertiesFromObjectRestrictions.add(property); - this.property_name = this.sfp.getShortForm(property.getIRI()); + this.property_name = this.sfp.getShortForm(property.getIRI()); } OWLClassExpression ceFiller = ce.getFiller(); @@ -145,28 +145,29 @@ public void visit(OWLObjectSomeValuesFrom ce) { public void visit(OWLObjectAllValuesFrom ce) { logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); Map restrictionsValues = new HashMap<>(); - for(OWLObjectProperty property:ce.getObjectPropertiesInSignature()) { + for (OWLObjectProperty property:ce.getObjectPropertiesInSignature()) { propertiesFromObjectRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); + property_name = sfp.getShortForm(property.getIRI()); } + if (ce.getFiller() instanceof OWLObjectUnionOf || ce.getFiller() instanceof OWLObjectIntersectionOf) { ce.getFiller().accept(this); - } else { + } else { List ranges = new ArrayList<>(); ranges.add(sfp.getShortForm(ce.getFiller().asOWLClass().getIRI())); if (ce.getFiller().asOWLClass().equals(owlThing)) { - logger.info("Ignoring owl:Thing range" + property_name); + logger.info("Ignoring owl:Thing range" + property_name); } else { propertiesFromObjectRestrictions_ranges.put(property_name, ranges); } - restrictionsValues.put("allValuesFrom", ""); + restrictionsValues.put("allValuesFrom", ""); restrictionsValuesFromClass.put(property_name, restrictionsValues); } } @Override - public void visit( OWLObjectUnionOf ce ) { + public void visit(OWLObjectUnionOf ce) { logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); // Loop through each item in the union and accept visits. @@ -174,8 +175,9 @@ public void visit( OWLObjectUnionOf ce ) { e.accept(this); } } + @Override - public void visit( OWLObjectIntersectionOf ce ) { + public void visit(OWLObjectIntersectionOf ce) { logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); // Loop through each item in the intersection and accept visits. @@ -185,28 +187,29 @@ public void visit( OWLObjectIntersectionOf ce ) { } @Override - public void visit( OWLObjectMinCardinality ce ) { + public void visit(OWLObjectMinCardinality ce) { logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); setPropertiesWithCardinality(ce, "minCardinality"); - } + @Override - public void visit( OWLObjectMaxCardinality ce ) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); - setPropertiesWithCardinality(ce,"maxCardinality") ; - } + public void visit(OWLObjectMaxCardinality ce) { + logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + setPropertiesWithCardinality(ce,"maxCardinality"); + } + @Override - public void visit( OWLObjectExactCardinality ce ) { + public void visit(OWLObjectExactCardinality ce) { logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); - setPropertiesWithCardinality(ce, "exactCardinality") ; + setPropertiesWithCardinality(ce, "exactCardinality"); } @Override - public void visit( OWLObjectComplementOf ce ) { + public void visit(OWLObjectComplementOf ce) { logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); Map restrictionsValues = new HashMap(); - String complementName = this.sfp.getShortForm(ce.getOperand().asOWLClass().getIRI()); - restrictionsValues.put("complementOf", complementName ); + String complementName = this.sfp.getShortForm(ce.getOperand().asOWLClass().getIRI()); + restrictionsValues.put("complementOf", complementName ); restrictionsValuesFromClass.put("complementOf", restrictionsValues); } @@ -214,7 +217,7 @@ public void visit( OWLObjectComplementOf ce ) { public void visit(OWLObjectHasValue ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - for(OWLObjectProperty property: ce.getObjectPropertiesInSignature()) { + for (OWLObjectProperty property: ce.getObjectPropertiesInSignature()) { List ranges = new ArrayList(); Map restrictionsValues = new HashMap(); @@ -242,7 +245,7 @@ public void visit(OWLObjectHasValue ce) { } @Override - public void visit( OWLObjectOneOf ce ) { + public void visit(OWLObjectOneOf ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); List ranges = new ArrayList(); Map restrictionsValues = new HashMap(); @@ -263,26 +266,27 @@ public void visit( OWLObjectOneOf ce ) { * (allValuesFrom) restriction and it asks us to visit it */ @Override - public void visit( OWLDataAllValuesFrom ce ) { + public void visit(OWLDataAllValuesFrom ce) { logger.info( "\n Analyzed Class: " + this.cls+ " with axiom: "+ce); Map restrictionsValues = new HashMap(); - for(OWLDataProperty property:ce.getDataPropertiesInSignature()) { + for (OWLDataProperty property:ce.getDataPropertiesInSignature()) { propertiesFromDataRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); + property_name = sfp.getShortForm(property.getIRI()); } + if (ce.getFiller() instanceof OWLDataUnionOf || ce.getFiller() instanceof OWLDataIntersectionOf) { ce.getFiller().accept(this); - } else { + } else { List ranges = new ArrayList(); ranges.add(sfp.getShortForm(ce.getFiller().asOWLDatatype().getIRI())); if (ce.getFiller().asOWLDatatype().equals(owlThing)) { - logger.info("Ignoring owl:Thing range" + property_name); + logger.info("Ignoring owl:Thing range" + property_name); + } else { + propertiesFromDataRestrictions_ranges.put(property_name,ranges); } - else - propertiesFromDataRestrictions_ranges.put(property_name,ranges); - restrictionsValues.put("allValuesFrom", ""); - restrictionsValuesFromClass.put(property_name, restrictionsValues); + restrictionsValues.put("allValuesFrom", ""); + restrictionsValuesFromClass.put(property_name, restrictionsValues); } } @@ -291,28 +295,28 @@ public void visit( OWLDataAllValuesFrom ce ) { * (someValuesFrom) restriction and it asks us to visit it */ @Override - public void visit( OWLDataSomeValuesFrom ce ) { + public void visit(OWLDataSomeValuesFrom ce) { logger.info( "\n Analyzed Class: " + this.cls + " with axiom: " + ce); Map restrictionsValues = new HashMap(); - for(OWLDataProperty property: ce.getDataPropertiesInSignature()) { + for (OWLDataProperty property: ce.getDataPropertiesInSignature()) { this.propertiesFromDataRestrictions.add(property); this.property_name = this.sfp.getShortForm(property.getIRI()); } OWLDataRange ceFiller = ce.getFiller(); if (ceFiller instanceof OWLDataUnionOf || ceFiller instanceof OWLDataIntersectionOf) { - restrictionsValues.put("someValuesFrom", ""); + restrictionsValues.put("someValuesFrom", ""); this.restrictionsValuesFromClass.put(property_name, restrictionsValues); ce.getFiller().accept(this); - } else { + } else { List ranges = new ArrayList(); ranges.add(this.sfp.getShortForm(ceFiller.asOWLDatatype().getIRI())); if (ceFiller.asOWLDatatype().equals(owlThing)) { - logger.info("Ignoring owl:Thing range" + property_name); + logger.info("Ignoring owl:Thing range" + property_name); } else { - propertiesFromDataRestrictions_ranges.put(property_name, ranges); - } + propertiesFromDataRestrictions_ranges.put(property_name, ranges); + } restrictionsValues.put("someValuesFrom", ""); this.restrictionsValuesFromClass.put(property_name, restrictionsValues); @@ -320,7 +324,7 @@ public void visit( OWLDataSomeValuesFrom ce ) { } @Override - public void visit( OWLDataUnionOf ce ) { + public void visit(OWLDataUnionOf ce) { logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); // Loop through each item in the union and accept visits. @@ -330,7 +334,7 @@ public void visit( OWLDataUnionOf ce ) { } @Override - public void visit( OWLDataIntersectionOf ce ) { + public void visit(OWLDataIntersectionOf ce) { logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); // Loop through each item in the intersection and accept visits. @@ -340,26 +344,26 @@ public void visit( OWLDataIntersectionOf ce ) { } @Override - public void visit( OWLDataMinCardinality ce ) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + public void visit(OWLDataMinCardinality ce) { + logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); setDataPropertiesWithCardinality(ce,"minCardinality"); } @Override - public void visit( OWLDataMaxCardinality ce ) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + public void visit(OWLDataMaxCardinality ce) { + logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); setDataPropertiesWithCardinality(ce,"maxCardinality"); - } + } @Override - public void visit( OWLDataExactCardinality ce ) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + public void visit(OWLDataExactCardinality ce) { + logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); setDataPropertiesWithCardinality(ce,"exactCardinality"); } @Override - public void visit( OWLDataOneOf ce ) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); + public void visit(OWLDataOneOf ce) { + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); List ranges = new ArrayList(); Map restrictionsValues = new HashMap(); @@ -373,10 +377,10 @@ public void visit( OWLDataOneOf ce ) { } @Override - public void visit( OWLDataComplementOf ce ) { + public void visit(OWLDataComplementOf ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); List ranges = new ArrayList(); - Map restrictionsValues = new HashMap(); + Map restrictionsValues = new HashMap(); for (OWLDatatype value: ce.getDatatypesInSignature()) { ranges.add(this.sfp.getShortForm(value.getIRI())); restrictionsValues.put("complementOf", ""); @@ -386,11 +390,11 @@ public void visit( OWLDataComplementOf ce ) { } @Override - public void visit( OWLDataHasValue ce ) { + public void visit(OWLDataHasValue ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); List ranges = new ArrayList(); Map restrictionsValues = new HashMap(); - for(OWLDataProperty property: ce.getDataPropertiesInSignature()) { + for (OWLDataProperty property: ce.getDataPropertiesInSignature()) { property_name = this.sfp.getShortForm(property.getIRI()); propertiesFromDataRestrictions.add(property); restrictionsValues.put("dataHasValue", ce.getFiller().getLiteral()); @@ -409,18 +413,19 @@ public void visit( OWLDataHasValue ce ) { * @param restriction string value of restriction e.g. "exactCardinality" */ public void setPropertiesWithCardinality(OWLObjectCardinalityRestriction ce, String restriction) { - String property_name=""; + String property_name = ""; List ranges = new ArrayList(); Map restrictionsValues = new HashMap(); - for(OWLObjectProperty property:ce.getObjectPropertiesInSignature()) { + for (OWLObjectProperty property:ce.getObjectPropertiesInSignature()) { propertiesFromObjectRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); + property_name = sfp.getShortForm(property.getIRI()); ranges.add(sfp.getShortForm(ce.getFiller().asOWLClass().getIRI())); propertiesFromObjectRestrictions_ranges.put(property_name,ranges); - } - this.property_name = property_name; + } + + this.property_name = property_name; - restrictionsValues.put(restriction, Integer.toString(ce.getCardinality())); + restrictionsValues.put(restriction, Integer.toString(ce.getCardinality())); restrictionsValuesFromClass.put(property_name, restrictionsValues); } @@ -432,41 +437,41 @@ public void setPropertiesWithCardinality(OWLObjectCardinalityRestriction ce, Str */ public void setBooleanCombinationProperties( Set ranges, Set properties, String restriction) { Map restrictionsValues = new HashMap(); - //if the expression ce is not part of a composed expression (existential or universal) - if (property_name.isEmpty()) { - for(OWLObjectProperty property:properties) { - propertiesFromObjectRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); - restrictionsValues.put(restriction, ""); - restrictionsValuesFromClass.put(property_name, restrictionsValues); - } - } else { - List rangeList = new ArrayList(); - for (OWLClassExpression range:ranges) { - rangeList.add(sfp.getShortForm(range.asOWLClass().getIRI())); - if (range.asOWLClass().equals(owlThing)) { - logger.info("Ignoring owl:Thing range" + property_name); - } - else { - propertiesFromObjectRestrictions_ranges.put(property_name,rangeList); - } + //if the expression ce is not part of a composed expression (existential or universal) + if (property_name.isEmpty()) { + for (OWLObjectProperty property:properties) { + propertiesFromObjectRestrictions.add(property); + property_name = sfp.getShortForm(property.getIRI()); + restrictionsValues.put(restriction, ""); + restrictionsValuesFromClass.put(property_name, restrictionsValues); + } + } else { + List rangeList = new ArrayList(); + for (OWLClassExpression range:ranges) { + rangeList.add(sfp.getShortForm(range.asOWLClass().getIRI())); + if (range.asOWLClass().equals(owlThing)) { + logger.info("Ignoring owl:Thing range" + property_name); + } else { + propertiesFromObjectRestrictions_ranges.put(property_name,rangeList); } - - if (!restrictionsValuesFromClass.isEmpty()) { - for (String j : restrictionsValuesFromClass.keySet()) { - if (j.equals(property_name)) { - Map value = restrictionsValuesFromClass.get(property_name); - for (String i : value.keySet() ) { - restrictionsValues.put(restriction, i); - } - restrictionsValuesFromClass.put(property_name, restrictionsValues); + } + + if (!restrictionsValuesFromClass.isEmpty()) { + for (String j: restrictionsValuesFromClass.keySet()) { + if (j.equals(property_name)) { + Map value = restrictionsValuesFromClass.get(property_name); + for (String i : value.keySet() ) { + restrictionsValues.put(restriction, i); } + + restrictionsValuesFromClass.put(property_name, restrictionsValues); } - } else { - restrictionsValues.put(restriction, ""); - restrictionsValuesFromClass.put(property_name, restrictionsValues); } + } else { + restrictionsValues.put(restriction, ""); + restrictionsValuesFromClass.put(property_name, restrictionsValues); } + } } /** @@ -475,60 +480,62 @@ public void setBooleanCombinationProperties( Set ranges, Set * @param properties data properties expression that have the boolean restriction * @param restriction string value of restriction e.g. "unionOf" */ - public void setBooleanCombinationDataProperties( Set ranges, Set properties, String restriction) { + public void setBooleanCombinationDataProperties(Set ranges, Set properties, String restriction) { Map restrictionsValues = new HashMap(); - //if the expression ce is not part of a composed expression (existential or universal) - if (property_name.equals("")) { - for(OWLDataProperty property:properties) { - propertiesFromDataRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); - restrictionsValues.put(restriction, ""); - restrictionsValuesFromClass.put(property_name, restrictionsValues); + //if the expression ce is not part of a composed expression (existential or universal) + if (property_name.equals("")) { + for (OWLDataProperty property:properties) { + propertiesFromDataRestrictions.add(property); + property_name = sfp.getShortForm(property.getIRI()); + restrictionsValues.put(restriction, ""); + restrictionsValuesFromClass.put(property_name, restrictionsValues); + } + } else { + List rangeList = new ArrayList(); + for (OWLDataRange range:ranges) { + rangeList.add(sfp.getShortForm(range.asOWLDatatype().getIRI())); + if (range.getClass().equals(owlThing)) { + logger.info("Ignoring owl: Thing range" + property_name); + } else { + propertiesFromDataRestrictions_ranges.put(property_name,rangeList); } - } else { - List rangeList = new ArrayList(); - for (OWLDataRange range:ranges) { - rangeList.add(sfp.getShortForm(range.asOWLDatatype().getIRI())); - if (range.getClass().equals(owlThing)) { - logger.info("Ignoring owl: Thing range" + property_name); - } - else { - propertiesFromDataRestrictions_ranges.put(property_name,rangeList); - } - } - if (!restrictionsValuesFromClass.isEmpty()) { - for (String j : restrictionsValuesFromClass.keySet()) { - if (j.equals(property_name)) { - Map value = restrictionsValuesFromClass.get(property_name); - for (String i : value.keySet()) { - restrictionsValues.put(restriction, i); - } - restrictionsValuesFromClass.put(property_name, restrictionsValues); - break; + } + + if (!restrictionsValuesFromClass.isEmpty()) { + for (String j: restrictionsValuesFromClass.keySet()) { + if (j.equals(property_name)) { + Map value = restrictionsValuesFromClass.get(property_name); + for (String i : value.keySet()) { + restrictionsValues.put(restriction, i); } + + restrictionsValuesFromClass.put(property_name, restrictionsValues); + break; } } - else { - restrictionsValues.put(restriction, ""); - restrictionsValuesFromClass.put(property_name, restrictionsValues); - } + } else { + restrictionsValues.put(restriction, ""); + restrictionsValuesFromClass.put(property_name, restrictionsValues); } + } } public void setDataPropertiesWithCardinality(OWLDataCardinalityRestriction ce, String restriction) { - String property_name=""; + String property_name = ""; List ranges = new ArrayList<>(); Map restrictionsValues = new HashMap<>(); - for(OWLDataProperty property:ce.getDataPropertiesInSignature()) { + for (OWLDataProperty property:ce.getDataPropertiesInSignature()) { propertiesFromDataRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); - for (OWLDatatype value:ce.getDatatypesInSignature()){ + property_name = sfp.getShortForm(property.getIRI()); + + for (OWLDatatype value: ce.getDatatypesInSignature()) { ranges.add(sfp.getShortForm(value.getIRI())); propertiesFromDataRestrictions_ranges.put(property_name,ranges); } - } + } + this.property_name = property_name; - restrictionsValues.put(restriction, Integer.toString(ce.getCardinality())); + restrictionsValues.put(restriction, Integer.toString(ce.getCardinality())); restrictionsValuesFromClass.put(property_name, restrictionsValues); } @@ -562,5 +569,5 @@ public List getEnums(IRI classIRI) { public Map> getAllEnums() { return this.enums; - } + } } From ea175013178441a770da84312aef65d72d741635 Mon Sep 17 00:00:00 2001 From: Christopher Weedall <5010253+cweedall@users.noreply.github.com> Date: Thu, 9 May 2024 15:20:49 -0500 Subject: [PATCH 02/10] more spacing --- .../java/edu/isi/oba/RestrictionVisitor.java | 56 +++++++++---------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/src/main/java/edu/isi/oba/RestrictionVisitor.java b/src/main/java/edu/isi/oba/RestrictionVisitor.java index 9da893b..e66a7ab 100644 --- a/src/main/java/edu/isi/oba/RestrictionVisitor.java +++ b/src/main/java/edu/isi/oba/RestrictionVisitor.java @@ -80,7 +80,7 @@ public void visit(OWLClass ce) { @Override public void visit( OWLEquivalentClassesAxiom ce ) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); // If equivalent class axiom AND contains owl:oneOf, then we're looking at an ENUM class. ce.classExpressions().filter((e) -> e instanceof OWLObjectOneOf).forEach((oneOfObj) -> { @@ -143,9 +143,9 @@ public void visit(OWLObjectSomeValuesFrom ce) { */ @Override public void visit(OWLObjectAllValuesFrom ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); Map restrictionsValues = new HashMap<>(); - for (OWLObjectProperty property:ce.getObjectPropertiesInSignature()) { + for (OWLObjectProperty property: ce.getObjectPropertiesInSignature()) { propertiesFromObjectRestrictions.add(property); property_name = sfp.getShortForm(property.getIRI()); } @@ -168,45 +168,45 @@ public void visit(OWLObjectAllValuesFrom ce) { @Override public void visit(OWLObjectUnionOf ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); // Loop through each item in the union and accept visits. - for (OWLClassExpression e : ce.getOperands()) { + for (OWLClassExpression e: ce.getOperands()) { e.accept(this); } } @Override public void visit(OWLObjectIntersectionOf ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); // Loop through each item in the intersection and accept visits. - for (OWLClassExpression e : ce.getOperands()) { + for (OWLClassExpression e: ce.getOperands()) { e.accept(this); } } @Override public void visit(OWLObjectMinCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); setPropertiesWithCardinality(ce, "minCardinality"); } @Override public void visit(OWLObjectMaxCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); setPropertiesWithCardinality(ce,"maxCardinality"); } @Override public void visit(OWLObjectExactCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); setPropertiesWithCardinality(ce, "exactCardinality"); } @Override public void visit(OWLObjectComplementOf ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); Map restrictionsValues = new HashMap(); String complementName = this.sfp.getShortForm(ce.getOperand().asOWLClass().getIRI()); restrictionsValues.put("complementOf", complementName ); @@ -267,9 +267,9 @@ public void visit(OWLObjectOneOf ce) { */ @Override public void visit(OWLDataAllValuesFrom ce) { - logger.info( "\n Analyzed Class: " + this.cls+ " with axiom: "+ce); + logger.info( "\n Analyzed Class: " + this.cls + " with axiom: " + ce); Map restrictionsValues = new HashMap(); - for (OWLDataProperty property:ce.getDataPropertiesInSignature()) { + for (OWLDataProperty property: ce.getDataPropertiesInSignature()) { propertiesFromDataRestrictions.add(property); property_name = sfp.getShortForm(property.getIRI()); } @@ -325,39 +325,39 @@ public void visit(OWLDataSomeValuesFrom ce) { @Override public void visit(OWLDataUnionOf ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); // Loop through each item in the union and accept visits. - for (OWLDataRange e : ce.getOperands()) { + for (OWLDataRange e: ce.getOperands()) { e.accept(this); } } @Override public void visit(OWLDataIntersectionOf ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); // Loop through each item in the intersection and accept visits. - for (OWLDataRange e : ce.getOperands()) { + for (OWLDataRange e: ce.getOperands()) { e.accept(this); } } @Override public void visit(OWLDataMinCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); setDataPropertiesWithCardinality(ce,"minCardinality"); } @Override public void visit(OWLDataMaxCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); setDataPropertiesWithCardinality(ce,"maxCardinality"); } @Override public void visit(OWLDataExactCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls+ " with axiom: "+ce); + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); setDataPropertiesWithCardinality(ce,"exactCardinality"); } @@ -416,7 +416,7 @@ public void setPropertiesWithCardinality(OWLObjectCardinalityRestriction ce, Str String property_name = ""; List ranges = new ArrayList(); Map restrictionsValues = new HashMap(); - for (OWLObjectProperty property:ce.getObjectPropertiesInSignature()) { + for (OWLObjectProperty property: ce.getObjectPropertiesInSignature()) { propertiesFromObjectRestrictions.add(property); property_name = sfp.getShortForm(property.getIRI()); ranges.add(sfp.getShortForm(ce.getFiller().asOWLClass().getIRI())); @@ -439,7 +439,7 @@ public void setBooleanCombinationProperties( Set ranges, Set Map restrictionsValues = new HashMap(); //if the expression ce is not part of a composed expression (existential or universal) if (property_name.isEmpty()) { - for (OWLObjectProperty property:properties) { + for (OWLObjectProperty property: properties) { propertiesFromObjectRestrictions.add(property); property_name = sfp.getShortForm(property.getIRI()); restrictionsValues.put(restriction, ""); @@ -447,7 +447,7 @@ public void setBooleanCombinationProperties( Set ranges, Set } } else { List rangeList = new ArrayList(); - for (OWLClassExpression range:ranges) { + for (OWLClassExpression range: ranges) { rangeList.add(sfp.getShortForm(range.asOWLClass().getIRI())); if (range.asOWLClass().equals(owlThing)) { logger.info("Ignoring owl:Thing range" + property_name); @@ -460,7 +460,7 @@ public void setBooleanCombinationProperties( Set ranges, Set for (String j: restrictionsValuesFromClass.keySet()) { if (j.equals(property_name)) { Map value = restrictionsValuesFromClass.get(property_name); - for (String i : value.keySet() ) { + for (String i: value.keySet() ) { restrictionsValues.put(restriction, i); } @@ -484,7 +484,7 @@ public void setBooleanCombinationDataProperties(Set ranges, Set restrictionsValues = new HashMap(); //if the expression ce is not part of a composed expression (existential or universal) if (property_name.equals("")) { - for (OWLDataProperty property:properties) { + for (OWLDataProperty property: properties) { propertiesFromDataRestrictions.add(property); property_name = sfp.getShortForm(property.getIRI()); restrictionsValues.put(restriction, ""); @@ -492,7 +492,7 @@ public void setBooleanCombinationDataProperties(Set ranges, Set rangeList = new ArrayList(); - for (OWLDataRange range:ranges) { + for (OWLDataRange range: ranges) { rangeList.add(sfp.getShortForm(range.asOWLDatatype().getIRI())); if (range.getClass().equals(owlThing)) { logger.info("Ignoring owl: Thing range" + property_name); @@ -505,7 +505,7 @@ public void setBooleanCombinationDataProperties(Set ranges, Set value = restrictionsValuesFromClass.get(property_name); - for (String i : value.keySet()) { + for (String i: value.keySet()) { restrictionsValues.put(restriction, i); } @@ -524,7 +524,7 @@ public void setDataPropertiesWithCardinality(OWLDataCardinalityRestriction ce, S String property_name = ""; List ranges = new ArrayList<>(); Map restrictionsValues = new HashMap<>(); - for (OWLDataProperty property:ce.getDataPropertiesInSignature()) { + for (OWLDataProperty property: ce.getDataPropertiesInSignature()) { propertiesFromDataRestrictions.add(property); property_name = sfp.getShortForm(property.getIRI()); From 15884de9df61403d00eba363615dbcc00015093f Mon Sep 17 00:00:00 2001 From: Christopher Weedall <5010253+cweedall@users.noreply.github.com> Date: Fri, 17 May 2024 08:43:57 -0500 Subject: [PATCH 03/10] lists to sets; min/max for certain types --- .../java/edu/isi/oba/MapperDataProperty.java | 55 +++++++++++-------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/src/main/java/edu/isi/oba/MapperDataProperty.java b/src/main/java/edu/isi/oba/MapperDataProperty.java index 38ca8d0..0bacefd 100644 --- a/src/main/java/edu/isi/oba/MapperDataProperty.java +++ b/src/main/java/edu/isi/oba/MapperDataProperty.java @@ -4,8 +4,9 @@ import io.swagger.v3.oas.models.media.*; -import java.util.List; +import java.math.BigDecimal; import java.util.Map; +import java.util.Set; class MapperDataProperty { private final Map dataTypes = Map.ofEntries( @@ -72,33 +73,34 @@ private String getDataType(String key) { final String name; final String description; - private List type; + private Set type; private Boolean array; private Boolean nullable; final Boolean isFunctional; - private Map restrictions; - private List valuesFromDataRestrictions_ranges; + private Map restrictions; + private Set valuesFromDataRestrictions_ranges; - public MapperDataProperty(String name, String description, Boolean isFunctional, Map restrictions, List valuesFromDataRestrictions_ranges, List type, Boolean array, Boolean nullable) { + public MapperDataProperty(String name, String description, Boolean isFunctional, Map restrictions, Set valuesFromDataRestrictions_ranges, Set type, Boolean array, Boolean nullable) { this.name = name; this.description = description; this.type = type; this.array = array; this.nullable = nullable; - this.isFunctional=isFunctional; - this.restrictions=restrictions; - this.valuesFromDataRestrictions_ranges=valuesFromDataRestrictions_ranges; + this.isFunctional = isFunctional; + this.restrictions = restrictions; + this.valuesFromDataRestrictions_ranges = valuesFromDataRestrictions_ranges; } public Schema getSchemaByDataProperty() { - if (this.type.isEmpty()) { + if (this.type == null || this.type.isEmpty()) { return (this.array) ? this.arraySchema(new StringSchema()) : this.nonArraySchema(new StringSchema()); } else if (this.type.size() > 1) { return (this.array) ? this.composedSchema() : this.nonArraySchema(new Schema()); } - String schemaType = getDataType(this.type.get(0)); + final String dataType = this.type.iterator().next(); + String schemaType = this.getDataType(dataType); if (schemaType == null) { logger.severe("property " + this.name + " type " + this.type); } @@ -115,7 +117,7 @@ public Schema getSchemaByDataProperty() { case DATETIME_TYPE: return (this.array) ? this.arraySchema(new DateTimeSchema()) : this.nonArraySchema(new DateTimeSchema()); default: - logger.warning("datatype mapping failed " + this.type.get(0)); + logger.warning("datatype mapping failed " + dataType); return (this.array) ? this.arraySchema(new Schema()) : this.nonArraySchema(new Schema()); } } @@ -140,9 +142,9 @@ private ArraySchema composedSchema() { case STRING_TYPE: schema = new StringSchema(); - if (item.equals("anyURI")) { + if ("anyURI".equals(item)) { schema.format("uri"); - } else if (item.equals("byte")) { + } else if ("byte".equals(item)) { schema.format("byte"); } @@ -150,9 +152,9 @@ private ArraySchema composedSchema() { case NUMBER_TYPE: schema = new NumberSchema(); - if (item.equals("float")) { + if ("float".equals(item)) { schema.format("double"); - } else if (item.equals("double")) { + } else if ("double".equals(item)) { schema.format("double"); } else { schema.format("number"); @@ -162,7 +164,15 @@ private ArraySchema composedSchema() { case INTEGER_TYPE: schema = new IntegerSchema(); - if (item.equals("long")) { + if ("nonPositiveInteger".equals(item)) { + schema.setMaximum(BigDecimal.ZERO); + } + + if ("nonNegativeInteger".equals(item)) { + schema.setMinimum(BigDecimal.ZERO); + } + + if ("long".equals(item)) { schema.format("int64"); } @@ -174,20 +184,20 @@ private ArraySchema composedSchema() { schema = new DateTimeSchema(); break; default: - logger.warning("datatype mapping failed " + this.type.get(0)); + logger.warning("datatype mapping failed " + item); schema = new Schema(); } switch (restriction) { case "unionOf": - if (value == "someValuesFrom") { + if ("someValuesFrom".equals(value)) { this.nullable = false; } composedSchema.addAnyOfItem(schema); break; case "intersectionOf": - if (value == "someValuesFrom") { + if ("someValuesFrom".equals(value)) { this.nullable = false; } @@ -227,8 +237,9 @@ private ArraySchema arraySchema(Schema base) { if (this.restrictions.containsKey("complementOf")) { Schema schema = new Schema(); Schema complementOf = new Schema(); - complementOf.setType(this.getDataType(this.type.get(0))); - complementOf.setFormat(this.type.get(0)); + final String dataType = this.type.iterator().next(); + complementOf.setType(this.getDataType(dataType)); + complementOf.setFormat(dataType); schema.setNot(complementOf); array.setNullable(this.nullable); array.setItems(schema); @@ -281,7 +292,7 @@ private Schema getSchemaRestrictions(Schema base) { //nothing to do break; case "oneOf": - if (value == "someValuesFrom") { + if ("someValuesFrom".equals(value)) { this.nullable = false; } From ef214d4d3c78e5df894b41c46a8f1386f796bfa8 Mon Sep 17 00:00:00 2001 From: Christopher Weedall <5010253+cweedall@users.noreply.github.com> Date: Fri, 17 May 2024 09:16:06 -0500 Subject: [PATCH 04/10] lists to sets --- src/main/java/edu/isi/oba/Oba.java | 2 +- .../java/edu/isi/oba/config/YamlConfig.java | 19 +++++----- src/test/java/edu/isi/oba/MapperTest.java | 38 +++++++++---------- src/test/java/edu/isi/oba/ObaUtilsTest.java | 3 +- .../edu/isi/oba/config/YamlConfigTest.java | 7 ++-- 5 files changed, 32 insertions(+), 37 deletions(-) diff --git a/src/main/java/edu/isi/oba/Oba.java b/src/main/java/edu/isi/oba/Oba.java index 2ee7d6f..80d95f7 100644 --- a/src/main/java/edu/isi/oba/Oba.java +++ b/src/main/java/edu/isi/oba/Oba.java @@ -93,7 +93,7 @@ public static void main(String[] args) throws Exception { } private static void generate_context(YamlConfig config_data, String destination_dir) { - List ontologies = config_data.getOntologies(); + Set ontologies = config_data.getOntologies(); JSONObject context_json_object = null; JSONObject context_json_object_class = null; try { diff --git a/src/main/java/edu/isi/oba/config/YamlConfig.java b/src/main/java/edu/isi/oba/config/YamlConfig.java index d0e9b31..507df58 100644 --- a/src/main/java/edu/isi/oba/config/YamlConfig.java +++ b/src/main/java/edu/isi/oba/config/YamlConfig.java @@ -7,6 +7,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; public class YamlConfig { private final Map configFlags = new HashMap<>(){{ @@ -27,14 +28,14 @@ public class YamlConfig { public OpenAPI openapi; public String output_dir = DEFAULT_OUTPUT_DIRECTORY; public String name = DEFAULT_PROJECT_NAME; - public List paths; - public List ontologies; + public Set paths; + public Set ontologies; private EndpointConfig endpoint; public AuthConfig auth; public FirebaseConfig firebase; public Map> relations; private LinkedHashMap custom_paths = null; - public List classes; + public Set classes; public String custom_queries_directory; public Boolean getEnable_get_paths() { @@ -101,19 +102,19 @@ public void setName(String name) { this.name = name; } - public List getPaths() { + public Set getPaths() { return paths; } - public void setPaths(List paths) { + public void setPaths(Set paths) { this.paths = paths; } - public List getOntologies() { + public Set getOntologies() { return ontologies; } - public void setOntologies(List ontologies) { + public void setOntologies(Set ontologies) { this.ontologies = ontologies; } @@ -157,11 +158,11 @@ public void setOpenapi(OpenAPI openapi) { this.openapi = openapi; } - public List getClasses() { + public Set getClasses() { return this.classes; } - public void setClasses(List classes) { + public void setClasses(Set classes) { this.classes = classes; } diff --git a/src/test/java/edu/isi/oba/MapperTest.java b/src/test/java/edu/isi/oba/MapperTest.java index 62c01e7..83c078e 100644 --- a/src/test/java/edu/isi/oba/MapperTest.java +++ b/src/test/java/edu/isi/oba/MapperTest.java @@ -1,27 +1,26 @@ package edu.isi.oba; -import static edu.isi.oba.ObaUtils.get_yaml_data; import edu.isi.oba.config.AuthConfig; import edu.isi.oba.config.CONFIG_FLAG; import edu.isi.oba.config.YamlConfig; +import static edu.isi.oba.Oba.logger; +import static edu.isi.oba.ObaUtils.get_yaml_data; + +import io.swagger.v3.oas.models.media.Schema; -import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; + +import java.util.HashSet; import java.util.Map; +import java.util.Set; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; -import io.swagger.v3.oas.models.media.Schema; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - import org.semanticweb.owlapi.model.OWLClass; public class MapperTest { @@ -30,16 +29,14 @@ public void testFilter() throws Exception{ String config_test_file_path = "src/test/config/dbpedia.yaml"; YamlConfig config_data = get_yaml_data(config_test_file_path); Mapper mapper = new Mapper(config_data); - List config = config_data.getClasses(); - List classes = mapper.filter_classes(); - List filter_classes = new ArrayList(); + Set config = config_data.getClasses(); + Set classes = mapper.filter_classes(); + Set filter_classes = new HashSet<>(); for (OWLClass _class : classes){ filter_classes.add(_class.getIRI().getIRIString()); } - Collections.sort(filter_classes); - Collections.sort(config); - Assertions.assertEquals(config, filter_classes); + Assertions.assertEquals(config, filter_classes); } /** @@ -100,21 +97,20 @@ public void testComplexOntology() throws Exception{ InputStream stream = Oba.class.getClassLoader().getResourceAsStream("logging.properties"); try { LogManager.getLogManager().readConfiguration(stream); - edu.isi.oba.Oba.logger = Logger.getLogger(Oba.class.getName()); - + logger = Logger.getLogger(Oba.class.getName()); } catch (IOException e) { e.printStackTrace(); } - edu.isi.oba.Oba.logger.setLevel(Level.FINE); - edu.isi.oba.Oba.logger.addHandler(new ConsoleHandler()); + + logger.setLevel(Level.FINE); + logger.addHandler(new ConsoleHandler()); String example_remote = "src/test/resources/complex_expr/config.yaml"; YamlConfig config_data = get_yaml_data(example_remote); - String destination_dir = config_data.getOutput_dir() + File.separator + config_data.getName(); config_data.setAuth(new AuthConfig()); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://businessontology.com/ontology/Person"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), Map.ofEntries(Map.entry(CONFIG_FLAG.DEFAULT_DESCRIPTIONS, true), Map.entry(CONFIG_FLAG.DEFAULT_PROPERTIES, true), Map.entry(CONFIG_FLAG.FOLLOW_REFERENCES, true))); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.stream().findFirst().get(), Map.ofEntries(Map.entry(CONFIG_FLAG.DEFAULT_DESCRIPTIONS, true), Map.entry(CONFIG_FLAG.DEFAULT_PROPERTIES, true), Map.entry(CONFIG_FLAG.FOLLOW_REFERENCES, true))); Schema schema = mapperSchema.getSchema(); // The person schema must not be null. Assertions.assertNotNull(schema); diff --git a/src/test/java/edu/isi/oba/ObaUtilsTest.java b/src/test/java/edu/isi/oba/ObaUtilsTest.java index c32f380..54c9f12 100644 --- a/src/test/java/edu/isi/oba/ObaUtilsTest.java +++ b/src/test/java/edu/isi/oba/ObaUtilsTest.java @@ -51,7 +51,7 @@ public void getDescription () throws OWLOntologyCreationException{ try { Mapper mapper = new Mapper(config_data); OWLClass planClass = mapper.manager.getOWLDataFactory().getOWLClass("http://purl.org/net/p-plan#Plan"); - String desc = ObaUtils.getDescription(planClass, mapper.ontologies.get(0), true); + String desc = ObaUtils.getDescription(planClass, mapper.ontologies.stream().findFirst().get(), true); Assertions.assertNotEquals(desc, ""); }catch(Exception e){ Assertions.fail("Failed to get description.", e); @@ -102,5 +102,4 @@ public void run() { }catch(Exception e){ } } - } \ No newline at end of file diff --git a/src/test/java/edu/isi/oba/config/YamlConfigTest.java b/src/test/java/edu/isi/oba/config/YamlConfigTest.java index aed8982..af0fd56 100644 --- a/src/test/java/edu/isi/oba/config/YamlConfigTest.java +++ b/src/test/java/edu/isi/oba/config/YamlConfigTest.java @@ -2,8 +2,7 @@ import static edu.isi.oba.ObaUtils.get_yaml_data; -import java.util.Arrays; -import java.util.List; +import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -13,8 +12,8 @@ public class YamlConfigTest { public void getSelectedClasses(){ String config_test_file_path = "examples/dbpedia/config_music.yaml"; YamlConfig config_data = get_yaml_data(config_test_file_path); - List expected = Arrays.asList("http://dbpedia.org/ontology/Genre", "http://dbpedia.org/ontology/Band"); - List config = config_data.getClasses(); + Set expected = Set.of("http://dbpedia.org/ontology/Genre", "http://dbpedia.org/ontology/Band"); + Set config = config_data.getClasses(); Assertions.assertEquals(expected, config); } } From 156a4d770dce895594fc1d02063c901896bf6060 Mon Sep 17 00:00:00 2001 From: Christopher Weedall <5010253+cweedall@users.noreply.github.com> Date: Fri, 17 May 2024 23:17:40 -0500 Subject: [PATCH 05/10] lists to sets; anyOf/allOf/enum fixes; composedSchema cardinality --- .../edu/isi/oba/MapperObjectProperty.java | 102 ++++++++++++------ 1 file changed, 68 insertions(+), 34 deletions(-) diff --git a/src/main/java/edu/isi/oba/MapperObjectProperty.java b/src/main/java/edu/isi/oba/MapperObjectProperty.java index 52bbaf5..79ed42e 100644 --- a/src/main/java/edu/isi/oba/MapperObjectProperty.java +++ b/src/main/java/edu/isi/oba/MapperObjectProperty.java @@ -4,50 +4,50 @@ import io.swagger.v3.oas.models.media.*; -import java.util.LinkedHashSet; -import java.util.List; +import java.util.HashMap; +import java.util.HashSet; import java.util.Map; -import java.util.stream.Collectors; +import java.util.Set; class MapperObjectProperty { final String name; final String description; - private List ref; + final private Set ref; private Boolean array; private Boolean nullable; final Boolean isFunctional; - final Map restrictions; + final Map restrictions; - public MapperObjectProperty(String name, String description, Boolean isFunctional, Map restrictions, List ref) { + public MapperObjectProperty(String name, String description, Boolean isFunctional, Map restrictions, Set ref) { this.name = name; this.description = description; - this.ref = ref; + this.ref = (ref != null) ? ref : new HashSet<>(); this.array = true; this.nullable = true; this.isFunctional = isFunctional; - this.restrictions = restrictions; + this.restrictions = (restrictions != null) ? restrictions : new HashMap<>(); } - public MapperObjectProperty(String name, String description, Boolean isFunctional, Map restrictions, List ref, Boolean array, Boolean nullable) { + public MapperObjectProperty(String name, String description, Boolean isFunctional, Map restrictions, Set ref, Boolean array, Boolean nullable) { this.name = name; this.description = description; - this.ref = ref; + this.ref = (ref != null) ? ref : new HashSet<>(); this.array = array; this.nullable = nullable; this.isFunctional = isFunctional; - this.restrictions = restrictions; + this.restrictions = (restrictions != null) ? restrictions : new HashMap<>(); } public Schema getSchemaByObjectProperty() { - if (this.ref.isEmpty()){ + if (this.ref == null || this.ref.isEmpty()){ return getComposedSchemaObject(this.ref, this.array, this.nullable); } if (this.ref.size() > 1){ return getComposedSchemaObject(this.ref, this.array, this.nullable); } else { - return getObjectPropertiesByRef(this.ref.get(0), this.array, this.nullable); + return getObjectPropertiesByRef(this.ref.iterator().next(), this.array, this.nullable); } } @@ -147,14 +147,14 @@ private Schema getObjectPropertiesByRef(String ref, boolean isArray, boolean isN return objects; } - private Schema getComposedSchemaObject(List refs, boolean array, boolean nullable) { + private Schema getComposedSchemaObject(Set refs, boolean array, boolean nullable) { Schema object = new ObjectSchema(); ComposedSchema composedSchema = new ComposedSchema(); object.setType("object"); object.setDescription(this.description); - if (array && !this.restrictions.isEmpty()) { + if (array) { ArraySchema objects = new ArraySchema(); objects.setDescription(this.description); @@ -165,10 +165,7 @@ private Schema getComposedSchemaObject(List refs, boolean array, boolean for (String restriction: this.restrictions.keySet()) { String value = this.restrictions.get(restriction); - // In some cases, the duplicate reference may have been added to the list. We only need to create one $ref item to it. - LinkedHashSet uniqueRefs = refs.stream().collect(Collectors.toCollection(LinkedHashSet::new)); - - for (String item: uniqueRefs) { + for (String item: refs) { Schema objectRange = new ObjectSchema(); objectRange.setType("object"); objectRange.set$ref(item); @@ -176,37 +173,66 @@ private Schema getComposedSchemaObject(List refs, boolean array, boolean switch (restriction) { case "unionOf": if ("someValuesFrom".equals(value)) { - nullable=false; + nullable = false; } - composedSchema.addAnyOfItem(objectRange); - objects.setItems(composedSchema); + if (composedSchema.getAnyOf() == null || !composedSchema.getAnyOf().contains(objectRange)) { + composedSchema.addAnyOfItem(objectRange); + objects.setItems(composedSchema); + } + break; case "intersectionOf": if ("someValuesFrom".equals(value)) { nullable = false; } - composedSchema.addAllOfItem(objectRange); - objects.setItems(composedSchema); + if (composedSchema.getAllOf() == null || !composedSchema.getAllOf().contains(objectRange)) { + composedSchema.addAllOfItem(objectRange); + objects.setItems(composedSchema); + } + break; case "someValuesFrom": - nullable=false; - composedSchema.addAnyOfItem(objectRange); - objects.setItems(composedSchema); + nullable = false; + + if (composedSchema.getAnyOf() == null || !composedSchema.getAnyOf().contains(objectRange)) { + composedSchema.addAnyOfItem(objectRange); + objects.setItems(composedSchema); + } + break; case "allValuesFrom": //nothing to do in the Schema break; case "oneOf": - if (value=="someValuesFrom") { - nullable=false; + if ("someValuesFrom".equals(value)) { + nullable = false; } - composedSchema.addEnumItemObject(item); - composedSchema.setType("string"); - composedSchema.setFormat("uri"); + Schema enumSchema = new Schema(); + + if (composedSchema.getOneOf() == null || composedSchema.getOneOf().isEmpty()) { + enumSchema.addEnumItemObject(item); + } else { + enumSchema = composedSchema.getOneOf().iterator().next(); + enumSchema.addEnumItemObject(item); + composedSchema = new ComposedSchema(); + } + + composedSchema.addOneOfItem(enumSchema); + objects.setItems(composedSchema); + break; + case "maxCardinality": + objects.setMaxItems(Integer.parseInt(value)); + break; + case "minCardinality": + objects.setMinItems(Integer.parseInt(value)); + break; + case "exactCardinality": + objects.setMaxItems(Integer.parseInt(value)); + objects.setMinItems(Integer.parseInt(value)); break; default: //if the property range is complex it will be omitted @@ -216,10 +242,18 @@ private Schema getComposedSchemaObject(List refs, boolean array, boolean } } + objects.setNullable(nullable); + if (refs.isEmpty()) { - objects.setItems(object); + if (objects.getItems() != null && objects.getEnum() != null) { + objects.setItems(object); + } else { + objects.setType(null); + objects.setDescription(null); + objects.setItems(null); + objects.setNullable(null); + } } - objects.setNullable(nullable); return objects; } else { From 8e0d1d61c77e6072b81a91bf78236cd8dd0cbe9a Mon Sep 17 00:00:00 2001 From: Christopher Weedall <5010253+cweedall@users.noreply.github.com> Date: Fri, 17 May 2024 23:20:50 -0500 Subject: [PATCH 06/10] pass first ontology of set --- src/test/java/edu/isi/oba/MapperTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/edu/isi/oba/MapperTest.java b/src/test/java/edu/isi/oba/MapperTest.java index 83c078e..50c8a21 100644 --- a/src/test/java/edu/isi/oba/MapperTest.java +++ b/src/test/java/edu/isi/oba/MapperTest.java @@ -110,7 +110,7 @@ public void testComplexOntology() throws Exception{ Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://businessontology.com/ontology/Person"); String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.stream().findFirst().get(), Map.ofEntries(Map.entry(CONFIG_FLAG.DEFAULT_DESCRIPTIONS, true), Map.entry(CONFIG_FLAG.DEFAULT_PROPERTIES, true), Map.entry(CONFIG_FLAG.FOLLOW_REFERENCES, true))); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, Map.ofEntries(Map.entry(CONFIG_FLAG.DEFAULT_DESCRIPTIONS, true), Map.entry(CONFIG_FLAG.DEFAULT_PROPERTIES, true), Map.entry(CONFIG_FLAG.FOLLOW_REFERENCES, true))); Schema schema = mapperSchema.getSchema(); // The person schema must not be null. Assertions.assertNotNull(schema); From 8ba263d7eabe521cc00ec94565085b632decf248 Mon Sep 17 00:00:00 2001 From: Christopher Weedall <5010253+cweedall@users.noreply.github.com> Date: Fri, 17 May 2024 23:25:26 -0500 Subject: [PATCH 07/10] list to set; remove unnecessary args --- src/main/java/edu/isi/oba/Mapper.java | 150 +++++++++++++------------- 1 file changed, 73 insertions(+), 77 deletions(-) diff --git a/src/main/java/edu/isi/oba/Mapper.java b/src/main/java/edu/isi/oba/Mapper.java index e7bb3c0..7ddbb7e 100644 --- a/src/main/java/edu/isi/oba/Mapper.java +++ b/src/main/java/edu/isi/oba/Mapper.java @@ -29,10 +29,10 @@ class Mapper { public final Map schemaDescriptions = new HashMap<>(); //URI-description of the schemas public Map schemas = new HashMap<>(); final Paths paths = new Paths(); - List selected_paths; - List ontologies; - List selected_classes; - List mappedClasses; + Set selected_paths = new HashSet<>(); + Set ontologies = new HashSet<>(); + List selected_classes = new ArrayList<>(); + List mappedClasses = new ArrayList<>(); YamlConfig config_data; public OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); @@ -40,9 +40,8 @@ class Mapper { public Mapper(YamlConfig config_data) throws OWLOntologyCreationException, IOException { this.config_data = config_data; this.selected_paths = config_data.getPaths(); - this.mappedClasses = new ArrayList<>(); - List config_ontologies = config_data.getOntologies(); + Set config_ontologies = config_data.getOntologies(); String destination_dir = config_data.getOutput_dir() + File.separator + config_data.getName(); File outputDir = new File(destination_dir); if (!outputDir.exists()) { @@ -51,28 +50,28 @@ public Mapper(YamlConfig config_data) throws OWLOntologyCreationException, IOExc //Load the ontology into the manager int i = 0; - List ontologyPaths = new ArrayList<>(); + Set ontologyPaths = new HashSet<>(); this.download_ontologies(config_ontologies, destination_dir, i, ontologyPaths); //set ontology paths in YAML to the ones we have downloaded (for later reference by owl2jsonld) this.config_data.setOntologies(ontologyPaths); - ontologies = this.manager.ontologies().collect(Collectors.toList()); + ontologies = this.manager.ontologies().collect(Collectors.toSet()); //Create a temporal Map schemaNames with the classes for (OWLOntology ontology : ontologies) { Set classes = ontology.getClassesInSignature(); this.setSchemaNames(classes); - this.setSchemaDrescriptions(classes,ontology); + this.setSchemaDescriptions(classes, ontology); } if (config_data.getClasses() != null) { - this.selected_classes = this.filter_classes(); + this.selected_classes.addAll(this.filter_classes()); } } - private void download_ontologies(List config_ontologies, String destination_dir, int i, List ontologyPaths) throws OWLOntologyCreationException, IOException { + private void download_ontologies(Set config_ontologies, String destination_dir, int i, Set ontologyPaths) throws OWLOntologyCreationException, IOException { for (String ontologyPath : config_ontologies) { //copy the ontologies used in the destination folder - String destinationPath = destination_dir + File.separator +"ontology"+i+".owl"; + String destinationPath = destination_dir + File.separator + "ontology" + i + ".owl"; File ontologyFile = new File (destinationPath); //content negotiation + download in case a URI is added if(ontologyPath.startsWith("http://") || ontologyPath.startsWith("https://")){ @@ -84,7 +83,7 @@ private void download_ontologies(List config_ontologies, String destinat //copy to the right folder Files.copy(new File(ontologyPath).toPath(), ontologyFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { - Logger.getLogger(Mapper.class.getName()).log(Level.SEVERE, "ERROR while loading file: "+ontologyPath, ex); + Logger.getLogger(Mapper.class.getName()).log(Level.SEVERE, "ERROR while loading file: " + ontologyPath, ex); throw ex; } } @@ -119,17 +118,20 @@ public void createSchemas(String destination_dir) { for (OWLOntology ontology : this.ontologies) { OWLDocumentFormat format = ontology.getFormat(); - String defaultOntologyPrefixIRI = format.asPrefixOWLDocumentFormat().getDefaultPrefix(); - if (defaultOntologyPrefixIRI == null) { - logger.severe("Unable to find the default prefix for the ontology"); + if (format == null) { + logger.severe("No ontology format found. Unable to proceed."); System.exit(1); - } + } else { + String defaultOntologyPrefixIRI = format.asPrefixOWLDocumentFormat().getDefaultPrefix(); + if (defaultOntologyPrefixIRI == null) { + logger.severe("Unable to find the default prefix for the ontology. Unable to proceed."); + System.exit(1); + } - Set classes = ontology.getClassesInSignature(); - for (OWLClass cls : classes) { - //filter if the class prefix does not have the default ontology prefix - if (cls.getIRI() != null) { - if (this.selected_classes == null || this.selected_classes.contains(cls)) { + Set classes = ontology.getClassesInSignature(); + for (OWLClass cls : classes) { + //filter if the class prefix does not have the default ontology prefix + if (cls.getIRI() != null) { this.add_owlclass_to_openapi(query, pathGenerator, ontology, defaultOntologyPrefixIRI, cls, true); } } @@ -162,59 +164,61 @@ private List add_owlclass_to_openapi(Query query, PathGenerator pathGe String defaultOntologyPrefixIRI, OWLClass cls, Boolean topLevel) { List ref = new ArrayList<>(); String classPrefixIRI = cls.getIRI().getNamespace(); - if (defaultOntologyPrefixIRI.equals(classPrefixIRI)) { - try{ - MapperSchema mapperSchema = getMapperSchema(query, ontology, cls, this.schemaDescriptions.get(cls.getIRI())); - // add references to schemas in class restrictions (check selected classes to avoid conflicts) - for (String classToCheck : mapperSchema.getPropertiesFromObjectRestrictions_ranges()) { - OWLClass clsToCheck = manager.getOWLDataFactory().getOWLClass(IRI.create(classPrefixIRI + classToCheck)); - if (this.mappedClasses.contains(clsToCheck) || (this.selected_classes != null && this.selected_classes.contains(clsToCheck))){ - logger.info("The class " + clsToCheck + " exists "); - } else { - //rare cases have instances, so we filter them out and recheck that the target is a class. - if(ontology.containsClassInSignature(clsToCheck.getIRI())) { - System.out.println("ADD "+ clsToCheck); - for (OWLOntology temp_ontology : this.ontologies) { - if (this.config_data.getConfigFlagValue(CONFIG_FLAG.FOLLOW_REFERENCES)) { - this.mappedClasses.add(clsToCheck); - this.getMapperSchema(query, temp_ontology, clsToCheck, this.schemaDescriptions.get(clsToCheck.getIRI())); - this.add_owlclass_to_openapi(query, pathGenerator, temp_ontology, classPrefixIRI, clsToCheck, false); - } - } - } - } - } + try{ + MapperSchema mapperSchema = this.getMapperSchema(query, cls, this.schemaDescriptions.get(cls.getIRI())); - // add references to schemas in property ranges - for (OWLClass ref_class : mapperSchema.getProperties_range()) { - if (this.mappedClasses.contains(ref_class)){ - logger.info("The class " + ref_class + " exists "); - } else { + // add references to schemas in class restrictions (check selected classes to avoid conflicts) + for (String classToCheck : mapperSchema.getPropertiesFromObjectRestrictions_ranges()) { + final var classIRI = IRI.create(classPrefixIRI + classToCheck); + OWLClass clsToCheck = manager.getOWLDataFactory().getOWLClass(classIRI); + if (this.mappedClasses.contains(clsToCheck) || this.selected_classes.contains(clsToCheck)){ + logger.info("The class " + clsToCheck + " exists "); + } else { + //rare cases have instances, so we filter them out and recheck that the target is a class. + if(ontology.containsClassInSignature(classIRI)) { + System.out.println("ADD "+ clsToCheck); for (OWLOntology temp_ontology : this.ontologies) { if (this.config_data.getConfigFlagValue(CONFIG_FLAG.FOLLOW_REFERENCES)) { - this.mappedClasses.add(ref_class); - this.getMapperSchema(query, temp_ontology, ref_class,this.schemaDescriptions.get(ref_class.getIRI())); - this.add_owlclass_to_openapi(query, pathGenerator, temp_ontology, classPrefixIRI, ref_class, false); + this.mappedClasses.add(clsToCheck); + this.getMapperSchema(query, clsToCheck, this.schemaDescriptions.get(classIRI)); + this.selected_classes.addAll(this.add_owlclass_to_openapi(query, pathGenerator, temp_ontology, classPrefixIRI, clsToCheck, false)); } } } } - - //Add the OpenAPI paths - if (topLevel) { - addOpenAPIPaths(pathGenerator, mapperSchema, cls); + } + + // add references to schemas in property ranges + for (OWLClass ref_class : mapperSchema.getProperties_range()) { + if (this.mappedClasses.contains(ref_class)){ + logger.info("The class " + ref_class + " exists "); + } else { + for (OWLOntology temp_ontology : this.ontologies) { + if (this.config_data.getConfigFlagValue(CONFIG_FLAG.FOLLOW_REFERENCES)) { + this.mappedClasses.add(ref_class); + this.getMapperSchema(query, ref_class, this.schemaDescriptions.get(ref_class.getIRI())); + this.selected_classes.addAll(this.add_owlclass_to_openapi(query, pathGenerator, temp_ontology, classPrefixIRI, ref_class, false)); + } + } } - }catch(Exception e){ - logger.log(Level.SEVERE,"Could not parse class "+cls.getIRI().toString()); } + + //Add the OpenAPI paths + if (topLevel) { + this.add_path(pathGenerator, mapperSchema); + } + }catch(Exception e){ + logger.log(Level.SEVERE,"Could not parse class " + cls.getIRI().toString()); + logger.log(Level.SEVERE,"\n\tdetails:\n" + e); } + return ref; } - private MapperSchema getMapperSchema(Query query, OWLOntology ontology, OWLClass cls, String cls_description) { + private MapperSchema getMapperSchema(Query query, OWLClass cls, String cls_description) { //Convert from OWL Class to OpenAPI Schema. - MapperSchema mapperSchema = new MapperSchema(this.ontologies, cls, cls_description, schemaNames, ontology, this.config_data.getConfigFlags()); + MapperSchema mapperSchema = new MapperSchema(this.ontologies, cls, cls_description, schemaNames, this.config_data.getConfigFlags()); //Write queries query.write_readme(mapperSchema.name); //Create the OpenAPI schema @@ -223,16 +227,8 @@ private MapperSchema getMapperSchema(Query query, OWLOntology ontology, OWLClass return mapperSchema; } - private void addOpenAPIPaths(PathGenerator pathGenerator, MapperSchema mapperSchema, OWLClass cls) { - if (this.selected_classes != null && !this.selected_classes.contains(cls)) { - logger.info("Ignoring class " + cls.toString()); - } else { - this.add_path(pathGenerator, mapperSchema); - } - } - private void setSchemaNames(Set classes) { - for (OWLClass cls : classes) { + for (OWLClass cls: classes) { this.schemaNames.put(cls.getIRI(), cls.getIRI().getShortForm()); } } @@ -243,10 +239,10 @@ private void setSchemaNames(Set classes) { * @param classes the classes you want the description for * @param ontology the ontology from where we will extract the descriptions */ - private void setSchemaDrescriptions(Set classes, OWLOntology ontology){ + private void setSchemaDescriptions(Set classes, OWLOntology ontology) { for (OWLClass cls: classes) { System.out.println(cls); - schemaDescriptions.put(cls.getIRI(), ObaUtils.getDescription(cls, ontology, this.config_data.getConfigFlagValue(CONFIG_FLAG.DEFAULT_DESCRIPTIONS))); + this.schemaDescriptions.put(cls.getIRI(), ObaUtils.getDescription(cls, ontology, this.config_data.getConfigFlagValue(CONFIG_FLAG.DEFAULT_DESCRIPTIONS))); } } @@ -266,17 +262,17 @@ private void add_path(PathGenerator pathGenerator, MapperSchema mapperSchema) { mapperSchema.getCls().getIRI().getIRIString())); } - - public List filter_classes() { - List selected_classes_iri = this.config_data.getClasses(); - ArrayList filtered_classes = new ArrayList(); - for (OWLOntology ontology : this.ontologies) { - for (OWLClass cls : ontology.getClassesInSignature()) { + public Set filter_classes() { + Set selected_classes_iri = this.config_data.getClasses(); + Set filtered_classes = new HashSet<>(); + for (OWLOntology ontology: this.ontologies) { + for (OWLClass cls: ontology.getClassesInSignature()) { if (selected_classes_iri.contains(cls.getIRI().toString())) { filtered_classes.add(cls); } } } + return filtered_classes; } } From 01c7150363bd1ab662905f2640d11baa22b0e0e1 Mon Sep 17 00:00:00 2001 From: Christopher Weedall <5010253+cweedall@users.noreply.github.com> Date: Fri, 17 May 2024 23:26:37 -0500 Subject: [PATCH 08/10] rewrite visitor class; list to set; fix affected tests --- .../java/edu/isi/oba/RestrictionVisitor.java | 751 +++++++++--------- .../java/edu/isi/oba/RestrictionsTest.java | 145 ++-- 2 files changed, 451 insertions(+), 445 deletions(-) diff --git a/src/main/java/edu/isi/oba/RestrictionVisitor.java b/src/main/java/edu/isi/oba/RestrictionVisitor.java index e66a7ab..3a5af6d 100644 --- a/src/main/java/edu/isi/oba/RestrictionVisitor.java +++ b/src/main/java/edu/isi/oba/RestrictionVisitor.java @@ -2,14 +2,15 @@ import static edu.isi.oba.Oba.logger; -import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Set; +import javax.annotation.Nonnull; + import org.semanticweb.owlapi.model.*; +import org.semanticweb.owlapi.reasoner.structural.StructuralReasonerFactory; import org.semanticweb.owlapi.util.IRIShortFormProvider; import org.semanticweb.owlapi.util.SimpleIRIShortFormProvider; @@ -37,60 +38,145 @@ public class RestrictionVisitor implements OWLObjectVisitor { private final IRIShortFormProvider sfp = new SimpleIRIShortFormProvider(); - private final Set processedClasses; + private final Set processedClasses = new HashSet(); private final OWLClass cls; - private final OWLOntology onto; + private final Set ontologies; String property_name; - OWLClass owlThing; + private OWLClass owlThing; - public Map> restrictionsValuesFromClass; + private Map> restrictionsValuesFromClass = new HashMap<>(); - public List propertiesFromObjectRestrictions; - public Map> propertiesFromObjectRestrictions_ranges; - public List propertiesFromDataRestrictions; - public Map> propertiesFromDataRestrictions_ranges; - public List valuesFromDataRestrictions_ranges; - public Map> enums; - - RestrictionVisitor(OWLClass visitedClass, OWLOntology onto, OWLClass owlThing, String propertyName ) { - processedClasses = new HashSet(); + private Set propertiesFromObjectRestrictions = new HashSet<>(); + private Map> propertiesFromObjectRestrictions_ranges = new HashMap<>(); + private Set propertiesFromDataRestrictions = new HashSet<>(); + private Map> propertiesFromDataRestrictions_ranges = new HashMap<>(); + private Set valuesFromDataRestrictions_ranges = new HashSet<>(); + private Map> enums = new HashMap<>(); + + /** + * Constructor for restriction visitor. + * + * @param visitedClass the class being checked for restrictions + * @param ontologies the set of loaded ontologies (presumably the visited class is within one of these) + * @param propertyName + */ + RestrictionVisitor(OWLClass visitedClass, Set ontologies, String propertyName) { this.cls = visitedClass; - this.onto = onto; + this.ontologies = ontologies; this.property_name = propertyName; - this.owlThing = owlThing; - this.propertiesFromObjectRestrictions_ranges= new HashMap<>(); - this.propertiesFromObjectRestrictions = new ArrayList<>(); - this.restrictionsValuesFromClass = new HashMap<>(); - this.propertiesFromDataRestrictions = new ArrayList<>(); - this.propertiesFromDataRestrictions_ranges= new HashMap<>(); - this.valuesFromDataRestrictions_ranges = new ArrayList<>(); - this.enums = new HashMap<>(); - } - @Override - public void visit(OWLClass ce) { - if (!this.processedClasses.contains(ce)) { - // If we are processing inherited restrictions then we recursively visit named supers. - this.processedClasses.add(ce); - for (OWLSubClassOfAxiom ax: this.onto.getSubClassAxiomsForSubClass(ce)) { - ax.getSuperClass().accept(this); + this.ontologies.forEach((ontology) -> { + if (ontology.containsClassInSignature(this.cls.getIRI())) { + this.owlThing = new StructuralReasonerFactory().createReasoner(ontology).getTopClassNode().getRepresentativeElement(); } + }); + } + + /** + * Convenience method for adding/updating restrictions to a property (i.e. in the {@link restrictionsValuesFromClass} map). + * + * @param propertyName the property name to attach the restriction to + * @param restrictionKey the restriction's name/key + * @param restrictionValue the restriction's value + */ + private void addRestrictionValueToProperty(String propertyName, String restrictionKey, String restrictionValue) { + Map restrictions = new HashMap<>(); + + if (!this.restrictionsValuesFromClass.containsKey(propertyName)) { + logger.info("No restriction values for " + propertyName + " exist yet. Creating now."); + } else { + restrictions = this.restrictionsValuesFromClass.get(propertyName); + } + + if (restrictions.containsKey(restrictionKey)) { + // What should happen here? There is a chance they differ? + logger.warning("Restriction value (= \"" + restrictionValue + "\") for " + propertyName + " already exists. Ignoring..."); + } else { + logger.info("Adding restriction <\"" + restrictionKey + "\", \"" + restrictionValue + "\"> to property \"" + propertyName + "\".\n"); + restrictions.put(restrictionKey, restrictionValue); + this.restrictionsValuesFromClass.put(propertyName, restrictions); + } + } + + /** + * Convenience method for adding/updating object restriction ranges to a property (i.e. in the {@link propertiesFromObjectRestrictions_ranges} map). + * + * @param propertyName the property name to attach the restriction range to + * @param range the object restriction range + */ + private void addObjectRestrictionRangeToProperty(String propertyName, String range) { + Set restrictionRanges = new HashSet<>(); + + if (!this.propertiesFromObjectRestrictions_ranges.containsKey(propertyName)) { + logger.info("No object restriction ranges for " + propertyName + " exist yet. Creating now."); + } else { + restrictionRanges = this.propertiesFromObjectRestrictions_ranges.get(propertyName); + } + + if (restrictionRanges.contains(range)) { + // What should happen here? There is a chance they differ? + logger.warning("Restriction range (= \"" + range + "\") for " + propertyName + " already exists. Ignoring..."); + } else { + logger.info("Adding object restriction range \"" + range + "\" to property \"" + propertyName + "\".\n"); + restrictionRanges.add(range); + this.propertiesFromObjectRestrictions_ranges.put(propertyName, restrictionRanges); + } + } + + /** + * Convenience method for adding/updating data restriction ranges to a property (i.e. in the {@link propertiesFromDataRestrictions_ranges} map). + * + * @param propertyName the property name to attach the restriction range to + * @param range the data restriction range + */ + private void addDataRestrictionRangeToProperty(String propertyName, String range) { + Set restrictionRanges = new HashSet<>(); + + if (!this.propertiesFromDataRestrictions_ranges.containsKey(propertyName)) { + logger.info("No data restriction ranges for " + propertyName + " exist yet. Creating now."); + } else { + restrictionRanges = this.propertiesFromDataRestrictions_ranges.get(propertyName); + } + + if (restrictionRanges.contains(range)) { + // What should happen here? There is a chance they differ? + logger.warning("Restriction range (= \"" + range + "\") for " + propertyName + " already exists. Ignoring..."); + } else { + logger.info("Adding object restriction range \"" + range + "\" to property \"" + propertyName + "\".\n"); + restrictionRanges.add(range); + this.propertiesFromDataRestrictions_ranges.put(propertyName, restrictionRanges); } } @Override - public void visit( OWLEquivalentClassesAxiom ce ) { + public void visit(@Nonnull OWLClass ce) { + // avoid cycles + if (!this.processedClasses.contains(ce)) { + // If we are processing inherited restrictions then we recursively visit named supers. + this.processedClasses.add(ce); + + for (OWLOntology ont: this.ontologies) { + ont.subClassAxiomsForSubClass(ce) + .forEach(ax -> ax.getSuperClass().accept(this)); + } + } + } + + @Override + public void visit(@Nonnull OWLEquivalentClassesAxiom ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); // If equivalent class axiom AND contains owl:oneOf, then we're looking at an ENUM class. ce.classExpressions().filter((e) -> e instanceof OWLObjectOneOf).forEach((oneOfObj) -> { - var enumValues = new ArrayList(); - ((OWLObjectOneOf) oneOfObj).getOperandsAsList().forEach((indv) -> { - enumValues.add(this.sfp.getShortForm(((OWLNamedIndividual) indv).getIRI())); - }); + var enumValues = ((OWLObjectOneOf) oneOfObj).getOperandsAsList(); + if (enumValues != null && !enumValues.isEmpty()) { + // Add enum individuals to restriction range + enumValues.forEach((indv) -> { + this.addObjectRestrictionRangeToProperty(this.property_name, this.sfp.getShortForm(((OWLNamedIndividual) indv).getIRI())); + }); - if (!enumValues.isEmpty()) { - this.enums.put(this.cls.getIRI(), enumValues); + // For class enums, this is a misnomer. There are no properties, in this case, and the property name will be an empty string. Thi + this.addRestrictionValueToProperty(this.property_name, "enum", ""); } }); @@ -101,473 +187,370 @@ public void visit( OWLEquivalentClassesAxiom ce ) { } /** - * This method gets called when a class expression is an existential - * (someValuesFrom) restriction and it asks us to visit it + * Convenience method for adding restriction values and ranges from a visit to {@link OWLNaryBooleanClassExpression} (i.e. {@link OWLObjectUnionOf} or {@link OWLObjectIntersectionOf}). + * + * @param ce the OWLNaryBooleanClassExpression object */ - @Override - public void visit(OWLObjectSomeValuesFrom ce) { - Map restrictionsValues = new HashMap<>(); + private void visitOWLNaryBooleanClassExpression(@Nonnull OWLNaryBooleanClassExpression ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - for (OWLObjectProperty property: ce.getObjectPropertiesInSignature()) { - this.propertiesFromObjectRestrictions.add(property); - this.property_name = this.sfp.getShortForm(property.getIRI()); - } + String restrictionKey = (ce instanceof OWLObjectUnionOf) ? "unionOf" : "intersectionOf"; - OWLClassExpression ceFiller = ce.getFiller(); - if (ceFiller instanceof OWLObjectUnionOf || ceFiller instanceof OWLObjectIntersectionOf || ceFiller instanceof OWLObjectOneOf) { - restrictionsValues.put("someValuesFrom", ""); - this.restrictionsValuesFromClass.put(this.property_name, restrictionsValues); - ce.getFiller().accept(this); - } else { - if (ceFiller.asOWLClass().equals(owlThing)) { - logger.info("Ignoring owl:Thing range" + this.property_name); + this.addRestrictionValueToProperty(this.property_name, restrictionKey, ""); + + // Loop through each item in the union/intersection and accept visits. + for (OWLClassExpression e: ce.getOperands()) { + if (e.isOWLClass()) { + this.addObjectRestrictionRangeToProperty(this.property_name, this.sfp.getShortForm(e.asOWLClass().getIRI())); } else { - if (this.propertiesFromObjectRestrictions_ranges.containsKey(this.property_name)) { - this.propertiesFromObjectRestrictions_ranges.get(this.property_name).add(this.sfp.getShortForm(ceFiller.asOWLClass().getIRI())); - } else { - List ranges = new ArrayList<>(); - ranges.add(this.sfp.getShortForm(ceFiller.asOWLClass().getIRI())); - this.propertiesFromObjectRestrictions_ranges.put(this.property_name, ranges); - } + e.accept(this); } - - restrictionsValues.put("someValuesFrom", ""); - this.restrictionsValuesFromClass.put(this.property_name, restrictionsValues); } } - + + @Override + public void visit(@Nonnull OWLObjectUnionOf ce) { + this.visitOWLNaryBooleanClassExpression(ce); + } + + @Override + public void visit(@Nonnull OWLObjectIntersectionOf ce) { + this.visitOWLNaryBooleanClassExpression(ce); + } + /** - * This method gets called when a class expression is a universal - * (allValuesFrom) restriction and it asks us to visit it + * Convenience method for adding restriction values and ranges from a visit to {@link OWLQuantifiedObjectRestriction} + * (i.e. {@link OWLObjectAllValuesFrom}, {@link OWLObjectSomeValuesFrom}, or + * {@link OWLObjectCardinalityRestriction [subinterfaces: {@link OWLObjectExactCardinality}, {@link OWLObjectMaxCardinality}, or {@link OWLObjectMinCardinality}]). + * + * @param ce the {@link OWLQuantifiedObjectRestriction} object */ - @Override - public void visit(OWLObjectAllValuesFrom ce) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - Map restrictionsValues = new HashMap<>(); - for (OWLObjectProperty property: ce.getObjectPropertiesInSignature()) { - propertiesFromObjectRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); + private void visitOWLQuantifiedObjectRestriction(@Nonnull OWLQuantifiedObjectRestriction or) { + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + or); + + this.property_name = this.sfp.getShortForm(or.getProperty().asOWLObjectProperty().getIRI()); + + String restrictionKey = ""; + + if (or instanceof OWLObjectAllValuesFrom) { + restrictionKey = "allValuesFrom"; + } else if (or instanceof OWLObjectSomeValuesFrom) { + restrictionKey = "someValuesFrom"; + } else if (or instanceof OWLObjectMinCardinality) { + restrictionKey = "minCardinality"; + } else if (or instanceof OWLObjectMaxCardinality) { + restrictionKey = "maxCardinality"; + } else if (or instanceof OWLObjectExactCardinality) { + restrictionKey = "exactCardinality"; } - if (ce.getFiller() instanceof OWLObjectUnionOf || ce.getFiller() instanceof OWLObjectIntersectionOf) { - ce.getFiller().accept(this); + // If it is a cardinality type, set the restriction's value, otherwise an empty string. + String restrictionValue = (or instanceof OWLObjectCardinalityRestriction) ? Integer.toString(((OWLObjectCardinalityRestriction) or).getCardinality()) : ""; + + this.addRestrictionValueToProperty(this.property_name, restrictionKey, restrictionValue); + + final var ce = or.getFiller(); + if (ce instanceof OWLObjectUnionOf || ce instanceof OWLObjectIntersectionOf || ce instanceof OWLObjectOneOf) { + ce.accept(this); } else { - List ranges = new ArrayList<>(); - ranges.add(sfp.getShortForm(ce.getFiller().asOWLClass().getIRI())); - if (ce.getFiller().asOWLClass().equals(owlThing)) { - logger.info("Ignoring owl:Thing range" + property_name); + if (ce.asOWLClass().equals(this.owlThing)) { + logger.info("Ignoring owl:Thing range" + this.property_name); } else { - propertiesFromObjectRestrictions_ranges.put(property_name, ranges); + this.addObjectRestrictionRangeToProperty(this.property_name, this.sfp.getShortForm(ce.asOWLClass().getIRI())); } - - restrictionsValues.put("allValuesFrom", ""); - restrictionsValuesFromClass.put(property_name, restrictionsValues); } } - + + /** + * This method gets called when a class expression is an existential + * (someValuesFrom) restriction and it asks us to visit it + */ @Override - public void visit(OWLObjectUnionOf ce) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - - // Loop through each item in the union and accept visits. - for (OWLClassExpression e: ce.getOperands()) { - e.accept(this); - } + public void visit(@Nonnull OWLObjectSomeValuesFrom ce) { + this.visitOWLQuantifiedObjectRestriction(ce); } - + + /** + * This method gets called when a class expression is a universal + * (allValuesFrom) restriction and it asks us to visit it + */ @Override - public void visit(OWLObjectIntersectionOf ce) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - - // Loop through each item in the intersection and accept visits. - for (OWLClassExpression e: ce.getOperands()) { - e.accept(this); - } + public void visit(@Nonnull OWLObjectAllValuesFrom ce) { + this.visitOWLQuantifiedObjectRestriction(ce); } @Override - public void visit(OWLObjectMinCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - setPropertiesWithCardinality(ce, "minCardinality"); + public void visit(@Nonnull OWLObjectMinCardinality ce) { + this.visitOWLQuantifiedObjectRestriction(ce); } @Override - public void visit(OWLObjectMaxCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - setPropertiesWithCardinality(ce,"maxCardinality"); + public void visit(@Nonnull OWLObjectMaxCardinality ce) { + this.visitOWLQuantifiedObjectRestriction(ce); } @Override - public void visit(OWLObjectExactCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - setPropertiesWithCardinality(ce, "exactCardinality"); + public void visit(@Nonnull OWLObjectExactCardinality ce) { + this.visitOWLQuantifiedObjectRestriction(ce); } @Override - public void visit(OWLObjectComplementOf ce) { + public void visit(@Nonnull OWLObjectComplementOf ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - Map restrictionsValues = new HashMap(); + String complementName = this.sfp.getShortForm(ce.getOperand().asOWLClass().getIRI()); - restrictionsValues.put("complementOf", complementName ); - restrictionsValuesFromClass.put("complementOf", restrictionsValues); + this.addRestrictionValueToProperty("complementOf", "complementOf", complementName); } @Override - public void visit(OWLObjectHasValue ce) { + public void visit(@Nonnull OWLObjectHasValue ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - - for (OWLObjectProperty property: ce.getObjectPropertiesInSignature()) { - List ranges = new ArrayList(); - Map restrictionsValues = new HashMap(); - this.property_name = this.sfp.getShortForm(property.getIRI()); + this.property_name = this.sfp.getShortForm(ce.getProperty().asOWLObjectProperty().getIRI()); - restrictionsValues.put("objectHasValue", this.sfp.getShortForm(((OWLNamedIndividual)ce.getFiller()).getIRI())); + if (ce.getFiller() instanceof OWLObjectUnionOf || ce.getFiller() instanceof OWLObjectIntersectionOf) { + ce.getFiller().accept(this); + } else { + for (OWLObjectProperty property: ce.getObjectPropertiesInSignature()) { + this.ontologies.forEach((ontology) -> { + // If object property has object(s) in its range, we want to set references to the object class. + var obRangeAxioms = ontology.getObjectPropertyRangeAxioms(property); + if (obRangeAxioms.isEmpty()) { + logger.warning("\tObject has value (named individual) but there is no associated class/reference for the value. Ontology may have errors."); + } else { + obRangeAxioms.forEach((obRangeAxiom) -> { + obRangeAxiom.getRange().classesInSignature().forEach((owlClass) -> { + this.addRestrictionValueToProperty(this.property_name, "objectHasReference", this.sfp.getShortForm(owlClass.getIRI())); + }); + }); + } - // If object property has object(s) in its range, we want to set references to the object class. - var obRangeAxioms = this.onto.getObjectPropertyRangeAxioms(property); - if (obRangeAxioms.isEmpty()) { - logger.warning("\tObject has value (named individual) but there is no associated class/reference for the value. Ontology may have errors."); - } else { - obRangeAxioms.forEach((obRangeAxiom) -> { - obRangeAxiom.getRange().classesInSignature().forEach((owlClass) -> { - restrictionsValues.put("objectHasReference", this.sfp.getShortForm(owlClass.getIRI())); - }); + this.propertiesFromObjectRestrictions.add(property); + this.addRestrictionValueToProperty(this.property_name, "objectHasValue", this.sfp.getShortForm(((OWLNamedIndividual) ce.getFiller()).getIRI())); + this.addObjectRestrictionRangeToProperty(this.property_name, "defaultValue"); }); } - - this.restrictionsValuesFromClass.put(this.property_name, restrictionsValues); - this.propertiesFromObjectRestrictions.add(property); - ranges.add("defaultValue"); - this.propertiesFromObjectRestrictions_ranges.put(this.property_name, ranges); } } @Override - public void visit(OWLObjectOneOf ce) { + public void visit(@Nonnull OWLObjectOneOf ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - List ranges = new ArrayList(); - Map restrictionsValues = new HashMap(); - if (!property_name.isEmpty()) { + if (!this.property_name.isBlank()) { for (OWLIndividual individual: ce.getIndividuals()) { - ranges.add(individual.toString()); + this.addObjectRestrictionRangeToProperty(this.property_name, this.sfp.getShortForm(individual.asOWLNamedIndividual().getIRI())); } - restrictionsValues.put("oneOf", "someValuesFrom"); - this.restrictionsValuesFromClass.put(this.property_name, restrictionsValues); - this.propertiesFromObjectRestrictions_ranges.put(this.property_name, ranges); + this.addRestrictionValueToProperty(this.property_name, "oneOf", "someValuesFrom"); } } - + /** - * This method gets called when a class expression is a universal - * (allValuesFrom) restriction and it asks us to visit it + * Convenience method for adding restriction values and ranges from a visit to {@link OWLNaryDataRange} (i.e. {@link OWLDataUnionOf} or {@link OWLDataIntersectionOf}). + * + * @param ce the OWLNaryDataRange object */ - @Override - public void visit(OWLDataAllValuesFrom ce) { - logger.info( "\n Analyzed Class: " + this.cls + " with axiom: " + ce); - Map restrictionsValues = new HashMap(); - for (OWLDataProperty property: ce.getDataPropertiesInSignature()) { - propertiesFromDataRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); - } + private void visitOWLNaryDataRange(@Nonnull OWLNaryDataRange ce) { + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - if (ce.getFiller() instanceof OWLDataUnionOf || ce.getFiller() instanceof OWLDataIntersectionOf) { - ce.getFiller().accept(this); - } else { - List ranges = new ArrayList(); - ranges.add(sfp.getShortForm(ce.getFiller().asOWLDatatype().getIRI())); - if (ce.getFiller().asOWLDatatype().equals(owlThing)) { - logger.info("Ignoring owl:Thing range" + property_name); - } else { - propertiesFromDataRestrictions_ranges.put(property_name,ranges); - } + String restrictionKey = (ce instanceof OWLDataUnionOf) ? "unionOf" : "intersectionOf"; - restrictionsValues.put("allValuesFrom", ""); - restrictionsValuesFromClass.put(property_name, restrictionsValues); + this.addRestrictionValueToProperty(this.property_name, restrictionKey, ""); + + // Loop through each item in the union/intersection and accept visits. + for (OWLDataRange e: ce.getOperands()) { + this.addDataRestrictionRangeToProperty(this.property_name, this.sfp.getShortForm(e.asOWLDatatype().getIRI())); + e.accept(this); } } - - /** - * This method gets called when a class expression is a some - * (someValuesFrom) restriction and it asks us to visit it - */ + @Override - public void visit(OWLDataSomeValuesFrom ce) { - logger.info( "\n Analyzed Class: " + this.cls + " with axiom: " + ce); - Map restrictionsValues = new HashMap(); - for (OWLDataProperty property: ce.getDataPropertiesInSignature()) { - this.propertiesFromDataRestrictions.add(property); - this.property_name = this.sfp.getShortForm(property.getIRI()); + public void visit(@Nonnull OWLDataUnionOf ce) { + this.visitOWLNaryDataRange(ce); + } + + @Override + public void visit(@Nonnull OWLDataIntersectionOf ce) { + this.visitOWLNaryDataRange(ce); + } + + /** + * Convenience method for adding restriction values and ranges from a visit to {@link OWLQuantifiedDataRestriction} + * (i.e. {@link OWLDataAllValuesFrom}, {@link OWLDataSomeValuesFrom}, or + * {@link OWLDataCardinalityRestriction} [subinterfaces: {@link OWLDataMinCardinality}, {@link OWLDataMaxCardinality}, or {@link OWLDataExactCardinality}]). + * + * @param ce the {@link OWLQuantifiedDataRestriction} object + */ + private void visitOWLQuantifiedDataRestriction(@Nonnull OWLQuantifiedDataRestriction dr) { + logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + dr); + + this.property_name = this.sfp.getShortForm(dr.getProperty().asOWLDataProperty().getIRI()); + + String restrictionKey = ""; + + if (dr instanceof OWLDataAllValuesFrom) { + restrictionKey = "allValuesFrom"; + } else if (dr instanceof OWLDataSomeValuesFrom) { + restrictionKey = "someValuesFrom"; + } else if (dr instanceof OWLDataMinCardinality) { + restrictionKey = "minCardinality"; + } else if (dr instanceof OWLDataMaxCardinality) { + restrictionKey = "maxCardinality"; + } else if (dr instanceof OWLDataExactCardinality) { + restrictionKey = "exactCardinality"; } - OWLDataRange ceFiller = ce.getFiller(); - if (ceFiller instanceof OWLDataUnionOf || ceFiller instanceof OWLDataIntersectionOf) { - restrictionsValues.put("someValuesFrom", ""); - this.restrictionsValuesFromClass.put(property_name, restrictionsValues); - ce.getFiller().accept(this); - } else { - List ranges = new ArrayList(); - ranges.add(this.sfp.getShortForm(ceFiller.asOWLDatatype().getIRI())); + // If it is a cardinality type, set the restriction's value, otherwise an empty string. + final String restrictionValue = (dr instanceof OWLDataCardinalityRestriction) ? Integer.toString(((OWLDataCardinalityRestriction) dr).getCardinality()) : ""; - if (ceFiller.asOWLDatatype().equals(owlThing)) { - logger.info("Ignoring owl:Thing range" + property_name); - } else { - propertiesFromDataRestrictions_ranges.put(property_name, ranges); - } + this.addRestrictionValueToProperty(this.property_name, restrictionKey, restrictionValue); - restrictionsValues.put("someValuesFrom", ""); - this.restrictionsValuesFromClass.put(property_name, restrictionsValues); + final var ce = dr.getFiller(); + if (ce instanceof OWLDataUnionOf || ce instanceof OWLDataIntersectionOf || ce instanceof OWLDataOneOf) { + ce.accept(this); + } else { + this.addDataRestrictionRangeToProperty(this.property_name, this.sfp.getShortForm(ce.asOWLDatatype().getIRI())); } } + /** + * This method gets called when a class expression is a universal + * (allValuesFrom) restriction and it asks us to visit it + */ @Override - public void visit(OWLDataUnionOf ce) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - - // Loop through each item in the union and accept visits. - for (OWLDataRange e: ce.getOperands()) { - e.accept(this); - } + public void visit(@Nonnull OWLDataAllValuesFrom ce) { + this.visitOWLQuantifiedDataRestriction(ce); } + /** + * This method gets called when a class expression is a some + * (someValuesFrom) restriction and it asks us to visit it + */ @Override - public void visit(OWLDataIntersectionOf ce) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - - // Loop through each item in the intersection and accept visits. - for (OWLDataRange e: ce.getOperands()) { - e.accept(this); - } + public void visit(@Nonnull OWLDataSomeValuesFrom ce) { + this.visitOWLQuantifiedDataRestriction(ce); } @Override - public void visit(OWLDataMinCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - setDataPropertiesWithCardinality(ce,"minCardinality"); + public void visit(@Nonnull OWLDataMinCardinality ce) { + this.visitOWLQuantifiedDataRestriction(ce); } @Override - public void visit(OWLDataMaxCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - setDataPropertiesWithCardinality(ce,"maxCardinality"); + public void visit(@Nonnull OWLDataMaxCardinality ce) { + this.visitOWLQuantifiedDataRestriction(ce); } @Override - public void visit(OWLDataExactCardinality ce) { - logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - setDataPropertiesWithCardinality(ce,"exactCardinality"); + public void visit(@Nonnull OWLDataExactCardinality ce) { + this.visitOWLQuantifiedDataRestriction(ce); } @Override - public void visit(OWLDataOneOf ce) { + public void visit(@Nonnull OWLDataOneOf ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - List ranges = new ArrayList(); - Map restrictionsValues = new HashMap(); for (OWLLiteral value: ce.getValues()) { - ranges.add(this.sfp.getShortForm(value.getDatatype().getIRI())); this.valuesFromDataRestrictions_ranges.add(value.getLiteral()); - restrictionsValues.put("oneOf", ""); - this.restrictionsValuesFromClass.put(this.property_name, restrictionsValues); - this.propertiesFromDataRestrictions_ranges.put(this.property_name, ranges); + this.addRestrictionValueToProperty(this.property_name, "oneOf", ""); + this.addDataRestrictionRangeToProperty(this.property_name, this.sfp.getShortForm(value.getDatatype().getIRI())); } } @Override - public void visit(OWLDataComplementOf ce) { + public void visit(@Nonnull OWLDataComplementOf ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - List ranges = new ArrayList(); - Map restrictionsValues = new HashMap(); + for (OWLDatatype value: ce.getDatatypesInSignature()) { - ranges.add(this.sfp.getShortForm(value.getIRI())); - restrictionsValues.put("complementOf", ""); - restrictionsValuesFromClass.put(this.property_name, restrictionsValues); - propertiesFromDataRestrictions_ranges.put(this.property_name, ranges); + this.addRestrictionValueToProperty(this.property_name, "complementOf", ""); + this.addDataRestrictionRangeToProperty(this.property_name, this.sfp.getShortForm(value.getIRI())); } } @Override - public void visit(OWLDataHasValue ce) { + public void visit(@Nonnull OWLDataHasValue ce) { logger.info("Analyzing restrictions of Class: " + this.cls + " with axiom: " + ce); - List ranges = new ArrayList(); - Map restrictionsValues = new HashMap(); - for (OWLDataProperty property: ce.getDataPropertiesInSignature()) { - property_name = this.sfp.getShortForm(property.getIRI()); - propertiesFromDataRestrictions.add(property); - restrictionsValues.put("dataHasValue", ce.getFiller().getLiteral()); - restrictionsValuesFromClass.put(property_name, restrictionsValues); - - for (OWLDatatype value: ce.getDatatypesInSignature()) { - ranges.add(this.sfp.getShortForm(value.getIRI())); - propertiesFromDataRestrictions_ranges.put(this.property_name, ranges); - } - } - } - - /** - * Method that given a class expression of any cardinality type will set it and its value. - * @param ce object cardinality value e.g. OWLObjectExactCardinality - * @param restriction string value of restriction e.g. "exactCardinality" - */ - public void setPropertiesWithCardinality(OWLObjectCardinalityRestriction ce, String restriction) { - String property_name = ""; - List ranges = new ArrayList(); - Map restrictionsValues = new HashMap(); - for (OWLObjectProperty property: ce.getObjectPropertiesInSignature()) { - propertiesFromObjectRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); - ranges.add(sfp.getShortForm(ce.getFiller().asOWLClass().getIRI())); - propertiesFromObjectRestrictions_ranges.put(property_name,ranges); - } - this.property_name = property_name; + this.property_name = this.sfp.getShortForm(ce.getProperty().asOWLDataProperty().getIRI()); - restrictionsValues.put(restriction, Integer.toString(ce.getCardinality())); - restrictionsValuesFromClass.put(property_name, restrictionsValues); - } - - /** - * Method that given a set of ranges and properties will set them according to the boolean restriction . - * @param ranges a set of class ranges that compose the boolean restriction - * @param properties object properties expression that have the boolean restriction - * @param restriction string value of restriction e.g. "unionOf" - */ - public void setBooleanCombinationProperties( Set ranges, Set properties, String restriction) { - Map restrictionsValues = new HashMap(); - //if the expression ce is not part of a composed expression (existential or universal) - if (property_name.isEmpty()) { - for (OWLObjectProperty property: properties) { - propertiesFromObjectRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); - restrictionsValues.put(restriction, ""); - restrictionsValuesFromClass.put(property_name, restrictionsValues); - } - } else { - List rangeList = new ArrayList(); - for (OWLClassExpression range: ranges) { - rangeList.add(sfp.getShortForm(range.asOWLClass().getIRI())); - if (range.asOWLClass().equals(owlThing)) { - logger.info("Ignoring owl:Thing range" + property_name); - } else { - propertiesFromObjectRestrictions_ranges.put(property_name,rangeList); - } - } + this.addRestrictionValueToProperty(this.property_name, "dataHasValue", ce.getFiller().getLiteral()); - if (!restrictionsValuesFromClass.isEmpty()) { - for (String j: restrictionsValuesFromClass.keySet()) { - if (j.equals(property_name)) { - Map value = restrictionsValuesFromClass.get(property_name); - for (String i: value.keySet() ) { - restrictionsValues.put(restriction, i); - } - - restrictionsValuesFromClass.put(property_name, restrictionsValues); - } - } - } else { - restrictionsValues.put(restriction, ""); - restrictionsValuesFromClass.put(property_name, restrictionsValues); - } - } - } - - /** - * Method that given a set of ranges and properties will set them according to the boolean restriction . - * @param ranges a set of class ranges that compose the boolean restriction - * @param properties data properties expression that have the boolean restriction - * @param restriction string value of restriction e.g. "unionOf" - */ - public void setBooleanCombinationDataProperties(Set ranges, Set properties, String restriction) { - Map restrictionsValues = new HashMap(); - //if the expression ce is not part of a composed expression (existential or universal) - if (property_name.equals("")) { - for (OWLDataProperty property: properties) { - propertiesFromDataRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); - restrictionsValues.put(restriction, ""); - restrictionsValuesFromClass.put(property_name, restrictionsValues); - } - } else { - List rangeList = new ArrayList(); - for (OWLDataRange range: ranges) { - rangeList.add(sfp.getShortForm(range.asOWLDatatype().getIRI())); - if (range.getClass().equals(owlThing)) { - logger.info("Ignoring owl: Thing range" + property_name); - } else { - propertiesFromDataRestrictions_ranges.put(property_name,rangeList); - } - } - - if (!restrictionsValuesFromClass.isEmpty()) { - for (String j: restrictionsValuesFromClass.keySet()) { - if (j.equals(property_name)) { - Map value = restrictionsValuesFromClass.get(property_name); - for (String i: value.keySet()) { - restrictionsValues.put(restriction, i); - } - - restrictionsValuesFromClass.put(property_name, restrictionsValues); - break; - } - } - } else { - restrictionsValues.put(restriction, ""); - restrictionsValuesFromClass.put(property_name, restrictionsValues); - } - } - } - - public void setDataPropertiesWithCardinality(OWLDataCardinalityRestriction ce, String restriction) { - String property_name = ""; - List ranges = new ArrayList<>(); - Map restrictionsValues = new HashMap<>(); - for (OWLDataProperty property: ce.getDataPropertiesInSignature()) { - propertiesFromDataRestrictions.add(property); - property_name = sfp.getShortForm(property.getIRI()); - - for (OWLDatatype value: ce.getDatatypesInSignature()) { - ranges.add(sfp.getShortForm(value.getIRI())); - propertiesFromDataRestrictions_ranges.put(property_name,ranges); - } + for (OWLDatatype value: ce.getDatatypesInSignature()) { + this.addDataRestrictionRangeToProperty(this.property_name, this.sfp.getShortForm(value.getIRI())); } - - this.property_name = property_name; - restrictionsValues.put(restriction, Integer.toString(ce.getCardinality())); - restrictionsValuesFromClass.put(property_name, restrictionsValues); } - public Map> getRestrictionsValuesFromClass() { + /** + * Getter for {@link restrictionsValuesFromClass}. + * + * @return a Map of property name keys with values that contain one or more restriction name keys and restriction values + */ + public Map> getRestrictionsValuesFromClass() { return this.restrictionsValuesFromClass; } - public List getPropertiesFromObjectRestrictions() { + /** + * Getter for {@link propertiesFromObjectRestrictions}. + * + * @return a Set of OWL object properties for the class + */ + public Set getPropertiesFromObjectRestrictions() { return this.propertiesFromObjectRestrictions; } - public Map> getPropertiesFromObjectRestrictions_ranges() { + /** + * Getter for {@link propertiesFromObjectRestrictions_ranges}. + * + * @return a Map of OWL object property name keys with values that contain a Set of OWL object restrictions + */ + public Map> getPropertiesFromObjectRestrictions_ranges() { return this.propertiesFromObjectRestrictions_ranges; } - - public List getPropertiesFromDataRestrictions() { - return this.propertiesFromDataRestrictions; - } - public List getValuesFromDataRestrictions_ranges() { - return this.valuesFromDataRestrictions_ranges; + /** + * Getter for {@link propertiesFromDataRestrictions}. + * + * @return a Set of OWL data properties for the class + */ + public Set getPropertiesFromDataRestrictions() { + return this.propertiesFromDataRestrictions; } - public Map> getPropertiesFromDataRestrictions_ranges() { + /** + * Getter for {@link propertiesFromDataRestrictions_ranges}. + * + * @return a Map of OWL object property name keys with values that contain a Set of OWL object restrictions + */ + public Map> getPropertiesFromDataRestrictions_ranges() { return this.propertiesFromDataRestrictions_ranges; } - public List getEnums(IRI classIRI) { + /** + * Getter for {@link valuesFromDataRestrictions_ranges}. + * + * @return a Set of values from the OWL data restrictions + */ + public Set getValuesFromDataRestrictions_ranges() { + return this.valuesFromDataRestrictions_ranges; + } + + /** + * Getter for a specific enumeration (enum). + * + * @param classIRI an IRI of the enum name + * @return a Set of short names for enum individuals + */ + public Set getEnums(IRI classIRI) { return this.enums.get(classIRI); } - public Map> getAllEnums() { + /** + * Getter for map of all enumerations (enums) (i.e. {@link enums}). + * + * @return a Map of IRIs (enum names) keys with values which are a Set of short names for the enum individuals + */ + public Map> getAllEnums() { return this.enums; } } diff --git a/src/test/java/edu/isi/oba/RestrictionsTest.java b/src/test/java/edu/isi/oba/RestrictionsTest.java index ed575ea..cb9db5e 100644 --- a/src/test/java/edu/isi/oba/RestrictionsTest.java +++ b/src/test/java/edu/isi/oba/RestrictionsTest.java @@ -16,7 +16,6 @@ import java.util.logging.Logger; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.semanticweb.owlapi.model.OWLClass; @@ -67,8 +66,8 @@ public void testFunctionalObjectProperty() throws OWLOntologyCreationException, YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#University"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("hasRector"); if (property instanceof io.swagger.v3.oas.models.media.ArraySchema) { @@ -93,8 +92,8 @@ public void testObjectUnionOf() throws OWLOntologyCreationException, Exception { YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#StudyMaterial"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("author"); if (property instanceof ArraySchema) { @@ -127,8 +126,8 @@ public void testObjectIntersectionOf() throws OWLOntologyCreationException, Exce YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#Course"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("hasEvaluationMethod"); if (property instanceof ArraySchema) { @@ -159,8 +158,8 @@ public void testSimpleObjectSomeValuesFrom() throws OWLOntologyCreationException YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#University"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("hasDepartment"); @@ -188,19 +187,29 @@ public void testObjectSomeValuesFrom_ComposedByRestriction() throws OWLOntologyC YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#Student"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("enrolledIn"); if (property instanceof ArraySchema) { - Boolean nullable = ((ArraySchema) property).getNullable(); Schema items = ((ArraySchema) property).getItems(); List itemsValue; if (items instanceof ComposedSchema) { itemsValue = ((ComposedSchema) items).getAnyOf(); + + // If the anyOf list is null, something is wrong. + Assertions.assertNotNull(itemsValue); + + // Verify the expectedResult list size and anyOf list size are equal. + Assertions.assertEquals(expectedResult.size(), itemsValue.size()); + + // The anyOf ordering may differ than the expectedResult list. for (int i = 0; i < itemsValue.size(); i++) { - Assertions.assertEquals(expectedResult.get(i), itemsValue.get(i).get$ref()); + expectedResult.remove(itemsValue.get(i).get$ref()); } + + // If the expectedResult list is now empty, then both lists contained the same reference values (even if in a different order). + Assertions.assertEquals(expectedResult.isEmpty(), true); } } } catch (OWLOntologyCreationException e) { @@ -219,10 +228,10 @@ public void testObjectExactCardinalityWithArraysGenerated() throws OWLOntologyCr YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#AmericanStudent"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); this.configFlags.put(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS, true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("hasRecord"); if (property instanceof ArraySchema) { @@ -251,11 +260,11 @@ public void testObjectExactCardinalityWithRequiredPropertiesAndWithoutArraysGene YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#AmericanStudent"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); this.configFlags.put(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS, false); this.configFlags.put(CONFIG_FLAG.REQUIRED_PROPERTIES_FROM_CARDINALITY, true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); boolean isRequired = schema.getRequired() != null && schema.getRequired().contains("hasRecord"); @@ -300,8 +309,8 @@ public void testObjectMinCardinality() throws OWLOntologyCreationException, Exce YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#AmericanStudent"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("takesCourse"); if (property instanceof ArraySchema) { @@ -330,8 +339,8 @@ public void testObjectMaxCardinality() throws OWLOntologyCreationException, Exce YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#Course"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("hasStudentEnrolled"); if (property instanceof ArraySchema) { @@ -360,8 +369,8 @@ public void testObjectComplementOf() throws OWLOntologyCreationException, Except YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#ProfessorInOtherDepartment"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); if (schema.getNot() != null) { Assertions.assertEquals(expectedResult, schema.getNot().get$ref()); @@ -391,8 +400,8 @@ public void testObjectHasValue() throws OWLOntologyCreationException, Exception YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#ProfessorInArtificialIntelligence"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("belongsTo"); @@ -427,26 +436,38 @@ public void testObjectOneOf() throws OWLOntologyCreationException, Exception { try { this.initializeLogger(); List expectedResult = new ArrayList(); - expectedResult.add(""); - expectedResult.add(""); + // Original full IRIs were: + // expectedResult.add(""); + // expectedResult.add(""); + // Because these are individuals which may up the (sub)set of the Degree enum, we only need their short form name now: + expectedResult.add("MS"); + expectedResult.add("PhD"); YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#Professor"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("hasDegree"); if (property instanceof ArraySchema) { Schema items = ((ArraySchema) property).getItems(); - List itemsValue; if (items instanceof ComposedSchema) { - itemsValue = ((ComposedSchema) items).getEnum(); - for (int i = 0; i < itemsValue.size(); i++) { - Object ref = itemsValue.get(i); - Assertions.assertEquals(expectedResult.get(i), ref.toString()); + final var oneOfValues = ((ComposedSchema) items).getOneOf(); + if (oneOfValues != null && !oneOfValues.isEmpty()) { + final var enumValues = oneOfValues.iterator().next().getEnum(); + for (int i = 0; i < enumValues.size(); i++) { + Object ref = enumValues.get(i); + Assertions.assertEquals(expectedResult.get(i), ref.toString()); + } + } else { + Assertions.fail("Property's oneOf items do not exist."); } + } else { + Assertions.fail("Property's items are not a composed schema type."); } + } else { + Assertions.fail("Property is not an array schema type."); } } catch (OWLOntologyCreationException e) { Assertions.fail("Error in ontology creation: ", e); @@ -464,8 +485,8 @@ public void testFunctionalDataProperty() throws OWLOntologyCreationException, Ex YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#AmericanStudent"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("birthDate"); if (property instanceof io.swagger.v3.oas.models.media.ArraySchema) { @@ -490,9 +511,12 @@ public void testDataUnionOf() throws OWLOntologyCreationException, Exception { YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); + + OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#Course"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("ects"); if (property instanceof ArraySchema) { @@ -527,8 +551,8 @@ public void testDataIntersectionOf() throws OWLOntologyCreationException, Except YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#ProfessorInArtificialIntelligence"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("memberOfOtherDepartments"); if (property instanceof ArraySchema) { @@ -550,7 +574,6 @@ public void testDataIntersectionOf() throws OWLOntologyCreationException, Except /** * This test attempts to get the OAS representation of the SomeValuesFrom restriction of a DataProperty. */ - @Disabled @Test public void testDataSomeValuesFrom() throws OWLOntologyCreationException, Exception { try { @@ -559,14 +582,14 @@ public void testDataSomeValuesFrom() throws OWLOntologyCreationException, Except YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#StudyProgram"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("studyProgramName"); if (property instanceof ArraySchema) { Boolean nullable = ((ArraySchema) property).getNullable(); Assertions.assertEquals(expectedResult, ((ArraySchema) property).getItems().getType()); - Assertions.assertEquals(false, nullable); + Assertions.assertEquals(true, nullable); } } catch (OWLOntologyCreationException e) { Assertions.fail("error in ontology creation: ", e); @@ -587,8 +610,8 @@ public void testDataSomeValuesFrom_ComposedByRestriction() throws OWLOntologyCre YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#ProfessorInArtificialIntelligence"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("memberOfOtherDepartments"); if (property instanceof ArraySchema) { @@ -602,7 +625,7 @@ public void testDataSomeValuesFrom_ComposedByRestriction() throws OWLOntologyCre } } - Assertions.assertEquals(false, nullable); + Assertions.assertEquals(true, nullable); } } catch (OWLOntologyCreationException e) { Assertions.fail("error in ontology creation: ", e); @@ -620,8 +643,8 @@ public void testDataAllValuesFrom() throws OWLOntologyCreationException, Excepti YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#StudyProgram"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("studyProgramName"); if (property instanceof ArraySchema) { @@ -645,8 +668,8 @@ public void testDataOneOf() throws OWLOntologyCreationException, Exception { YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#Person"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("gender"); if (property instanceof ArraySchema) { @@ -677,8 +700,8 @@ public void testDataHasValue() throws OWLOntologyCreationException, Exception { YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#AmericanStudent"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("nationality"); @@ -704,8 +727,8 @@ public void testDataExactCardinality() throws OWLOntologyCreationException,Excep YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#University"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("universityName"); @@ -747,8 +770,8 @@ public void testDataMinCardinality() throws OWLOntologyCreationException, Except YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#Professor"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("researchField"); Integer minItems = ((ArraySchema) property).getMinItems(); @@ -774,8 +797,8 @@ public void testDataMaxCardinality() throws OWLOntologyCreationException, Except YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#Person"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("address"); Integer maxItems = ((ArraySchema) property).getMaxItems(); @@ -801,8 +824,8 @@ public void testDataComplementOf() throws OWLOntologyCreationException,Exception YamlConfig config_data = get_yaml_data("examples/restrictions/config.yaml"); Mapper mapper = new Mapper(config_data); OWLClass cls = mapper.manager.getOWLDataFactory().getOWLClass("https://w3id.org/example#Department"); - String desc = ObaUtils.getDescription(cls, mapper.ontologies.get(0), true); - MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, mapper.ontologies.get(0), this.configFlags); + String desc = ObaUtils.getDescription(cls, mapper.ontologies.stream().findFirst().get(), true); + MapperSchema mapperSchema = new MapperSchema(mapper.ontologies, cls, desc, mapper.schemaNames, this.configFlags); Schema schema = mapperSchema.getSchema(); Object property = schema.getProperties().get("numberOfProfessors"); From efff8928ccbb90aacebc8e867b3128c7a0d028cc Mon Sep 17 00:00:00 2001 From: Christopher Weedall <5010253+cweedall@users.noreply.github.com> Date: Fri, 17 May 2024 23:27:14 -0500 Subject: [PATCH 09/10] list to set; update affected areas from restriction visitor rewrite --- src/main/java/edu/isi/oba/MapperSchema.java | 567 ++++++++++---------- 1 file changed, 272 insertions(+), 295 deletions(-) diff --git a/src/main/java/edu/isi/oba/MapperSchema.java b/src/main/java/edu/isi/oba/MapperSchema.java index 681e774..06cc882 100644 --- a/src/main/java/edu/isi/oba/MapperSchema.java +++ b/src/main/java/edu/isi/oba/MapperSchema.java @@ -4,12 +4,13 @@ import static edu.isi.oba.Oba.logger; import io.swagger.v3.oas.models.examples.Example; +import io.swagger.v3.oas.models.media.ComposedSchema; import io.swagger.v3.oas.models.media.ObjectSchema; import io.swagger.v3.oas.models.media.Schema; import java.util.*; +import java.util.stream.Collectors; -import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.*; import org.semanticweb.owlapi.reasoner.OWLReasoner; import org.semanticweb.owlapi.reasoner.OWLReasonerFactory; @@ -20,70 +21,68 @@ class MapperSchema { - private final OWLReasoner reasoner; + private OWLReasoner reasoner; + private OWLReasonerFactory reasonerFactory; + private OWLClass owlThing; private final IRIShortFormProvider sfp = new SimpleIRIShortFormProvider(); private final String type; private final OWLClass cls; private final String cls_description; - private final List ontologies; - private Map dataProperties; - private Map objectProperties; - private Map properties; - private List required_properties; - private Map> enums; + private OWLOntology ontology_cls; + private final Set ontologies; + private Map dataProperties = new HashMap<>(); + private Map objectProperties = new HashMap<>(); + private Map properties = new HashMap<>(); + private Set required_properties = new HashSet<>(); final String name; private final Map schemaNames; private final Schema schema; - private OWLOntology ontology_cls; - private OWLReasonerFactory reasonerFactory; - public List properties_range; + public Set properties_range = new HashSet<>(); private final Map configFlags = new HashMap<>(); - public List propertiesFromObjectRestrictions; - public Map> propertiesFromObjectRestrictions_ranges; - public String complementOf; - public List propertiesFromDataRestrictions; - public Map> propertiesFromDataRestrictions_ranges; + public Set propertiesFromObjectRestrictions = new HashSet<>(); + public Map> propertiesFromObjectRestrictions_ranges = new HashMap<>(); + public Set propertiesFromDataRestrictions = new HashSet<>(); + public Map> propertiesFromDataRestrictions_ranges = new HashMap<>(); - public List getProperties_range() { - return this.properties_range; - } - - public List getPropertiesFromObjectRestrictions_ranges() { - List aggregatedClasses = new ArrayList<>(); - for (List l: this.propertiesFromObjectRestrictions_ranges.values()) { - aggregatedClasses.addAll(l); - } - - return aggregatedClasses; - } - - public Schema getSchema() { - return this.schema; - } + public String complementOf; - public MapperSchema(List ontologies, OWLClass cls, String clsDescription, Map schemaNames, OWLOntology class_ontology, Map configFlags) { + public MapperSchema(Set ontologies, OWLClass cls, String clsDescription, Map schemaNames, Map configFlags) { this.schemaNames = schemaNames; this.configFlags.putAll(configFlags); this.cls = cls; this.cls_description = clsDescription; this.type = "object"; this.ontologies = ontologies; - this.ontology_cls = class_ontology; - this.reasonerFactory = new StructuralReasonerFactory(); - this.reasoner = reasonerFactory.createReasoner(this.ontology_cls); - this.properties_range = new ArrayList<>(); - this.propertiesFromObjectRestrictions_ranges = new HashMap<>(); - this.propertiesFromObjectRestrictions = new ArrayList<>(); - this.propertiesFromDataRestrictions_ranges = new HashMap<>(); - this.propertiesFromDataRestrictions = new ArrayList<>(); - this.properties = new HashMap<>(); - this.required_properties = new ArrayList<>(); this.complementOf = ""; + + this.reasonerFactory = new StructuralReasonerFactory(); + + // We can pragmatically determine the class's ontology based on the set of ontologies and the class itself. Also set the owl:Thing for that ontology. + this.ontologies.stream().takeWhile(ontology -> ontology.containsClassInSignature(this.cls.getIRI())).forEach((ontology) -> { + this.ontology_cls = ontology; + this.reasoner = reasonerFactory.createReasoner(ontology); + this.owlThing = this.reasoner.getTopClassNode().getRepresentativeElement(); + }); + this.getClassRestrictions(cls); this.name = getSchemaName(cls); this.schema = setSchema(); + + logger.info("\n\n----------------Beginning schema mapping for class \"" + this.cls + "\"."); + } + + public Set getProperties_range() { + return this.properties_range; + } + + public Set getPropertiesFromObjectRestrictions_ranges() { + return this.propertiesFromObjectRestrictions_ranges.values().stream().flatMap(Set::stream).collect(Collectors.toSet()); + } + + public Schema getSchema() { + return this.schema; } private Map setProperties() { @@ -97,31 +96,34 @@ private Schema setSchema() { schema.setName(this.name); schema.setDescription(this.cls_description); - if (this.enums.containsKey(this.cls.getIRI())) { + final var property_schemas = this.getProperties(); + + // Enum schemas have no properties, so the property name for its only schema is empty. + if (property_schemas.get("") != null && property_schemas.get("").getEnum() != null) { // Only string enums allowed in RDF/OWL ?? schema.setType("string"); - schema.setEnum(this.enums.get(this.cls.getIRI())); + schema.setEnum(property_schemas.get("").getEnum()); } else { - // if the Schema is the complement of other Schema - if (complementOf!="") { + if (complementOf != "") { Schema complement = new ObjectSchema(); complement.set$ref(complementOf); schema.not(complement); } + schema.setType(this.type); - schema.setProperties(this.getProperties()); + schema.setProperties(property_schemas); if (this.configFlags.containsKey(CONFIG_FLAG.REQUIRED_PROPERTIES_FROM_CARDINALITY) && this.configFlags.get(CONFIG_FLAG.REQUIRED_PROPERTIES_FROM_CARDINALITY)) { - schema.setRequired(this.required_properties); + schema.setRequired(this.required_properties.stream().collect(Collectors.toList())); } - HashMap exampleMap = new HashMap<>(); + Map exampleMap = new HashMap<>(); exampleMap.put("id", "some_id"); Example example = new Example(); example.setValue(exampleMap); schema.setExample(example); - ArrayList examples = new ArrayList(); + List examples = new ArrayList(); examples.add(example); schema.setExamples(examples); } @@ -156,18 +158,13 @@ private boolean checkDomainClass(OWLClass cls, OWLPropertyDomainAxiom dp) { } /** - * Obtain a list of Codegenproperty of a OWLClass + * Obtain a map of Codegen properties of a OWLClass * * @return A HashMap key: property name, value: SchemaProperty */ private Map getDataProperties() { - OWLOntologyManager m = OWLManager.createOWLOntologyManager(); - OWLDataFactory dataFactory = m.getOWLDataFactory(); - OWLClass owlThing = dataFactory.getOWLThing(); HashMap propertyNameURI = new HashMap<>(); - Map properties = new HashMap<>(); Set properties_class = new HashSet<>(); - Set functional; for (OWLOntology ontology: this.ontologies) { properties_class.addAll(ontology.getAxioms(AxiomType.DATA_PROPERTY_DOMAIN)); @@ -207,26 +204,26 @@ private Map getDataProperties() { propertyNameURI.put(propertyURI, propertyName); //obtain type using the range - List valuesFromDataRestrictions_ranges = new ArrayList(); + Set valuesFromDataRestrictions_ranges = new HashSet<>(); Map restrictionValues = new HashMap(); - for (OWLOntology ontology: this.ontologies) { - RestrictionVisitor restrictionVisitor = new RestrictionVisitor(this.cls, ontology, owlThing, propertyName); - for (OWLDataPropertyRangeAxiom propertyRangeAxiom : ranges) { - OWLDataRange ce = propertyRangeAxiom.getRange(); - ce.accept(restrictionVisitor); - if (ce instanceof OWLDataOneOf) { - valuesFromDataRestrictions_ranges = restrictionVisitor.getValuesFromDataRestrictions_ranges(); - } - } - Map> restrictionsValuesFromClass = restrictionVisitor.getRestrictionsValuesFromClass(); - for (String j : restrictionsValuesFromClass.keySet()) { - if (j.equals(propertyName)) { - restrictionValues = restrictionsValuesFromClass.get(j); - } - } - } - List propertyRanges = getCodeGenTypesByRangeData(ranges, odp); + RestrictionVisitor restrictionVisitor = new RestrictionVisitor(this.cls, this.ontologies, propertyName); + for (OWLDataPropertyRangeAxiom propertyRangeAxiom : ranges) { + OWLDataRange ce = propertyRangeAxiom.getRange(); + ce.accept(restrictionVisitor); + if (ce instanceof OWLDataOneOf) { + valuesFromDataRestrictions_ranges = restrictionVisitor.getValuesFromDataRestrictions_ranges(); + } + } + + Map> restrictionsValuesFromClass = restrictionVisitor.getRestrictionsValuesFromClass(); + for (String j : restrictionsValuesFromClass.keySet()) { + if (j.equals(propertyName)) { + restrictionValues = restrictionsValuesFromClass.get(j); + } + } + + Set propertyRanges = this.getCodeGenTypesByRangeData(ranges, odp); String propertyDescription = ObaUtils.getDescription(odp, this.ontology_cls, this.configFlags.get(CONFIG_FLAG.DEFAULT_DESCRIPTIONS)); MapperDataProperty mapperProperty = new MapperDataProperty(propertyName, propertyDescription, isFunctional, restrictionValues, valuesFromDataRestrictions_ranges, propertyRanges, array, nullable); try { @@ -240,10 +237,10 @@ private Map getDataProperties() { } if (this.configFlags.get(CONFIG_FLAG.DEFAULT_DESCRIPTIONS)) { - properties.putAll(this.getDefaultProperties()); + this.properties.putAll(this.getDefaultProperties()); } - return properties; + return this.properties; } /** @@ -255,18 +252,18 @@ private Map getDataProperties() { */ private Map getDefaultProperties() { Map defaultRestrictionValues = new HashMap(); - List valuesFromDataRestrictions_ranges = new ArrayList(); + Set valuesFromDataRestrictions_ranges = new HashSet(); // Add some typical default properties (e.g. id, lable, type, and description) - MapperDataProperty idProperty = new MapperDataProperty("id", "identifier", true, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new ArrayList(){{add("integer");}}, false, false); - MapperDataProperty labelProperty = new MapperDataProperty("label", "short description of the resource", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new ArrayList(){{add("string");}}, false, true); - MapperDataProperty typeProperty = new MapperDataProperty("type", "type(s) of the resource", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new ArrayList(){{add("string");}}, true, true); - MapperDataProperty descriptionProperty = new MapperDataProperty("description", "small description", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new ArrayList(){{add("string");}}, false, true); + MapperDataProperty idProperty = new MapperDataProperty("id", "identifier", true, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new HashSet(){{add("integer");}}, false, false); + MapperDataProperty labelProperty = new MapperDataProperty("label", "short description of the resource", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new HashSet(){{add("string");}}, false, true); + MapperDataProperty typeProperty = new MapperDataProperty("type", "type(s) of the resource", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new HashSet(){{add("string");}}, true, true); + MapperDataProperty descriptionProperty = new MapperDataProperty("description", "small description", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new HashSet(){{add("string");}}, false, true); // Also add some default property examples of different types (e.g. a date/time, a boolean, and a float) - MapperDataProperty eventDateTimeProperty = new MapperDataProperty("eventDateTime", "a date/time of the resource", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new ArrayList(){{add("dateTime");}}, false, true); - MapperDataProperty isBoolProperty = new MapperDataProperty("isBool", "a boolean indicator of the resource", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new ArrayList(){{add("boolean");}}, false, true); - MapperDataProperty quantityProperty = new MapperDataProperty("quantity", "a number quantity of the resource", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new ArrayList(){{add("float");}}, false, true); + MapperDataProperty eventDateTimeProperty = new MapperDataProperty("eventDateTime", "a date/time of the resource", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new HashSet(){{add("dateTime");}}, false, true); + MapperDataProperty isBoolProperty = new MapperDataProperty("isBool", "a boolean indicator of the resource", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new HashSet(){{add("boolean");}}, false, true); + MapperDataProperty quantityProperty = new MapperDataProperty("quantity", "a number quantity of the resource", false, defaultRestrictionValues, valuesFromDataRestrictions_ranges, new HashSet(){{add("float");}}, false, true); return Map.ofEntries( Map.entry(idProperty.name, idProperty.getSchemaByDataProperty()), @@ -279,17 +276,12 @@ private Map getDefaultProperties() { ); } - /** + /** * Read the Ontology, obtain the ObjectProperties, obtain the range for each property and generate the SchemaProperty * @return A HashMap key: propertyName, value: SchemaProperty */ private Map getObjectProperties() { - OWLOntologyManager m = OWLManager.createOWLOntologyManager(); - OWLDataFactory dataFactory = m.getOWLDataFactory(); - OWLClass owlThing = dataFactory.getOWLThing(); - Set properties_class = new HashSet<>(); - Set functional; for (OWLOntology ontology: this.ontologies) { properties_class.addAll(ontology.getAxioms(AxiomType.OBJECT_PROPERTY_DOMAIN)); } @@ -329,25 +321,25 @@ private Map getObjectProperties() { String propertyURI = odp.getIRI().toString(); propertyNameURI.put(propertyURI, propertyName); - List propertyRanges = getCodeGenTypesByRangeObject(ranges, odp, owlThing); + Set propertyRanges = this.getCodeGenTypesByRangeObject(ranges, odp); Map restrictionValues = new HashMap() ; - for (OWLOntology ontology: this.ontologies) { - RestrictionVisitor restrictionVisitor = new RestrictionVisitor(this.cls, ontology, owlThing, propertyName); - for (OWLObjectPropertyRangeAxiom propertyRangeAxiom : ranges) { - OWLClassExpression ce = propertyRangeAxiom.getRange(); - ce.accept(restrictionVisitor); - } - Map> restrictionsValuesFromClass = restrictionVisitor.getRestrictionsValuesFromClass(); - for (String j : restrictionsValuesFromClass.keySet()) { - if (j.equals(propertyName)) { - restrictionValues=restrictionsValuesFromClass.get(j); - } - } - if (restrictionsValuesFromClass.isEmpty() && propertyRanges.size() > 1) { - propertyRanges.clear(); + RestrictionVisitor restrictionVisitor = new RestrictionVisitor(this.cls, this.ontologies, propertyName); + for (OWLObjectPropertyRangeAxiom propertyRangeAxiom : ranges) { + OWLClassExpression ce = propertyRangeAxiom.getRange(); + ce.accept(restrictionVisitor); + } + + Map> restrictionsValuesFromClass = restrictionVisitor.getRestrictionsValuesFromClass(); + for (String j : restrictionsValuesFromClass.keySet()) { + if (j.equals(propertyName)) { + restrictionValues=restrictionsValuesFromClass.get(j); } - } + } + + if (restrictionsValuesFromClass.isEmpty() && propertyRanges.size() > 1) { + propertyRanges.clear(); + } String propertyDescription = ObaUtils.getDescription(odp, this.ontology_cls, this.configFlags.get(CONFIG_FLAG.DEFAULT_DESCRIPTIONS)); @@ -365,46 +357,27 @@ private Map getObjectProperties() { return properties; } - /** - * Obtain SchemaPropertyType from the OWLRange of a OWLDataProperty - * @param ranges Represents a DataPropertyRange - * @param odp Represents a OWLDataProperty - * @return A list with the properties - */ - private List getCodeGenTypesByRangeData(Set ranges, OWLDataProperty odp) { - List dataProperties = new ArrayList<>(); - for (OWLDataPropertyRangeAxiom propertyRangeAxiom : ranges) { - for (OWLEntity rangeStr : propertyRangeAxiom.getSignature()) { - if (!rangeStr.containsEntityInSignature(odp)) { - String propertyName = this.sfp.getShortForm(rangeStr.getIRI()); - dataProperties.add(propertyName); - } - } - } - - return dataProperties; - } - - /** - * Obtain SchemaPropertyType from the OWLRange of a OWLObjectProperty + /** + * Obtain SchemaPropertyType from the OWLRange of a OWLObjectProperty. + * * @param ranges Represents a ObjectPropertyRange * @param odp Represents a OWLObjectProperty - * @param owlThing - * @return A list with the properties + * @return A Set with the properties */ - private List getCodeGenTypesByRangeObject(Set ranges, OWLObjectProperty odp, OWLClass owlThing) { - List objectProperty = new ArrayList<>(); + private Set getCodeGenTypesByRangeObject(Set ranges, OWLObjectProperty odp) { + Set objectProperty = new HashSet<>(); for (OWLObjectPropertyRangeAxiom propertyRangeAxiom : ranges) { for (OWLEntity rangeClass : propertyRangeAxiom.getSignature()) { if (rangeClass instanceof OWLClassExpression) { if (!rangeClass.containsEntityInSignature(odp)) { - if (rangeClass.asOWLClass().equals(owlThing)) { + if (rangeClass.asOWLClass().equals(this.owlThing)) { logger.info("Ignoring owl:Thing" + odp); } else { this.properties_range.add(rangeClass.asOWLClass()); - if (this.configFlags.get(CONFIG_FLAG.FOLLOW_REFERENCES)) - objectProperty.add(getSchemaName(rangeClass.asOWLClass())); + if (this.configFlags.get(CONFIG_FLAG.FOLLOW_REFERENCES)) { + objectProperty.add(getSchemaName(rangeClass.asOWLClass())); + } } } } @@ -414,203 +387,191 @@ private List getCodeGenTypesByRangeObject(Set with the properties + */ + private Set getCodeGenTypesByRangeData(Set ranges, OWLDataProperty odp) { + Set dataProperties = new HashSet<>(); + for (OWLDataPropertyRangeAxiom propertyRangeAxiom: ranges) { + for (OWLEntity rangeStr: propertyRangeAxiom.getSignature()) { + if (!rangeStr.containsEntityInSignature(odp)) { + String propertyName = this.sfp.getShortForm(rangeStr.getIRI()); + dataProperties.add(propertyName); + } + } + } + + return dataProperties; + } + /** * Read the Ontology and gets all the Class restrictions on object or data properties and * generate SchemaProperties. + * * @param analyzedClass Class that will be analyzed in order to get its restrictions */ private void getClassRestrictions(OWLClass analyzedClass) { - OWLOntologyManager m = OWLManager.createOWLOntologyManager(); - OWLDataFactory dataFactory = m.getOWLDataFactory(); - OWLClass owlThing = dataFactory.getOWLThing(); + // Determine properties before setting restrictions for those properties. + this.properties = this.setProperties(); for (OWLOntology ontology: this.ontologies) { - final RestrictionVisitor restrictionVisitor = new RestrictionVisitor(analyzedClass, ontology, owlThing, ""); - for (OWLSubClassOfAxiom ax: ontology.getSubClassAxiomsForSubClass(analyzedClass)) { - OWLClassExpression superCls = ax.getSuperClass(); - // Ask our superclass to accept a visit from the RestrictionVisitor - // - e.g. if it is an existential restriction then the restriction visitor - // will answer it - if not the visitor will ignore it - superCls.accept(restrictionVisitor); - } + final RestrictionVisitor restrictionVisitor = new RestrictionVisitor(analyzedClass, this.ontologies, ""); + + ontology.subClassAxiomsForSubClass(analyzedClass).forEach((ax) -> { + // Ask our superclass to accept a visit from the RestrictionVisitor + ax.getSuperClass().accept(restrictionVisitor); + }); // For equivalent (to) classes (e.g. Defined classes) we need to accept the visit to navigate it. ontology.equivalentClassesAxioms(analyzedClass).forEach((eqClsAx) -> { eqClsAx.accept(restrictionVisitor); }); - this.enums = restrictionVisitor.getAllEnums(); - this.propertiesFromObjectRestrictions = restrictionVisitor.getPropertiesFromObjectRestrictions(); - this.propertiesFromObjectRestrictions_ranges = restrictionVisitor.getPropertiesFromObjectRestrictions_ranges(); - this.propertiesFromDataRestrictions = restrictionVisitor.getPropertiesFromDataRestrictions(); - this.propertiesFromDataRestrictions_ranges = restrictionVisitor.getPropertiesFromDataRestrictions_ranges(); Map> restrictionsValuesFromClass = restrictionVisitor.getRestrictionsValuesFromClass(); + // Only set up the restriction mapping if there are restrictions for the class. if (!restrictionsValuesFromClass.isEmpty()) { - // When the restriction is a ObjectComplementOf it doesn't have a object property, - // thus we need to set its value at the setSchema function + this.propertiesFromObjectRestrictions = restrictionVisitor.getPropertiesFromObjectRestrictions(); + this.propertiesFromObjectRestrictions_ranges = restrictionVisitor.getPropertiesFromObjectRestrictions_ranges(); + this.propertiesFromDataRestrictions = restrictionVisitor.getPropertiesFromDataRestrictions(); + this.propertiesFromDataRestrictions_ranges = restrictionVisitor.getPropertiesFromDataRestrictions_ranges(); + var valuesFromDataRestrictions_ranges = restrictionVisitor.getValuesFromDataRestrictions_ranges(); + + // When the restriction is a ObjectComplementOf it doesn't have a object property, thus we need to set its value at the setSchema function if (restrictionsValuesFromClass.containsKey("complementOf") && restrictionsValuesFromClass.size() == 1) { - for (String j: restrictionsValuesFromClass.keySet()) { - Map restrictionValues = restrictionsValuesFromClass.get(j); - for (String restriction: restrictionValues.keySet()) { - this.complementOf = restrictionValues.get(restriction); - } - } + restrictionsValuesFromClass.forEach((property, restrictions) -> { + restrictions.forEach((restrictionKey, restrictionValue) -> { + this.complementOf = restrictionValue; + }); + }); } else { - for (OWLObjectProperty op: this.propertiesFromObjectRestrictions) { - boolean isFunctional = EntitySearcher.isFunctional(op, this.ontologies.stream()); - - MapperObjectProperty mapperObjectProperty; - String propertyDescription = ObaUtils.getDescription(op, this.ontology_cls, this.configFlags.get(CONFIG_FLAG.DEFAULT_DESCRIPTIONS)); - if (!this.propertiesFromObjectRestrictions_ranges.isEmpty()) { - List rangesOP = this.propertiesFromObjectRestrictions_ranges.get(this.sfp.getShortForm(op.getIRI())); - for (String j : restrictionsValuesFromClass.keySet()) { - Map restrictionValues = restrictionsValuesFromClass.get(j); - if (j.equals(this.sfp.getShortForm(op.getIRI()))) { - int exactCardinality = -1; - int minCardinality = -1; - int maxCardinality = -1; - - if (rangesOP != null && rangesOP.get(0).equals("defaultValue")) { - mapperObjectProperty = new MapperObjectProperty(this.sfp.getShortForm(op.getIRI()), propertyDescription, isFunctional, restrictionValues, rangesOP, false, true); - } else { - String exactCardinalityStr = restrictionValues.get("exactCardinality"); - exactCardinalityStr = ((exactCardinalityStr == null || exactCardinalityStr.isBlank()) ? "-1" : exactCardinalityStr); - exactCardinality = Integer.parseInt(exactCardinalityStr); - - String minCardinalityStr = restrictionValues.get("minCardinality"); - minCardinalityStr = ((minCardinalityStr == null || minCardinalityStr.isBlank()) ? "-1" : minCardinalityStr); - minCardinality = Integer.parseInt(minCardinalityStr); - - String maxCardinalityStr = restrictionValues.get("maxCardinality"); - maxCardinalityStr = ((maxCardinalityStr == null || maxCardinalityStr.isBlank()) ? "-1" : maxCardinalityStr); - maxCardinality = Integer.parseInt(maxCardinalityStr); - - // If cardinality is present and allows for multiple values and it is not functional, - // then this is an array. - boolean isArray = !isFunctional - && (exactCardinality > 1 - || minCardinality > 1 - || maxCardinality > 1); - - // If config flag to generate arrays is set, use it to override current setting. - isArray |= (this.configFlags.containsKey(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS) && this.configFlags.get(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS)); + // Loop through each property and its associated restrictions + restrictionsValuesFromClass.forEach((propertyName, restrictionValues) -> { + if (restrictionValues != null && !restrictionValues.isEmpty()) { + // TODO: THIS CAN BE DONE BETTER. BUT WILL PROBABLY REQUIRE RE-WORKING OTHER STUFF. THIS IS A WORKAROUND FOR NOW. + boolean isFunctional = false; + String propertyDescription = null; + for (OWLObjectProperty op: this.propertiesFromObjectRestrictions) { + if (this.sfp.getShortForm(op.getIRI()).equals(propertyName)) { + propertyDescription = ObaUtils.getDescription(op, ontology, this.configFlags.get(CONFIG_FLAG.DEFAULT_DESCRIPTIONS)); + isFunctional = EntitySearcher.isFunctional(op, this.ontologies.stream()); + } + } - // If cardinality is exactly 1 OR a minimum of 1, then not nullable. - boolean isNullable = (exactCardinality == -1 && minCardinality == -1) ? true : exactCardinality != 1 && minCardinality < 1; + String exactCardinalityStr = restrictionValues.get("exactCardinality"); + exactCardinalityStr = ((exactCardinalityStr == null || exactCardinalityStr.isBlank()) ? "-1" : exactCardinalityStr); + int exactCardinality = Integer.parseInt(exactCardinalityStr); + + String minCardinalityStr = restrictionValues.get("minCardinality"); + minCardinalityStr = ((minCardinalityStr == null || minCardinalityStr.isBlank()) ? "-1" : minCardinalityStr); + int minCardinality = Integer.parseInt(minCardinalityStr); + + String maxCardinalityStr = restrictionValues.get("maxCardinality"); + maxCardinalityStr = ((maxCardinalityStr == null || maxCardinalityStr.isBlank()) ? "-1" : maxCardinalityStr); + int maxCardinality = Integer.parseInt(maxCardinalityStr); + + // If cardinality is present and allows for multiple values and it is not functional, then this is an array. + boolean isArray = !isFunctional + && (exactCardinality > 1 + || minCardinality > 1 + || maxCardinality > 1); + + // If config flag to generate arrays is set, use it to override current setting. + isArray |= (this.configFlags.containsKey(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS) && this.configFlags.get(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS)); + + // If cardinality is exactly 1 OR a minimum of 1, then not nullable. + boolean isNullable = (exactCardinality == -1 && minCardinality == -1) ? true : exactCardinality != 1 && minCardinality < 1; + + //----------Handle object property restrictions. + Set rangesOP = this.propertiesFromObjectRestrictions_ranges.get(propertyName); + + // If property name is blank but we have ranges, this is an enum. + if (propertyName.isBlank() && rangesOP != null && !rangesOP.isEmpty()) { + this.properties.put(propertyName, this.getEnumSchema(rangesOP)); + } else { + MapperObjectProperty mapperObjectProperty; + + if (rangesOP != null && rangesOP.iterator().next().equals("defaultValue")) { + mapperObjectProperty = new MapperObjectProperty(propertyName, propertyDescription, isFunctional, restrictionValues, rangesOP, false, true); + } else { + mapperObjectProperty = new MapperObjectProperty(propertyName, propertyDescription, isFunctional, restrictionValues, rangesOP, isArray, isNullable); + } + + try { + Schema opSchema = mapperObjectProperty.getSchemaByObjectProperty(); - mapperObjectProperty = new MapperObjectProperty(this.sfp.getShortForm(op.getIRI()), propertyDescription, isFunctional, restrictionValues, rangesOP, isArray, isNullable); - } - - try { - Schema opSchema = mapperObjectProperty.getSchemaByObjectProperty(); - - boolean is_required = false; - - // If cardinality is exactly 1, then we can remove the min/max property constraints - // and set the property to be required for the class. - if (exactCardinality == 1 || (minCardinality == 1 && maxCardinality == 1)) { - if (this.configFlags.containsKey(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS) && !this.configFlags.get(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS)) { - opSchema.setMinItems(null); - opSchema.setMaxItems(null); - } - - is_required = true; - } + boolean is_required = false; - // If cardinality minimum is 1, keep the min/max property constraints - // and set the property to be required for the class. - if (minCardinality > 0) { - is_required = true; + // If cardinality is exactly 1, then we can remove the min/max property constraints and set the property to be required for the class. + if (exactCardinality == 1 || (minCardinality == 1 && maxCardinality == 1)) { + if (this.configFlags.containsKey(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS) && !this.configFlags.get(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS)) { + opSchema.setMinItems(null); + opSchema.setMaxItems(null); } + + is_required = true; + } - if (is_required) { - this.required_properties.add(mapperObjectProperty.name); - } + // If cardinality minimum is 1, keep the min/max property constraints and set the property to be required for the class. + if (minCardinality > 0) { + is_required = true; + } - this.properties.put(mapperObjectProperty.name, opSchema); - } catch (Exception e) { - logger.warning("Error when parsing object property "+mapperObjectProperty.name); + if (is_required) { + this.required_properties.add(propertyName); } + + this.properties.put(propertyName, opSchema); + } catch (Exception e) { + logger.warning("Error when parsing object property " + propertyName); + logger.warning(" ------> " + e); } } - } - } - - for (OWLDataProperty dp: this.propertiesFromDataRestrictions) { - boolean isFunctional = EntitySearcher.isFunctional(dp, this.ontologies.stream()); - - List valuesFromDataRestrictions_ranges = new ArrayList<>(); - String propertyDescription = ObaUtils.getDescription(dp, this.ontology_cls, this.configFlags.get(CONFIG_FLAG.DEFAULT_DESCRIPTIONS)); - if (!this.propertiesFromDataRestrictions_ranges.isEmpty()) { - List rangesDP = this.propertiesFromDataRestrictions_ranges.get(this.sfp.getShortForm(dp.getIRI())); - for (String j: restrictionsValuesFromClass.keySet()) { - Map restrictionValues = restrictionsValuesFromClass.get(j); - if (j.equals(this.sfp.getShortForm(dp.getIRI()))) { - String exactCardinalityStr = restrictionValues.get("exactCardinality"); - exactCardinalityStr = ((exactCardinalityStr == null || exactCardinalityStr.isBlank()) ? "-1" : exactCardinalityStr); - int exactCardinality = Integer.parseInt(exactCardinalityStr); - - String minCardinalityStr = restrictionValues.get("minCardinality"); - minCardinalityStr = ((minCardinalityStr == null || minCardinalityStr.isBlank()) ? "-1" : minCardinalityStr); - int minCardinality = Integer.parseInt(minCardinalityStr); - - String maxCardinalityStr = restrictionValues.get("maxCardinality"); - maxCardinalityStr = ((maxCardinalityStr == null || maxCardinalityStr.isBlank()) ? "-1" : maxCardinalityStr); - int maxCardinality = Integer.parseInt(maxCardinalityStr); - - // If cardinality is present and allows for multiple values and it is not functional, - // then this is an array. - boolean isArray = !isFunctional - && (exactCardinality > 1 - || minCardinality > 1 - || maxCardinality > 1); - - // If config flag to generate arrays is set, use it to override current setting. - isArray |= (this.configFlags.containsKey(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS) && this.configFlags.get(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS)); - - // If cardinality is exactly 1 OR a minimum of 1, then not nullable. - boolean isNullable = (exactCardinality == -1 && minCardinality == -1) ? true : exactCardinality != 1 && minCardinality < 1; - - MapperDataProperty mapperDataProperty = new MapperDataProperty(this.sfp.getShortForm(dp.getIRI()), propertyDescription, isFunctional, restrictionValues, valuesFromDataRestrictions_ranges, rangesDP, isArray, isNullable); - try { - Schema dpSchema = mapperDataProperty.getSchemaByDataProperty(); - - boolean is_required = false; - - // If cardinality is exactly 1, then we can remove the min/max property constraints - // and set the property to be required for the class. - if (exactCardinality == 1 || (minCardinality == 1 && maxCardinality == 1)) { - if (this.configFlags.containsKey(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS) && !this.configFlags.get(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS)) { - dpSchema.setMinItems(null); - dpSchema.setMaxItems(null); - } - - is_required = true; - } + - // If cardinality minimum is 1, keep the min/max property constraints - // and set the property to be required for the class. - if (minCardinality > 0) { - is_required = true; - } + //----------Handle data property restrictions. + Set rangesDP = this.propertiesFromDataRestrictions_ranges.get(propertyName); + + if (rangesDP != null && !rangesDP.isEmpty()) { + MapperDataProperty mapperDataProperty = new MapperDataProperty(propertyName, propertyDescription, isFunctional, restrictionValues, valuesFromDataRestrictions_ranges, rangesDP, isArray, isNullable); + try { + Schema dpSchema = mapperDataProperty.getSchemaByDataProperty(); + + boolean is_required = false; - if (is_required) { - this.required_properties.add(mapperDataProperty.name); + // If cardinality is exactly 1, then we can remove the min/max property constraints and set the property to be required for the class. + if (exactCardinality == 1 || (minCardinality == 1 && maxCardinality == 1)) { + if (this.configFlags.containsKey(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS) && !this.configFlags.get(CONFIG_FLAG.ALWAYS_GENERATE_ARRAYS)) { + dpSchema.setMinItems(null); + dpSchema.setMaxItems(null); } - this.properties.put(mapperDataProperty.name, dpSchema); - } catch (Exception e) { - logger.warning("Error when processing data property " + mapperDataProperty.name); + is_required = true; } + + // If cardinality minimum is 1, keep the min/max property constraints and set the property to be required for the class. + if (minCardinality > 0) { + is_required = true; + } + + if (is_required) { + this.required_properties.add(mapperDataProperty.name); + } + + this.properties.put(mapperDataProperty.name, dpSchema); + } catch (Exception e) { + logger.warning("Error when processing data property " + mapperDataProperty.name); + logger.warning(" ------> " + e); } } } - } + }); } } - - this.properties = setProperties(); } if (this.configFlags.get(CONFIG_FLAG.DEFAULT_PROPERTIES)) { @@ -629,4 +590,20 @@ private String getSchemaName(OWLClass cls) { public OWLClass getCls() { return this.cls; } + + private Schema getEnumSchema(Set refs) { + Schema object = new ObjectSchema(); + ComposedSchema composedSchema = new ComposedSchema(); + + object.setType("string"); + object.setDescription(this.cls_description); + + for (String item: refs) { + composedSchema.addEnumItemObject(item); + } + + object.setEnum(composedSchema.getEnum()); + + return object; + } } From c926bde583eb29d5717148464d00c70ddf74932f Mon Sep 17 00:00:00 2001 From: Christopher Weedall <5010253+cweedall@users.noreply.github.com> Date: Fri, 17 May 2024 23:52:01 -0500 Subject: [PATCH 10/10] bump to new minor version instead of patch version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ac30d59..7783e07 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ jar edu.isi.oba oba - 3.9.1 + 3.10.0 core https://github.com/KnowledgeCaptureAndDiscovery/OBA