示例#1
0
 @Override
 public List<Node> getSubjects(Node predicate, Node object) {
   Model graph = null;
   GraphConnection graphConnection = null;
   try {
     graphConnection = openGraph();
     graph = graphConnection.getGraph();
     graph.enterCriticalSection(Lock.READ);
     SimpleSelector selector = getJenaSelector(graph, new StatementImpl(null, predicate, object));
     ResIterator it =
         graph.listSubjectsWithProperty(selector.getPredicate(), selector.getObject());
     List<Node> res = new ArrayList<Node>();
     while (it.hasNext()) {
       res.add(getNXRelationsNode(it.nextResource().asNode()));
     }
     return res;
   } finally {
     if (graph != null) {
       graph.leaveCriticalSection();
     }
     if (graphConnection != null) {
       graphConnection.close();
     }
   }
 }
示例#2
0
 private String getConfigsUriFromPrefix(String pre) {
   ResIterator subjects = config.listSubjectsWithProperty(EYE.prefix, config.createLiteral(pre));
   if (subjects.hasNext()) {
     StmtIterator uris = config.listStatements(subjects.nextResource(), EYE.nsURI, (RDFNode) null);
     if (uris.hasNext()) return uris.nextStatement().getObject().asNode().getLiteralLexicalForm();
   }
   return null; // Return null otherwise
 }
  /**
   * Index all the resources in a Jena Model to ES
   *
   * @param model the model to index
   * @param bulkRequest a BulkRequestBuilder
   * @param getPropLabel if set to true all URI property values will be indexed as their label. The
   *     label is taken as the value of one of the properties set in {@link #uriDescriptionList}.
   */
  private void addModelToES(Model model, BulkRequestBuilder bulkRequest, boolean getPropLabel) {
    long startTime = System.currentTimeMillis();
    long bulkLength = 0;
    HashSet<Property> properties = new HashSet<Property>();

    StmtIterator it = model.listStatements();
    while (it.hasNext()) {
      Statement st = it.nextStatement();
      Property prop = st.getPredicate();
      String property = prop.toString();

      if (rdfPropList.isEmpty()
          || (isWhitePropList && rdfPropList.contains(property))
          || (!isWhitePropList && !rdfPropList.contains(property))
          || (normalizeProp.containsKey(property))) {
        properties.add(prop);
      }
    }

    ResIterator resIt = model.listSubjects();

    while (resIt.hasNext()) {
      Resource rs = resIt.nextResource();
      Map<String, ArrayList<String>> jsonMap = getJsonMap(rs, properties, model, getPropLabel);

      bulkRequest.add(
          client.prepareIndex(indexName, typeName, rs.toString()).setSource(mapToString(jsonMap)));
      bulkLength++;

      // We want to execute the bulk for every  DEFAULT_BULK_SIZE requests
      if (bulkLength % EEASettings.DEFAULT_BULK_SIZE == 0) {
        BulkResponse bulkResponse = bulkRequest.execute().actionGet();
        // After executing, flush the BulkRequestBuilder.
        bulkRequest = client.prepareBulk();

        if (bulkResponse.hasFailures()) {
          processBulkResponseFailure(bulkResponse);
        }
      }
    }

    // Execute remaining requests
    if (bulkRequest.numberOfActions() > 0) {
      BulkResponse response = bulkRequest.execute().actionGet();
      // Handle failure by iterating through each bulk response item
      if (response.hasFailures()) {
        processBulkResponseFailure(response);
      }
    }

    // Show time taken to index the documents
    logger.info(
        "Indexed {} documents on {}/{} in {} seconds",
        bulkLength,
        indexName,
        typeName,
        (System.currentTimeMillis() - startTime) / 1000.0);
  }
示例#4
0
 @Override
 protected List<Resource> getModelTargetConnections() {
   final Resource property = getResource();
   final List<Resource> list = new ArrayList<Resource>();
   final ResIterator iterator =
       property.getModel().listSubjectsWithProperty(Schema.destination, property);
   while (iterator.hasNext()) {
     list.add(iterator.nextResource());
   }
   return list;
 }
  public ArrayList<String> getOrganizations() {
    long startTime = System.currentTimeMillis();

    ArrayList<String> organizations = new ArrayList<String>();

    Resource organization = ontModel.getResource(ORGANIZATION_CLASS);

    ResIterator iter = ontModel.listSubjectsWithProperty(RDF.type, organization);

    if (iter.hasNext()) {
      LOGGER.info("Organizations were found in the database");
      LOGGER.debug("The database contains these organizations:");
      while (iter.hasNext()) {
        Resource organizationResource = iter.nextResource();
        String organizationUri = organizationResource.getURI();
        LOGGER.debug(organizationUri);
        //		        String organizationId =
        // organizationResource.getProperty(ontModel.getProperty(ORGID)).getString();
        //		        System.out.println("  " + organizationId);
        organizations.add(organizationUri);
        // System.out.println("   -" +
        // iter.nextResource().getProperty(ontModel.getProperty("http://www.smartdeveloperhub.org/vocabulary/organization#id")).getString());
        // System.out.println("   -" +
        // iter.nextResource().getProperty(ontModel.getProperty("http://www.w3.org/ns/org#classification")).getResource().getURI());
      }
    } else {
      LOGGER.info("No organizations were found in the database");
    }

    long stopTime = System.currentTimeMillis();
    long elapsedTime = stopTime - startTime;
    // System.out.println("Load organizations, elapsed time (ms):"+elapsedTime);
    LOGGER.debug("- Load organizations, elapsed time (ms)..: {}", elapsedTime);

    return organizations;
  }
 private void processPermanentURIRequest(VitroRequest vreq, ModelMaker maker) {
   String modelName = vreq.getParameter("modelName");
   String oldModel = vreq.getParameter("oldModel");
   String newModel = vreq.getParameter("newModel");
   String oldNamespace = vreq.getParameter("oldNamespace");
   String newNamespace = vreq.getParameter("newNamespace");
   String dNamespace = vreq.getParameter("defaultNamespace");
   newNamespace = (newNamespace == null || newNamespace.isEmpty()) ? oldNamespace : newNamespace;
   newNamespace = (dNamespace != null) ? dNamespace : newNamespace;
   if (modelName != null) {
     Model m = maker.getModel(modelName);
     List<String> namespaceList = new ArrayList<>();
     ResIterator resItr = m.listResourcesWithProperty((Property) null);
     if (resItr != null) {
       while (resItr.hasNext()) {
         String namespace = resItr.nextResource().getNameSpace();
         if (!namespaceList.contains(namespace)) {
           namespaceList.add(namespace);
         }
       }
     } else {
       namespaceList.add("no resources present");
     }
     String defaultNamespace = vreq.getUnfilteredWebappDaoFactory().getDefaultNamespace();
     vreq.setAttribute("modelName", modelName);
     vreq.setAttribute("defaultNamespace", defaultNamespace);
     vreq.setAttribute("namespaceList", namespaceList);
     vreq.setAttribute("title", "Permanent URI");
     vreq.setAttribute("bodyJsp", PERMANENT_URI);
   } else if (oldModel != null) {
     JenaIngestUtils utils = new JenaIngestUtils();
     utils.doPermanentURI(oldModel, newModel, oldNamespace, newNamespace, maker, vreq);
     vreq.setAttribute("title", "Ingest Menu");
     vreq.setAttribute("bodyJsp", INGEST_MENU_JSP);
   }
 }
  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;
  }
示例#8
0
  public void doctorModel(Model report, Model m, Model config) {
    this.input = m;
    this.repair = report;
    this.output = this.input;
    this.config = config;

    ResIterator it = repair.listSubjectsWithProperty(EYE.repairType, EYE.replaceNamespace);
    while (it.hasNext()) {
      /*
       * We are able to make one or more of the following assumptions;
       * (1)	o The Prefix is probably desired                                       \\
       * (3)	o The URI is likely misspelt                                          ===>  Work these with the precedence specified
       * (2)	o The URI is right, but the user mistakenly used a 'reserved' prefix   //
       */
      Resource curr = it.nextResource();
      String prefix =
          repair
              .listObjectsOfProperty(curr, EYE.onPrefix)
              .nextNode()
              .asNode()
              .getLiteralLexicalForm();
      String currUri = output.getNsPrefixURI(prefix);
      String configsUri = getConfigsUriFromPrefix(prefix);
      String configsPre = null;
      if (currUri != null) configsPre = getConfigsPrefixFromUri(currUri);
      if (configsUri != null) // Change the URI to a preferred one
      changeNsUri(currUri, configsUri);
      else if (configsPre != null) // Use that URI, but set the prefix according to config
      changeNsPrefix(prefix, configsPre);
      else // Use the 'expected' URI
      output.setNsPrefix(
            prefix,
            repair
                .listObjectsOfProperty(curr, EYE.expected)
                .nextNode()
                .asNode()
                .getLiteralLexicalForm());
    }

    it = repair.listSubjectsWithProperty(EYE.repairType, EYE.removeDuplicatePrefixes);
    while (it.hasNext()) {
      Resource curr = it.nextResource();
      NodeIterator it2 = repair.listObjectsOfProperty(curr, EYE.onPrefix);
      String uri =
          repair
              .listObjectsOfProperty(curr, EYE.multiplePrefixesForNamespace)
              .nextNode()
              .asNode()
              .getLiteralLexicalForm();
      if (it2.hasNext()) {
        boolean oneKept = false;
        while (it2.hasNext()) {
          RDFNode curra = it2.nextNode();
          if (m.getNsPrefixURI(curra.asNode().getLiteralLexicalForm()) != null)
            if (m.getNsPrefixURI(curra.asNode().getLiteralLexicalForm())
                .equals(uri)) // The prefix is still used in the model
            {
              if (oneKept) m.removeNsPrefix(curra.asNode().getLiteralLexicalForm());
              else oneKept = true;
            }
        }
      }
    }
  }