Esempio n. 1
0
  /*
   * (non-Javadoc)
   * @see net.java.treaty.ContractVocabulary#getSubProperties(java.net.URI)
   */
  public Set<URI> getSubProperties(URI relationshipOrProperty) throws TreatyException {

    Set<URI> result;
    result = new HashSet<URI>();

    OntModel model;
    model = getOntology();

    OntProperty property;
    property = model.getOntProperty(relationshipOrProperty.toString());

    for (Iterator<? extends OntProperty> iterator = property.listSubProperties(false);
        iterator.hasNext(); ) {

      try {
        URI next;
        next = new URI(iterator.next().getURI());

        /* It seems that jena returns the URI itself. */
        if (!relationshipOrProperty.equals(next)) {
          result.add(next);
        }
        // no else.
      } catch (URISyntaxException e) {
        throw new TreatyException(e);
      }
      // end catch.
    }
    // end for.

    return result;
  }
Esempio n. 2
0
  private Model createModelFromDatabase() throws DataBaseNotAccessibleException {
    HashMap<String, Vector<String>> res = this.getMetaInfoFromDataBase();
    OntModel m = ModelFactory.createOntologyModel();

    String ns = "http://www.lirmm.fr/metaInfo#";
    m.setNsPrefix("metaInfos", ns);

    OntClass maDataBase = m.createClass(ns + "DATABASE");
    OntClass nameDataBase = m.createClass(ns + database.getDatabaseName());
    nameDataBase.addSuperClass(maDataBase);

    OntClass maSuperClasse = m.createClass(ns + "TABLE");

    for (String cle : res.keySet()) {
      OntClass c = m.createClass(ns + cle);
      c.addSuperClass(maSuperClasse);
      for (int i = 0; i < res.get(cle).size(); i++) {
        OntClass c2 = m.createClass(ns + res.get(cle).get(i));
        OntProperty prop =
            m.createOntProperty(ns + "COLONNE_" + c.getLocalName() + "_" + c2.getLocalName());
        prop.setRange(c2);
        prop.setDomain(c);
        c2.addSuperClass(maSuperClasse);
      }
    }
    return m;
  }
Esempio n. 3
0
  /*
   * (non-Javadoc)
   * @see net.java.treaty.ContractVocabulary#getSuperProperties(java.net.URI)
   */
  public Set<URI> getSuperProperties(URI relationshipOrProperty) throws TreatyException {

    Set<URI> result;
    result = new HashSet<URI>();

    OntModel model;
    model = getOntology();

    OntProperty property;
    property = model.getOntProperty(relationshipOrProperty.toString());

    for (Iterator<? extends OntProperty> iterator = property.listSuperProperties(false);
        iterator.hasNext(); ) {

      try {
        result.add(new URI(iterator.next().getURI()));
      } catch (URISyntaxException e) {
        throw new TreatyException(e);
      }
      // end catch.
    }
    // end for.

    return result;
  }
Esempio n. 4
0
 private void addFields() {
   List<OntProperty> list = listProperties();
   for (OntProperty p : list) {
     if (isStandard(p.getURI())) continue;
     addFields(p, p);
   }
 }
 private float execute(OntProperty c1, OntProperty c2) {
   float similarity = strategyEditDistance.compute(c1.getLocalName(), c2.getLocalName());
   SimilarityVO similarityVO = new SimilarityVO();
   similarityVO.setElementA(c1);
   similarityVO.setElementB(c2);
   similarityVO.setSimilarity(similarity);
   similaridade.add(similarityVO);
   return similarity;
 }
 public int insertProp(PropertyInstanceIface prop, OntModelSelector oms) {
   OntModel ontModel = oms.getABoxModel();
   OntModel tboxModel = oms.getTBoxModel();
   ontModel.enterCriticalSection(Lock.WRITE);
   try {
     tboxModel.enterCriticalSection(Lock.READ);
     try {
       Resource subjRes = ontModel.getResource(prop.getSubjectEntURI());
       OntProperty pred = tboxModel.getOntProperty(prop.getPropertyURI());
       Resource objRes = ontModel.getResource(prop.getObjectEntURI());
       if ((subjRes != null) && (pred != null) && (objRes != null)) {
         getOntModel()
             .getBaseModel()
             .notifyEvent(
                 new IndividualUpdateEvent(
                     getWebappDaoFactory().getUserURI(), true, prop.getSubjectEntURI()));
         try {
           ontModel.add(subjRes, pred, objRes);
           updatePropertyDateTimeValue(
               subjRes, MODTIME, Calendar.getInstance().getTime(), getOntModel());
         } finally {
           getOntModel()
               .getBaseModel()
               .notifyEvent(
                   new IndividualUpdateEvent(
                       getWebappDaoFactory().getUserURI(), false, prop.getSubjectEntURI()));
         }
         OntProperty invPred = pred.getInverse();
         if (invPred != null) {
           getOntModel()
               .getBaseModel()
               .notifyEvent(
                   new IndividualUpdateEvent(
                       getWebappDaoFactory().getUserURI(), true, prop.getObjectEntURI()));
           try {
             ontModel.add(objRes, invPred, subjRes);
             updatePropertyDateTimeValue(
                 objRes, MODTIME, Calendar.getInstance().getTime(), getOntModel());
           } finally {
             getOntModel()
                 .getBaseModel()
                 .notifyEvent(
                     new IndividualUpdateEvent(
                         getWebappDaoFactory().getUserURI(), false, prop.getSubjectEntURI()));
           }
         }
       }
       return 0;
     } finally {
       tboxModel.leaveCriticalSection();
     }
   } finally {
     ontModel.leaveCriticalSection();
   }
 }
Esempio n. 7
0
 private void addSuperProperties(UmlClass umlClass, OntProperty property) {
   List<? extends OntProperty> list = property.listSuperProperties(true).toList();
   for (OntProperty superProperty : list) {
     if (superProperty.getURI().equals(property.getURI())) {
       continue;
     }
     UmlClass superClass = addPropertyClass(superProperty, true);
     umlClass.addSupertype(superClass);
     superClass.addSubtype(umlClass);
   }
 }
Esempio n. 8
0
 /**
  * Checks whether adding p to this node would violate cardinality constraints
  *
  * @param p OntProperty
  * @return true if adding the property would violate a cardinality constraint
  */
 public boolean violatesCardinality(OntProperty p) {
   if (p.isInverseFunctionalProperty()) {
     if (node.getIncomingEdges(p.getLocalName()).size() > 0) return true;
   }
   OntProperty inverse = reader.getInverse(p);
   if (inverse == null)
     return false; // if the inverse property does not exist there are no cardinal constraints on
   // it...
   if (optional.contains(inverse) || compulsory.contains(inverse)) return false;
   if (addShowOrHideOption() == SGNode.INCOMPLETE) return false;
   return true;
 }
Esempio n. 9
0
  private void handleSubpropertyOf(OntProperty p, OntProperty ancestor) {

    List<RDFNode> list = ancestor.listPropertyValues(RDFS.subPropertyOf).toList();
    for (RDFNode node : list) {
      if (!node.canAs(OntProperty.class)) continue;

      OntProperty superProperty = node.as(OntProperty.class);
      if (superProperty.equals(ancestor)) continue;
      addFields(p, superProperty);
      handleSubpropertyOf(p, superProperty);
    }
  }
Esempio n. 10
0
  private void addSubProperties(UmlClass umlClass, OntProperty type) {

    List<? extends OntProperty> list = type.listSubProperties(true).toList();
    for (OntProperty p : list) {
      if (p.getURI().equals(type.getURI())) {
        continue;
      }
      UmlClass subProperty = addPropertyClass(p, false);
      umlClass.addSubtype(subProperty);
      subProperty.addSupertype(umlClass);
    }
  }
  private float execute(OntClass c1, OntClass c2) {
    int max = 0, min = 0;
    Collection<OntProperty> listaProps2 = OntologyCache.getOrAddListProperties(c2);

    for (Iterator i = OntologyCache.getOrAddListProperties(c1).iterator(); i.hasNext(); ) {
      OntProperty p1 = (OntProperty) i.next();
      if (p1.isDatatypeProperty()) {
        max += 1;
        for (OntProperty p2 : listaProps2) {
          if (p2.isDatatypeProperty()) {
            SimilarityVO similarityVO = new SimilarityVO();
            similarityVO.setElementA(p1);
            similarityVO.setElementB(p2);
            similarityVO.setSimilarity(
                strategyEditDistance.compute(p1.getLocalName(), p2.getLocalName()));
            similaridade.add(similarityVO);
          }
        }
      }
    }
    // Loop para pegar o numero de datatypeproperty de c2
    for (OntProperty p2 : listaProps2) if (p2.isDatatypeProperty()) min += 1;

    similaridade = strategyCalculation.explore(similaridade);
    return averageWithPenalty(sumSimilarities(), max, min);
  }
 // replaces the label of the property
 public void replacePropertyLabel(
     String uri,
     String newLabel,
     boolean activeRandomString,
     boolean activeTranslateString,
     boolean activeSynonym,
     int activeStringOperation) {
   OntProperty prop = modifiedModel.getOntProperty(uri);
   if (prop.getLabel("en") != null) {
     if (activeTranslateString) {
       prop.setLabel(newLabel, "fr");
     } else {
       prop.setLabel(newLabel, "en");
     }
   }
 }
Esempio n. 13
0
 public Collection<OntView> getCandidates() {
   OntResource r = verb.getRange();
   r = m().getOntClass(r.getURI());
   return new each(r.asClass().listInstances()) {
     void $() {
       if (!m().contains(subject, verb, item)) add(OntView.$(item));
     }
   }.result;
 }
Esempio n. 14
0
 private boolean isAbstract(OntProperty p) {
   List<RDFNode> list = p.listPropertyValues(RDF.type).toList();
   for (RDFNode node : list) {
     if (node.canAs(Resource.class)) {
       Resource r = node.asResource();
       if (BindVocabulary.AbstractProperty.getURI().equals(r.getURI())) return true;
     }
   }
   return false;
 }
Esempio n. 15
0
 public static synchronized boolean isSingleValued(
     OntClass cls, OntProperty prop, String rngString) {
   if (prop.isFunctionalProperty()) {
     return true;
   }
   if (cls != null) {
     ExtendedIterator<OntClass> eitr = cls.listSuperClasses(false);
     while (eitr.hasNext()) {
       OntClass supercls = eitr.next();
       if (supercls.isRestriction()) {
         Restriction rstrct = supercls.asRestriction();
         if (rstrct.isMaxCardinalityRestriction()) {
           MaxCardinalityRestriction mxcr = rstrct.asMaxCardinalityRestriction();
           if (mxcr.getOnProperty().equals(prop) && mxcr.getMaxCardinality() == 1) {
             return true;
           }
         } else if (rstrct.isCardinalityRestriction()) {
           if (rstrct.isCardinalityRestriction()) {
             CardinalityRestriction cr = rstrct.asCardinalityRestriction();
             if (cr.getOnProperty().equals(prop) && cr.getCardinality() == 1) {
               return true;
             }
           }
         } else {
           if (rstrct.hasProperty(OWL2.maxQualifiedCardinality)) {
             if (rstrct.getOnProperty().equals(prop)
                 && rstrct.getProperty(OWL2.maxQualifiedCardinality).getInt() == 1) {
               // check class
               if (rstrct.getProperty(OWL2.onClass).getResource().toString().equals(rngString)) {
                 return true;
               }
             }
           } else if (rstrct.hasProperty(OWL2.qualifiedCardinality)) {
             if (rstrct.getOnProperty().equals(prop)
                 && rstrct.getProperty(OWL2.qualifiedCardinality).getInt() == 1) {
               // check class
               if (rstrct.getProperty(OWL2.onClass).getResource().toString().equals(rngString)) {
                 return true;
               }
             }
           }
           //						StmtIterator siter = rstrct.listProperties();
           //						while (siter.hasNext()) {
           //							System.out.println(siter.nextStatement().toString());
           //						}
         }
       }
     }
   }
   return false;
 }
Esempio n. 16
0
  private void handlePropertySubclassOf(OntProperty p) {

    List<RDFNode> list = p.listPropertyValues(RDFS.subClassOf).toList();
    for (RDFNode node : list) {
      if (!node.canAs(Resource.class)) continue;
      Resource resource = node.asResource();
      Resource onPropertyValue = resource.getPropertyResourceValue(OWL.onProperty);
      if (!RDFS.domain.equals(onPropertyValue)) continue;
      Resource someValuesFrom = resource.getPropertyResourceValue(OWL.someValuesFrom);
      if (someValuesFrom == null) continue;
      String uri = someValuesFrom.getURI();
      if (uri != null) {
        OntResource type = someValuesFrom.as(OntResource.class);
        addField(type, p, null);
      } else {
        Resource unionList = someValuesFrom.getPropertyResourceValue(OWL.unionOf);
        while (unionList != null) {
          Resource first = unionList.getPropertyResourceValue(RDF.first);
          if (first != null) {
            String typeURI = first.getURI();
            if (typeURI == null) {
              logger.warn(
                  "Cannot handle union that contains an anonymous class in the domain of "
                      + p.getURI());
            } else {
              OntResource type = first.as(OntResource.class);
              addField(type, p, null);
            }
          }
          unionList = unionList.getPropertyResourceValue(RDF.rest);
          if (RDF.nil.equals(unionList)) {
            break;
          }
        }
      }
    }
  }
Esempio n. 17
0
 /**
  * Call this method to convert a value (v) as a Java object to a typed Literal matching the range
  * of the property.
  *
  * @param m
  * @param prop
  * @param v
  * @return
  * @throws Exception
  */
 public static synchronized Literal getLiteralMatchingDataPropertyRange(
     OntModel m, OntProperty prop, Object v) throws Exception {
   Literal val = null;
   String errMsg = null;
   if (prop.isAnnotationProperty()) {
     return m.createTypedLiteral(v);
   }
   // SADL only has DoubleLiterals--if this property has range float convert v to Float.
   OntResource rng = prop.getRange();
   String rnguri = rng != null ? rng.getURI() : null;
   if (rng == null) {
     errMsg = "Range not given.";
   } else if (rng.isAnon()) {
     // this is a complex range--needs work. Try to do something with it....
     // If value is a String
     if (v instanceof String) {
       v = stripQuotes((String) v);
       val = m.createTypedLiteral(v);
     } else {
       val = m.createTypedLiteral(v);
       if (val == null) {
         errMsg =
             "Range is an unsupported complex type, failed to create a Literal value for '"
                 + v.toString()
                 + "'.";
       }
     }
   } else {
     val = getLiteralMatchingDataPropertyRange(m, rnguri, v);
   }
   if (errMsg != null) {
     errMsg += " (Property is '" + prop.getLocalName() + "'.)";
     throw new Exception(errMsg);
   }
   return val;
 }
Esempio n. 18
0
  /**
   * Initialises the anchor, finding the node's compulsory and optional properties and their NL
   * representations and ordering it all in lists and maps, using the submenus.
   *
   * @param c OntClass corresponding to this anchor
   * @param query true if this is an anchor for a node in the QueryGraph
   * @throws BadAnchorException if the given SGNode does not need an anchor
   */
  public void init(OntClass c, boolean query) throws BadAnchorException {
    Map<String, Integer[]> map = reader.getCardinalities(c.getLocalName());
    List<OntProperty> list = reader.getDomainProperties(c.getLocalName());
    for (int i = 0; i < list.size(); i++) {
      OntProperty p = list.get(i);
      String name = p.getLocalName();
      int nr =
          node.getOutgoingEdges(name).size(); // number of times the node already has this property
      String inverse = reader.getInverse(name); // , n.getLabel(), null);
      if (inverse != null)
        nr +=
            node.getIncomingEdges(inverse)
                .size(); // plus the number of times the inverse has this node as range

      if (map.containsKey(name)) {
        int min =
            map.get(name)[0]; // if the minimum cardinality is not satisfied, add to 'compulsory'
        int max = map.get(name)[1];
        if (query) optional.add(p); // for the query, cardinality constraints do not matter
        else if ((min != 0)
            && (min > nr)) // if the minimum cardinality > 0, add the property to compulsory
        compulsory.add(p);
        else if ((max == 0)
            || (max > nr)) // if the maximum cardinality will not be violated, add to optional
        optional.add(p);
      } else optional.add(p); // no cardinality constraints, so add to optional
    }

    if (!compulsory.isEmpty()) // if there are compulsory properties, this is a red anchor
    redAnchor = true;
    else if (optional.isEmpty()) // compulsory and optional both empty - means this is not an anchor
    throw new BadAnchorException(
          "Node " + node.getLabel() + " is not an anchor anymore; all its relations are specified");

    sort(query);
  }
Esempio n. 19
0
  private void addFields(OntProperty p, OntProperty ancestor) {
    OntResource domainResource = ancestor.getDomain();
    if (domainResource == null) {
      handleNullDomain(p, ancestor);
      return;
    }

    OntClass domain = domainResource.as(OntClass.class);
    List<OntResource> domainList = listUnionMembers(p, domain);
    if (domainList.isEmpty()) {
      domainList.add(domain);
    }

    for (OntResource type : domainList) {
      addField(type, p, ancestor);
    }
  }
 /**
  * List of all subproperties of the predicate parameter
  *
  * @param prop prefix namespace : name of the propoety
  * @return list<prefix:prop_name>
  */
 public List<String> listSubProp(String prop) {
   List<String> l = new ArrayList<String>();
   ExtendedIterator<OntProperty> listAllOntProperties = ontologie.listAllOntProperties();
   while (listAllOntProperties.hasNext()) {
     OntProperty next = listAllOntProperties.next();
     if (next.getLocalName().equals(prop.split(":")[1])
         && next.getNameSpace().equals(prop.split(":")[0])) {
       ExtendedIterator<? extends OntProperty> listSubProperties = next.listSubProperties();
       while (listSubProperties.hasNext()) {
         OntProperty next2 = listSubProperties.next();
         l.add(next2.getNameSpace() + ":" + next2.getLocalName());
       }
     }
   }
   return l;
 }
  @Override
  public void runMetric() {

    // class annotation cover
    // List<Property> classAnnotationList = new ArrayList<Property>();
    classMetricMap = new HashMap<Property, CoverageTriple>();

    totalClassCount = ontology.getClassesList().size();

    for (Node classNode : ontology.getClassesList()) {
      OntClass currentClass = (OntClass) classNode.getResource().as(OntClass.class);
      StmtIterator i = currentClass.listProperties();

      Map<Property, Boolean> countedMap = new HashMap<Property, Boolean>();
      while (i.hasNext()) {
        Statement s = (Statement) i.next();
        Property p = s.getPredicate();

        if (p.canAs(AnnotationProperty.class) && countedMap.get(p) == null) {
          // this is an annotation property
          if (classMetricMap.get(p) == null) {
            // this property doesn't exit
            CoverageTriple t = new CoverageTriple();
            t.count = 1;
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
            classMetricMap.put(p, t);
          } else {
            CoverageTriple count = classMetricMap.get(p);
            count.count++;
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
          }
        }
      }
    }

    totalPropertyCount = ontology.getPropertiesList().size();
    // property annotation cover
    propertyMetricMap = new HashMap<Property, CoverageTriple>();

    for (Node propertyNode : ontology.getPropertiesList()) {
      OntProperty currentProperty = (OntProperty) propertyNode.getResource().as(OntProperty.class);
      StmtIterator i = currentProperty.listProperties();

      Map<Property, Boolean> countedMap = new HashMap<Property, Boolean>();
      while (i.hasNext()) {
        Statement s = (Statement) i.next();
        Property p = s.getPredicate();

        if (p.canAs(AnnotationProperty.class)) {
          // this is an annotation property
          if (propertyMetricMap.get(p) == null && countedMap.get(p) == null) {
            // this property doesn't exit
            CoverageTriple t = new CoverageTriple();
            t.count = 1;
            propertyMetricMap.put(p, t);
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
          } else {
            CoverageTriple count = propertyMetricMap.get(p);
            count.count++;
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
          }
        }
      }
    }

    // compute the percent coverage
    for (Entry<Property, CoverageTriple> entry : classMetricMap.entrySet()) {
      entry.getValue().coverage = (double) entry.getValue().count / (double) totalClassCount;
      if (entry.getValue().count > totalClassCount) {
        // test?
        System.out.println("--");
      }
    }

    for (Entry<Property, CoverageTriple> entry : propertyMetricMap.entrySet()) {
      entry.getValue().coverage = (double) entry.getValue().count / (double) totalPropertyCount;
      if (entry.getValue().count > totalPropertyCount) {
        // test?
        System.out.println("--");
      }
    }
  }
  @Override
  public UpdateContainer doIt(VWorkspace vWorkspace) throws CommandException {
    OntologyManager ontMgr = vWorkspace.getWorkspace().getOntologyManager();
    JSONArray classesList = new JSONArray();
    JSONArray classesMap = new JSONArray();
    JSONArray propertiesList = new JSONArray();
    JSONArray propertiesMap = new JSONArray();

    Map<String, String> prefixMap = vWorkspace.getWorkspace().getOntologyManager().getPrefixMap();

    ExtendedIterator<OntClass> iter = ontMgr.getOntModel().listNamedClasses();
    //		ExtendedIterator<DatatypeProperty> propsIter = ontMgr.getOntModel()
    //				.listDatatypeProperties();
    ExtendedIterator<OntProperty> propsIter = ontMgr.getOntModel().listAllOntProperties();
    final JSONObject outputObj = new JSONObject();

    try {
      while (iter.hasNext()) {
        OntClass cls = iter.next();

        String pr = prefixMap.get(cls.getNameSpace());
        String classLabel = cls.getLocalName();
        //				if (cls.getLabel(null) != null && !cls.getLabel(null).equals(""))
        //					classLabel = cls.getLabel(null);
        String clsStr = (pr != null && !pr.equals("")) ? pr + ":" + classLabel : classLabel;

        classesList.put(clsStr);
        JSONObject classKey = new JSONObject();
        classKey.put(clsStr, cls.getURI());
        classesMap.put(classKey);
      }

      while (propsIter.hasNext()) {
        //				DatatypeProperty prop = propsIter.next();
        OntProperty prop = propsIter.next();

        if (prop.isObjectProperty() && !prop.isDatatypeProperty()) continue;

        String pr = prefixMap.get(prop.getNameSpace());
        String propLabel = prop.getLocalName();
        //				if (prop.getLabel(null) != null && !prop.getLabel(null).equals(""))
        //					propLabel = prop.getLabel(null);
        String propStr = (pr != null && !pr.equals("")) ? pr + ":" + propLabel : propLabel;

        propertiesList.put(propStr);
        JSONObject propKey = new JSONObject();
        propKey.put(propStr, prop.getURI());
        propertiesMap.put(propKey);
      }

      // Populate the JSON object that will hold everything in output
      outputObj.put(JsonKeys.classList.name(), classesList);
      outputObj.put(JsonKeys.classMap.name(), classesMap);
      outputObj.put(JsonKeys.propertyList.name(), propertiesList);
      outputObj.put(JsonKeys.propertyMap.name(), propertiesMap);

    } catch (JSONException e) {
      logger.error("Error populating JSON!");
    }

    UpdateContainer upd =
        new UpdateContainer(
            new AbstractUpdate() {
              @Override
              public void generateJson(String prefix, PrintWriter pw, VWorkspace vWorkspace) {
                pw.print(outputObj.toString());
              }
            });
    return upd;
  }
  public Collection<PropertyInstance> getAllPropInstByVClasses(List<VClass> vclasses) {

    List<PropertyInstance> propInsts = new ArrayList<PropertyInstance>();

    if (vclasses == null || vclasses.isEmpty()) {
      return propInsts;
    }

    Collections.sort(
        vclasses, new VClassHierarchyRanker(this.getWebappDaoFactory().getVClassDao()));

    OntModel ontModel = getOntModelSelector().getTBoxModel();

    try {

      ontModel.enterCriticalSection(Lock.READ);

      // map object property URI to an array of two resources:
      // the first is the "allValuesFrom" resource and the second is
      // "someValuesFrom"
      Map<String, Resource[]> applicableProperties = new HashMap<String, Resource[]>();

      try {
        for (VClass vclass : vclasses) {
          if (vclass.isAnonymous()) {
            continue;
          }
          String VClassURI = vclass.getURI();

          OntClass ontClass = getOntClass(ontModel, VClassURI);
          if (ontClass != null) {
            List<OntClass> relatedClasses = new ArrayList<OntClass>();
            relatedClasses.addAll(ontClass.listEquivalentClasses().toList());
            relatedClasses.addAll(ontClass.listSuperClasses().toList());
            for (OntClass relatedClass : relatedClasses) {
              // find properties in restrictions
              if (relatedClass.isRestriction()) {
                // TODO: check if restriction is something like
                // maxCardinality 0 or allValuesFrom owl:Nothing,
                // in which case the property is NOT applicable!
                Restriction rest = (Restriction) relatedClass.as(Restriction.class);
                OntProperty onProperty = rest.getOnProperty();
                if (onProperty != null && onProperty.canAs(ObjectProperty.class)) {
                  Resource[] ranges = new Resource[2];
                  if (rest.isAllValuesFromRestriction()) {
                    ranges[0] = (rest.asAllValuesFromRestriction()).getAllValuesFrom();
                  } else if (rest.isSomeValuesFromRestriction()) {
                    ranges[1] = (rest.asSomeValuesFromRestriction()).getSomeValuesFrom();
                  }
                  updatePropertyRangeMap(applicableProperties, onProperty.getURI(), ranges);
                }
              }
            }

            // find properties with class in domain
            ResIterator pit = ontModel.listSubjectsWithProperty(RDFS.domain, ontClass);
            while (pit.hasNext()) {
              Resource prop = pit.nextResource();
              if (prop.getNameSpace() != null
                  && !NONUSER_NAMESPACES.contains(prop.getNameSpace())) {
                StmtIterator rangeSit = prop.listProperties(RDFS.range);
                Resource rangeRes = null;
                while (rangeSit.hasNext()) {
                  Statement s = rangeSit.nextStatement();
                  if (s.getObject().isURIResource()) {
                    rangeRes = (Resource) s.getObject();
                  }
                }
                Resource[] ranges = new Resource[2];
                ranges[0] = rangeRes;
                updatePropertyRangeMap(applicableProperties, prop.getURI(), ranges);
              }
            }
          }
        }
      } catch (Exception e) {
        log.error(
            "Unable to get applicable properties "
                + "by examining property restrictions and domains",
            e);
      }

      // make the PropertyInstance objects
      for (String propertyURI : applicableProperties.keySet()) {
        ObjectProperty op = ontModel.getObjectProperty(propertyURI);
        if (op == null) {
          continue;
        }
        String domainURIStr = getURIStr(op.getDomain());
        Resource[] foundRanges = applicableProperties.get(propertyURI);
        Resource rangeRes =
            (foundRanges[0] != null)
                ? foundRanges[0]
                : (op.getRange() == null && foundRanges[1] != null)
                    ? foundRanges[1]
                    : op.getRange();
        PropertyInstance pi = new PropertyInstance();
        if (rangeRes != null) {
          String rangeClassURI;
          if (rangeRes.isAnon()) {
            rangeClassURI = PSEUDO_BNODE_NS + rangeRes.getId().toString();
          } else {
            rangeClassURI = (String) rangeRes.getURI();
          }
          pi.setRangeClassURI(rangeClassURI);
          try {
            pi.setRangeClassName(
                getWebappDaoFactory().getVClassDao().getVClassByURI(rangeClassURI).getName());
            // pi.setRangeClassName(getLabel(getOntModel().getOntResource(rangeClassURI)));
          } catch (NullPointerException e) {
            /* probably a union or intersection - need to handle this somehow */
          }
        } else {
          pi.setRangeClassURI(OWL.Thing.getURI()); // TODO see above
        }
        pi.setDomainClassURI(domainURIStr);
        try {
          pi.setDomainClassName(
              getWebappDaoFactory().getVClassDao().getVClassByURI(domainURIStr).getName());
          // pi.setDomainClassName(getLabel(getOntModel().getOntResource(op.getDomain().getURI())));
        } catch (NullPointerException e) {
          /* probably a union or intersection - need to handle this somehow */
        }
        pi.setSubjectSide(true);
        pi.setPropertyURI(op.getURI());
        pi.setPropertyName(getLabelOrId(op)); // TODO
        pi.setRangePublic(getLabelOrId(op));
        pi.setDomainPublic(getLabelOrId(op));
        propInsts.add(pi);
      }
    } finally {
      ontModel.leaveCriticalSection();
    }

    Collections.sort(propInsts, new PropInstSorter());
    return propInsts;
  }
Esempio n. 24
0
  private void addField(OntResource type, OntProperty p, OntProperty ancestor) {
    int minCardinality = 0;
    int maxCardinality = -1;
    OntResource range = null;

    String typeURI = type.getURI();
    if (typeURI == null) {
      // We only add fields to named types.
      return;
    }

    // Do not add abstract properties.
    if (isAbstract(p)) return;

    Frame frame = manager.getFrameByUri(typeURI);
    if (frame == null) {
      if (isStandard(typeURI)) return;
      logger.warn(
          "Ignoring property "
              + p.getLocalName()
              + " on class "
              + type.getLocalName()
              + ": frame not found");
      return;
    }

    if (frame.getDeclaredFieldByPropertyURI(p.getURI()) != null) return;

    if (p.hasRDFType(OWL.FunctionalProperty)) {
      maxCardinality = 1;
    }

    OntClass restriction = frame.getRestriction(p.getURI());
    range = p.getRange();
    if (range == null && ancestor != null) {
      range = ancestor.getRange();
    }
    if (range == null) {
      //      logger.warn("Ignoring property " + p.getLocalName() + " on class " +
      // type.getLocalName() + ": range not defined");
      //      return;
      range = THING;
    }
    if (restriction != null) {
      Resource onClass = restriction.getPropertyResourceValue(OWL2.onClass);
      if (onClass != null) {
        range = onClass.as(OntResource.class);
        if (restriction.hasProperty(OWL2.minQualifiedCardinality)) {
          minCardinality = restriction.getProperty(OWL2.minQualifiedCardinality).getInt();
        }
        if (restriction.hasProperty(OWL2.maxQualifiedCardinality)) {
          maxCardinality = restriction.getProperty(OWL2.maxQualifiedCardinality).getInt();
        }

      } else {
        if (restriction.hasProperty(OWL.minCardinality)) {
          minCardinality = restriction.getProperty(OWL.minCardinality).getInt();
        }
        if (restriction.hasProperty(OWL.maxCardinality)) {
          maxCardinality = restriction.getProperty(OWL.maxCardinality).getInt();
        }
      }
    }

    Field field = null;

    String rangeURI = range.getURI();
    if (rangeURI == null) {

      field = createListField(frame, p, range);

      if (field == null) {
        logger.warn(
            "Ignoring property "
                + p.getLocalName()
                + " on class "
                + type.getLocalName()
                + ": range has no URI");
        return;
      }
    } else {

      field = new Field(frame, p, range, minCardinality, maxCardinality);

      if (field.getRdfType() == null) {
        logger.warn(
            "Failed to create RdfType for field "
                + field.getLocalName()
                + " of type "
                + field.getType().getURI());
      }
    }

    Resource rawInverse = p.getPropertyResourceValue(OWL.inverseOf);
    if (rawInverse != null && rawInverse.canAs(OntProperty.class)) {
      field.setInverseOf(rawInverse.as(OntProperty.class));
    }
    frame.getDeclaredFields().add(field);
  }
Esempio n. 25
0
  private void addFieldFromRestriction(
      Map<String, Field> fieldMap, Frame frame, OntClass restriction) {
    int minCardinality = 0;
    int maxCardinality = -1;
    OntResource range = null;

    Resource resource = restriction.getPropertyResourceValue(OWL2.onProperty);
    String uri = resource.getURI();
    Field priorField = fieldMap.get(uri);

    if (priorField != null) {
      maxCardinality = priorField.getMaxCardinality();
    }

    OntProperty property = null;

    if (restriction.getPropertyResourceValue(OWL2.onProperty).canAs(OntProperty.class)) {
      property = resource.as(OntProperty.class);
    } else {
      property = model.createOntProperty(resource.getURI());
    }

    if (property != null && property.canAs(FunctionalProperty.class)) {
      maxCardinality = 1;
    }

    if (restriction.hasProperty(OWL.minCardinality)) {
      minCardinality = restriction.getProperty(OWL.minCardinality).getInt();
    }
    if (restriction.hasProperty(OWL.maxCardinality)) {
      maxCardinality = restriction.getProperty(OWL.maxCardinality).getInt();
    }
    Resource valueType = restriction.getPropertyResourceValue(OWL.allValuesFrom);
    if (valueType != null) {
      range = valueType.as(OntResource.class);
    }

    Resource hasValue = restriction.getPropertyResourceValue(OWL.hasValue);
    NamedIndividual individualValue = null;
    if (hasValue != null && hasValue.getURI() != null) {
      String individualURI = hasValue.getURI();
      individualValue = new NamedIndividual(hasValue.as(OntResource.class));
    }

    //      Resource onClass = restriction.getPropertyResourceValue(OWL2.onClass);
    //      if (onClass != null) {
    //        range = onClass.as(OntResource.class);
    //        if (restriction.hasProperty(OWL2.minQualifiedCardinality)) {
    //          minCardinality = restriction.getProperty(OWL2.minQualifiedCardinality).getInt();
    //        }
    //        if (restriction.hasProperty(OWL2.maxQualifiedCardinality)) {
    //          maxCardinality = restriction.getProperty(OWL2.maxQualifiedCardinality).getInt();
    //        }
    //
    //      } else {
    //        if (restriction.hasProperty(OWL.minCardinality)) {
    //          minCardinality = restriction.getProperty(OWL.minCardinality).getInt();
    //        }
    //        if (restriction.hasProperty(OWL.maxCardinality)) {
    //          maxCardinality = restriction.getProperty(OWL.maxCardinality).getInt();
    //        }
    //      }

    if (range == null) {
      Resource value = property.getPropertyResourceValue(RDFS.range);
      if (value == null) {
        logger.warn(
            "Ignoring field "
                + resource.getLocalName()
                + " on class "
                + frame.getLocalName()
                + ": the range is not defined.");
        return;
      }
      range = property.getPropertyResourceValue(RDFS.range).as(OntResource.class);
    }

    String comment = restriction.getComment(null);
    if (priorField != null && priorField.getDeclaringFrame() == frame) {

      priorField.setComment(comment);
      priorField.setMinCardinality(minCardinality);
      priorField.setMaxCardinality(maxCardinality);
      priorField.setValueRestriction(individualValue);
      return;
    }
    Field field = new Field(frame, property, range, minCardinality, maxCardinality);
    field.setComment(comment);
    field.setValueRestriction(individualValue);
    fieldMap.put(uri, field);

    frame.getDeclaredFields().add(field);
  }
  // get the URIs of the properties and their translation
  public HashMap<String, String> getPropertiesIdentifiers(
      float percentage,
      boolean activeRandomString,
      boolean activeTranslateString,
      boolean activeSynonym,
      int activeStringOperation) {
    HashMap<String, String> propertiesIdentifiers =
        new HashMap<String, String>(); // the HashMap of the properties identifiers
    List<String> propertiesName = new ArrayList<String>(); // the properties identifiers

    List<OntProperty> propertiesTo =
        new ArrayList<OntProperty>(); // the list of properties to be renamed
    List<OntProperty> notRenamedProperties =
        new ArrayList<OntProperty>(); // the list of not renamed properties
    List<OntProperty> properties = getOntologyProperties(); // the list of all the properties

    int nbProperties, toBeRenamed, renamedProperties;

    // build the list of all unrenamed properties from the model
    for (OntProperty p : properties) {
      String local = getLocalName(p.getURI());
      if (alignment.containsKey(local)) {
        if (alignment.getProperty(local).equals(local))
          notRenamedProperties.add(p); // add the property to not renamed properties
      }
    }

    nbProperties = properties.size(); // the number of renamed properties
    renamedProperties = nbProperties - notRenamedProperties.size();
    toBeRenamed =
        Math.round(percentage * nbProperties)
            - renamedProperties; // -renamedProperties -> for Benchmark

    // toBeRenamed is negative when properties have been added to the model
    if (toBeRenamed < 0) toBeRenamed = 0;
    // builds the list of properties to be renamed
    int[] n = randNumbers(notRenamedProperties.size(), toBeRenamed);
    for (int i = 0; i < toBeRenamed; i++) {
      OntProperty p = notRenamedProperties.get(n[i]);
      propertiesTo.add(p);
      if (getNameSpace(p.getURI()).equals(modifiedOntologyNS))
        propertiesName.add(getLocalName(p.getURI()));
    }

    for (OntProperty prop : propertiesTo) {
      String prefix = getNameSpace(prop.getURI());
      String localName = getLocalName(prop.getURI());
      // has the same Namespace as the Ontology Namespace
      if (prefix.equals(modifiedOntologyNS)) {
        if (!propertiesIdentifiers.containsKey(localName)) {
          if (activeTranslateString) { // replace the URI with the translated one
            String translateStrg = parseString(localName, true, false);
            propertiesIdentifiers.put(localName, translateStrg);
            replacePropertyLabel(
                prop.getURI(),
                translateStrg,
                activeRandomString,
                activeTranslateString,
                activeSynonym,
                activeStringOperation);

            if (alignment.containsKey(localName)) { // alignment.remove( prop.getURI() );
              alignment.put(localName, translateStrg); // the reference alignment
            }
          } else if (activeRandomString) { // replace the URI with a random string
            String newStrg = getRandomString();
            propertiesIdentifiers.put(localName, newStrg);
            replacePropertyLabel(
                prop.getURI(),
                newStrg,
                activeRandomString,
                activeTranslateString,
                activeSynonym,
                activeStringOperation);
            if (alignment.containsKey(localName)) { // alignment.remove( prop.getURI() );
              alignment.put(localName, newStrg); // the reference alignment
            }
          } else if (activeSynonym) {
            String synonym = parseString(localName, false, true);
            if (propertiesName.contains(synonym)) propertiesIdentifiers.put(localName, localName);
            else {
              propertiesIdentifiers.put(localName, synonym);
              replacePropertyLabel(
                  prop.getURI(),
                  synonym,
                  activeRandomString,
                  activeTranslateString,
                  activeSynonym,
                  activeStringOperation);
              if (alignment.containsKey(localName)) { // alignment.remove( prop.getURI() );
                alignment.put(localName, synonym); // the reference alignment
              }
            }
          } else if (activeStringOperation == 1) { // replace the URI with the UpperCase URI
            propertiesIdentifiers.put(localName, localName.toUpperCase());
            replacePropertyLabel(
                prop.getURI(),
                localName.toUpperCase(),
                activeRandomString,
                activeTranslateString,
                activeSynonym,
                activeStringOperation);
            if (alignment.containsKey(localName)) { // alignment.remove( prop.getURI() );
              alignment.put(localName, localName.toUpperCase()); // the reference alignment
            }
          } else if (activeStringOperation == 2) {
            propertiesIdentifiers.put(localName, localName.toLowerCase());
            replacePropertyLabel(
                prop.getURI(),
                localName.toLowerCase(),
                activeRandomString,
                activeTranslateString,
                activeSynonym,
                activeStringOperation);
            if (alignment.containsKey(localName)) { // alignment.remove( prop.getURI() );
              alignment.put(localName, localName.toLowerCase()); // the reference alignment
            }
          } else {
            propertiesIdentifiers.put(localName, localName + "PROPERTY");
            replacePropertyLabel(
                prop.getURI(),
                localName + "PROPERTY",
                activeRandomString,
                activeTranslateString,
                activeSynonym,
                activeStringOperation);
            if (alignment.containsKey(localName)) { // alignment.remove( prop.getURI() );
              alignment.put(localName, localName + "PROPERTY");
            }
          }
        }
      }
    }
    return propertiesIdentifiers;
  }
  public void createJenaModel(RegisterContextRequest rcr) {

    OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
    Model entityOnt = FileManager.get().loadModel(ONT_FILE);
    ontModel.addSubModel(entityOnt);
    ontModel.setNsPrefixes(entityOnt.getNsPrefixMap());
    //        ontModel.loadImports();

    ExtendedIterator<OntProperty> iter = ontModel.listAllOntProperties();
    while (iter.hasNext()) {
      OntProperty ontProp = iter.next();
      System.out.println(ontProp.getLocalName());
      //            if (formParams.containsKey(ontProp.getLocalName())) {
      //                regIndividual.addProperty(ontProp,
      // ontModel.getcreateTypedLiteral(formParams.get(ontProp.getLocalName())[0]));
      //            }
    }

    //         OntClass regClass = ontModel.getOntClass(ONT_URL + "iotReg");
    //         OntClass entClass = ontModel.createOntClass(ONT_URL + "entity");
    //        OntClass regClass = (OntClass) ontModel.createOntResource(OntClass.class,
    // null,ONT_URL+"Registration" );
    //        OntClass regClass = (OntClass) ontModel.createClass(ONT_URL + "Registration");
    //        OntClass entityClass = (OntClass) ontModel.createClass(ONT_URL + "Entity");
    OntClass entityGroup = (OntClass) ontModel.getOntClass(ONT_URL + "EntityGroup");
    OntClass entity = (OntClass) ontModel.getOntClass(ONT_URL + "Entity");
    OntClass attribute = (OntClass) ontModel.getOntClass(ONT_URL + "Attribute");
    OntClass metadata = (OntClass) ontModel.getOntClass(ONT_URL + "Metadata");
    OntClass location = (OntClass) ontModel.getOntClass(entityOnt.getNsPrefixURI("geo") + "Point");

    //         System.out.println("Class type is: " + regClass.getLocalName());
    String ngsiValue = "";
    ngsiValue = rcr.getRegistrationId();
    Individual entityGroupIndiv = ontModel.createIndividual(ONT_URL + ngsiValue, entityGroup);
    entityGroupIndiv.setPropertyValue(
        ontModel.getProperty(ONT_URL + "registrationId"), ontModel.createLiteral(ngsiValue));
    ngsiValue = rcr.getTimestamp().toString();
    entityGroupIndiv.setPropertyValue(
        ontModel.getProperty(ONT_URL + "regTimeStamp"), ontModel.createLiteral(ngsiValue));
    ngsiValue = rcr.getDuration();
    entityGroupIndiv.setPropertyValue(
        ontModel.getProperty(ONT_URL + "duration"), ontModel.createLiteral(ngsiValue));

    ngsiValue = rcr.getContextRegistration().get(0).getEntityId().get(0).getId();
    Individual entity1 = ontModel.createIndividual(ONT_URL + ngsiValue, entity);
    entityGroupIndiv.setPropertyValue(ontModel.getProperty(ONT_URL + "hasEntity"), entity1);
    ngsiValue = rcr.getContextRegistration().get(0).getEntityId().get(0).getId();
    entity1.setPropertyValue(
        ontModel.getProperty(ONT_URL + "id"), ontModel.createLiteral(ngsiValue));
    ngsiValue = rcr.getContextRegistration().get(0).getEntityId().get(0).getType();
    entity1.setPropertyValue(
        ontModel.getProperty(ONT_URL + "type"), ontModel.createLiteral(ngsiValue));

    ngsiValue =
        rcr.getContextRegistration().get(0).getContextRegistrationAttribute().get(0).getName();
    Individual attribute1 = ontModel.createIndividual(ONT_URL + ngsiValue, attribute);
    entity1.setPropertyValue(ontModel.getProperty(ONT_URL + "hasAttribute"), attribute1);

    ngsiValue =
        rcr.getContextRegistration().get(0).getContextRegistrationAttribute().get(0).getType();
    attribute1.setPropertyValue(
        ontModel.getProperty(ONT_URL + "type"), ontModel.createLiteral(ngsiValue));

    ngsiValue =
        rcr.getContextRegistration()
            .get(0)
            .getContextRegistrationAttribute()
            .get(0)
            .getContextMetadata()
            .get(0)
            .getName();
    Individual metadata1 = ontModel.createIndividual(ONT_URL + ngsiValue, metadata);
    attribute1.setPropertyValue(ontModel.getProperty(ONT_URL + "hasMetadata"), metadata1);

    ngsiValue =
        rcr.getContextRegistration()
            .get(0)
            .getContextRegistrationAttribute()
            .get(0)
            .getContextMetadata()
            .get(0)
            .getType();
    metadata1.setPropertyValue(
        ontModel.getProperty(ONT_URL + "type"), ontModel.createLiteral(ngsiValue));
    ngsiValue =
        rcr.getContextRegistration()
            .get(0)
            .getContextRegistrationAttribute()
            .get(0)
            .getContextMetadata()
            .get(0)
            .getValue()
            .toString();
    metadata1.setPropertyValue(
        ontModel.getProperty(ONT_URL + "value"), ontModel.createLiteral(ngsiValue));

    ngsiValue =
        rcr.getContextRegistration()
            .get(0)
            .getContextRegistrationAttribute()
            .get(0)
            .getContextMetadata()
            .get(1)
            .getName();
    Individual metadata2 = ontModel.createIndividual(ONT_URL + ngsiValue, metadata);
    attribute1.addProperty(ontModel.getProperty(ONT_URL + "hasMetadata"), metadata2);

    ngsiValue =
        rcr.getContextRegistration()
            .get(0)
            .getContextRegistrationAttribute()
            .get(0)
            .getContextMetadata()
            .get(1)
            .getType();
    metadata2.setPropertyValue(
        ontModel.getProperty(ONT_URL + "type"), ontModel.createLiteral(ngsiValue));
    ngsiValue =
        rcr.getContextRegistration()
            .get(0)
            .getContextRegistrationAttribute()
            .get(0)
            .getContextMetadata()
            .get(1)
            .getValue()
            .toString();
    metadata2.setPropertyValue(
        ontModel.getProperty(ONT_URL + "value"), ontModel.createLiteral(ngsiValue));

    //        ngsiValue =
    // rcr.getContextRegistration().get(0).getContextRegistrationAttribute().get(0).getContextMetadata().get(2).getName();
    //        Individual metadata3 = ontModel.createIndividual(ONT_URL + ngsiValue, metadata);
    //        attribute1.addProperty(ontModel.getProperty(ONT_URL + "hasMetadata"), metadata3);
    //
    //        ngsiValue =
    // rcr.getContextRegistration().get(0).getContextRegistrationAttribute().get(0).getContextMetadata().get(2).getType();
    //        metadata3.setPropertyValue(ontModel.getProperty(ONT_URL + "type"),
    // ontModel.createLiteral(ngsiValue));
    //        ngsiValue =
    // rcr.getContextRegistration().get(0).getContextRegistrationAttribute().get(0).getContextMetadata().get(2).getValue().toString();
    //        metadata3.setPropertyValue(ontModel.getProperty(ONT_URL + "value"),
    // ontModel.createLiteral(ngsiValue));

    //        System.out.println("has propertry
    // \"expiry\":"+entityIndiv.hasProperty(ontModel.getProperty(ONT_URL, "expiry")));

    ontModel.write(System.out, "TURTLE");
    //        ontModel.write(System.out, "RDF/XML");
    //          ontModel.write(System.out, "JSON-LD");

  }
  public void setSubPropertyOf(Properties Properties, OntModel ontologyModel) {

    Iterator<OntProperty> IteratorExtractedProperties =
        Properties.getExtractedProperty().iterator();
    while (IteratorExtractedProperties.hasNext()) {
      OntProperty property = (OntProperty) IteratorExtractedProperties.next();
      String URI = property.getURI();

      if (URI != null) {
        try {
          ExtendedIterator<OntProperty> itSup =
              (ExtendedIterator<OntProperty>) property.listSuperProperties(true);
          while (itSup.hasNext()) {
            OntProperty propertySup = itSup.next();
            String URISUP = propertySup.getURI();

            if (URISUP != null) {
              addSubPropertyOfRelation(property, propertySup);
            }
          }
        } catch (Exception e) {
          // SPARQL Query for SubProperties
          String queryString =
              "PREFIX rdfs:<"
                  + RDFS.getURI()
                  + ">"
                  + "PREFIX ont:<"
                  + property.getNameSpace()
                  + ">"
                  + "SELECT ?obj "
                  + "WHERE {"
                  + "      ont:"
                  + property.getLocalName()
                  + " rdfs:subPropertyOf ?obj"
                  + "      }";

          // Execute Query
          Query query = QueryFactory.create(queryString);
          QueryExecution qexec = QueryExecutionFactory.create(query, ontologyModel);

          try {

            ResultSet results = qexec.execSelect();

            // Temporary Model in Order to Construct Node for External Property
            OntModel ontologyTempModel =
                ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, null);

            // Extract Relation
            for (; results.hasNext(); ) {
              QuerySolution soln = results.nextSolution();

              Resource obj = soln.getResource("obj");
              String URIObj = obj.getURI();

              // Get SubPropertyOf all Property different from the current one
              if (URIObj != null && property.getURI() != URIObj) {
                OntProperty propertySup = ontologyTempModel.createOntProperty(URIObj);

                // Save SubPropertyOf Relation (property SubPropertyOf PropertySub)
                addSubPropertyOfRelation(property, propertySup);
              }
            }
          } finally {
            qexec.close();
          }
        }
      }
    }
  }