Beispiel #1
0
  private void changeNsUri(String from, String to) {
    /*
     *   o Change all usages of URI 'from' to 'to'
     *   o Set the prefix of 'from' to be that of 'to'
     */
    Model toAdd = ModelFactory.createDefaultModel();
    Model toDel = ModelFactory.createDefaultModel();
    Resource newUri = output.createResource(to);
    StmtIterator it = output.listStatements(output.createResource(from), null, (RDFNode) null);
    while (it.hasNext()) {
      Statement curr = it.nextStatement();
      toDel.add(curr);
      toAdd.add(newUri, curr.getPredicate(), curr.getObject());
    }

    it = output.listStatements(null, null, output.createResource(from));
    while (it.hasNext()) {
      Statement curr = it.nextStatement();
      toDel.add(curr);
      toAdd.add(curr.getSubject(), curr.getPredicate(), newUri);
    }

    output.remove(toDel);
    output.add(toAdd);

    String prefix = output.getNsURIPrefix(from);
    output.setNsPrefix(prefix, to);
  }
 @Override
 public int compare(Statement s1, Statement s2) {
   return ComparisonChain.start()
       .compare(s1.getPredicate().asNode(), s2.getPredicate().asNode(), nodeComparator)
       .compare(s1.getObject().asNode(), s2.getObject().asNode(), nodeComparator)
       .result();
 }
  public void addedStatement(com.hp.hpl.jena.rdf.model.Statement stmt) {

    if (stmt.getPredicate().equals(hasContextProperty)) {
      if (!stmt.getObject().canAs(com.hp.hpl.jena.rdf.model.Resource.class)) return;
      com.hp.hpl.jena.rdf.model.Resource resource =
          (com.hp.hpl.jena.rdf.model.Resource)
              stmt.getObject().as(com.hp.hpl.jena.rdf.model.Resource.class);
      hasContext = null;
      if (true) { // don't check resource type if the property range is Resource
        try {
          hasContext =
              ibspan.tss.um.ontology.UserModellingFactory.getUserBehaviourContext(resource, _model);
        } catch (JastorException e) {
          // e.printStackTrace();
        }
      }
      if (listeners != null) {
        java.util.ArrayList consumers;
        synchronized (listeners) {
          consumers = (java.util.ArrayList) listeners.clone();
        }
        for (java.util.Iterator iter = consumers.iterator(); iter.hasNext(); ) {
          ExtendedUserBehaviourListener listener = (ExtendedUserBehaviourListener) iter.next();
          listener.hasContextChanged(ibspan.tss.um.ontology.ExtendedUserBehaviourImpl.this);
        }
      }
      return;
    }
    if (stmt.getPredicate().equals(hasUserBehaviourProperty)) {
      if (!stmt.getObject().canAs(com.hp.hpl.jena.rdf.model.Resource.class)) return;
      com.hp.hpl.jena.rdf.model.Resource resource =
          (com.hp.hpl.jena.rdf.model.Resource)
              stmt.getObject().as(com.hp.hpl.jena.rdf.model.Resource.class);
      hasUserBehaviour = null;
      if (true) { // don't check resource type if the property range is Resource
        try {
          hasUserBehaviour =
              ibspan.tss.um.ontology.UserModellingFactory.getUserBehaviour(resource, _model);
        } catch (JastorException e) {
          // e.printStackTrace();
        }
      }
      if (listeners != null) {
        java.util.ArrayList consumers;
        synchronized (listeners) {
          consumers = (java.util.ArrayList) listeners.clone();
        }
        for (java.util.Iterator iter = consumers.iterator(); iter.hasNext(); ) {
          ExtendedUserBehaviourListener listener = (ExtendedUserBehaviourListener) iter.next();
          listener.hasUserBehaviourChanged(ibspan.tss.um.ontology.ExtendedUserBehaviourImpl.this);
        }
      }
      return;
    }
  }
  public void deduceLocation() {
    Property loc = model.getModel().getProperty(uri, "hasLocation");

    for (Resource human : humans) {

      Statement ss1 = null;
      String s = "";
      Resource r = null;

      StmtIterator locii = model.getModel().listStatements(human, loc, (RDFNode) null);
      if (locii.hasNext()) {
        ss1 = (Statement) locii.next();
        System.out.println(
            "initial statements:"
                + ss1.getSubject().getLocalName()
                + " "
                + ss1.getPredicate().getLocalName()
                + " "
                + ss1.getResource().getLocalName());
      }

      StmtIterator loci = infmodel.getDeductionsModel().listStatements(human, loc, (RDFNode) null);
      if (loci.hasNext()) {
        Statement ssl = (Statement) loci.next();
        RDFNode obj = (RDFNode) ssl.getObject();
        if (obj instanceof Resource) {
          r = (Resource) obj;
          s = r.getLocalName();
        } else {
          System.out.print("!!! Literal");
        }
        System.out.println(
            "Inferred: user: "******" changed location to room "
                + s);
      }

      if (r != null) ss1.changeObject(r);

      StmtIterator fi = model.getModel().listStatements(human, loc, (RDFNode) null);
      while (fi.hasNext()) {
        Statement ss = (Statement) fi.next();
        System.out.println(
            "After updating the ontology \n"
                + ss.getSubject().getLocalName()
                + " "
                + ss.getPredicate().getLocalName()
                + " "
                + ss.getResource().getLocalName());
      }
    }
  }
Beispiel #5
0
 private static void printModel(OntModel model, Property prop) {
   StmtIterator stit = model.listStatements();
   Statement st = null;
   while (stit.hasNext()) {
     st = stit.next();
     if (prop == null || prop.equals(st.getPredicate())) {
       System.out.println("S: " + st.getSubject());
       System.out.println("P: " + st.getPredicate());
       System.out.println("O: " + st.getObject());
     }
   }
 }
  public void deduceAuthorization() {

    Property auth = model.getModel().getProperty(uri, "isAuthenticatedBy");

    for (Resource human : humans) {

      Resource r = null;

      StmtIterator ii = model.getModel().listStatements(human, auth, (RDFNode) null);
      if (ii.hasNext()) {
        Statement ss1 = (Statement) ii.next();
        System.out.println(
            "initial statements:"
                + ss1.getSubject().getLocalName()
                + " "
                + ss1.getPredicate().getLocalName()
                + " "
                + ss1.getResource().getLocalName());

        StmtIterator iii =
            infmodel.getDeductionsModel().listStatements(human, auth, (RDFNode) null);
        if (iii.hasNext()) {
          Statement ss2 = (Statement) iii.next();
          System.out.println(
              "inferred: "
                  + ss2.getSubject().getLocalName()
                  + " "
                  + ss2.getPredicate().getLocalName()
                  + " "
                  + ss2.getResource().getLocalName());
          r = ss2.getResource();
        }

        if (r != null) ss1.changeObject(r);

        StmtIterator fi = model.getModel().listStatements(human, auth, (RDFNode) null);
        while (fi.hasNext()) {
          Statement ss = (Statement) fi.next();
          System.out.println(
              "After updating the ontology \n"
                  + ss.getSubject().getLocalName()
                  + " "
                  + ss.getPredicate().getLocalName()
                  + " "
                  + ss.getResource().getLocalName());
        }
      }
    }
  }
  public static Triple createTriple(Statement statement) throws OREException {
    try {
      URI subject = new URI(statement.getSubject().getURI());
      Property property = statement.getPredicate();

      Predicate pred = new Predicate();
      pred.setURI(new URI(property.getURI()));

      TripleJena triple = new TripleJena();
      triple.initialise(new URI(statement.getSubject().getURI()));

      RDFNode node = statement.getObject();
      if (node instanceof Resource) {
        String uris = ((Resource) node).getURI();

        // if the object is not a blank node, we include it
        if (uris != null) {
          URI object = new URI(uris);
          triple.relate(pred, object);
        }
      } else {
        String object = ((Literal) statement.getObject()).getLexicalForm();
        triple.relate(pred, object);
      }

      return triple;
    } catch (URISyntaxException e) {
      throw new OREException(e);
    }
  }
Beispiel #8
0
  private static boolean hasPermission(
      String userPrefix, String username, String uri, Property[] permissions) {
    Set<Property> permissionSet = new HashSet<Property>();
    Resource resource = configModel.createResource(uri);
    Resource user;

    if (username == null) user = PERM.Public;
    else user = configModel.createResource(userPrefix + username);

    for (Property permission : permissions) {
      if (configModel.contains(user, permission, resource)) return true;
      permissionSet.add(permission);
    }

    StmtIterator stmts = user.listProperties();
    while (stmts.hasNext()) {
      Statement stmt = stmts.next();
      if (!permissionSet.contains(stmt.getPredicate())) continue;
      RDFNode resourceMatch = stmt.getObject();
      if (!(resourceMatch.isResource()
          && configModel.contains((Resource) resourceMatch, RDF.type, PERM.ResourceMatch)))
        continue;

      RDFNode matchRegex = ((Resource) resourceMatch).getProperty(PERM.matchExpression).getObject();
      if (matchRegex == null || !matchRegex.isLiteral()) continue;

      try {
        if (uri.matches(((Literal) matchRegex).getString())) return true;
      } catch (PatternSyntaxException e) {
      }
    }

    if (username != null) return hasPermission(userPrefix, null, uri, permissions);
    else return false;
  }
Beispiel #9
0
  @Override
  public Edge getEdge(final Object id) {
    final String[] keys = id.toString().split("->");
    final StmtIterator statements =
        model.listStatements(
            new SimpleSelector() {

              @Override
              public boolean selects(final Statement s) {
                if (s.getObject().isResource()
                    && s.getSubject().isResource()
                    && s.getSubject().asResource().getURI().equals(keys[0])
                    && s.getPredicate().asResource().getURI().equals(keys[1])
                    && s.getObject().asResource().getURI().equals(keys[2])) {
                  return true;
                }
                return false;
              }
            });
    JenaEdge edge = null;
    if (statements.hasNext()) {
      final Statement statement = statements.next();
      final Property predicate = statement.getPredicate();
      edge = new JenaEdge(model, predicate, statement.getSubject(), statement.getObject());
    }
    return edge;
  }
Beispiel #10
0
 private void writeTriple(Statement stmt) throws IOException {
   write("    <triple>\n");
   writeNode(stmt.getSubject());
   writeNode(stmt.getPredicate());
   writeNode(stmt.getObject());
   write("    </triple>\n");
 }
  /**
   * purgeRelationship should be idempotent with respect to the returned HTTP status code. The
   * response body however, should indicate "false" for successive deletes of the same resource.
   *
   * @throws Exception
   */
  @Test
  public void testIdempotency() throws Exception {
    FedoraResponse response = null;
    Model model = null;
    Statement s = null;
    String subject = String.format("info:fedora/%s", testPid);
    String predicate = "urn:foo/p";
    String object = "你好";

    // first add a relationship
    response = addRelationship(testPid).predicate(predicate).object(object, true).execute();
    assertEquals(200, response.getStatus());

    // verify it was added
    response = getRelationships(testPid).predicate(predicate).execute();
    assertEquals(200, response.getStatus());
    model = ModelFactory.createDefaultModel();
    model.read(response.getEntityInputStream(), null, FileUtils.langXML);
    StmtIterator it = model.listStatements();
    while (it.hasNext()) {
      s = it.next();
      assertEquals(subject, s.getSubject().toString());
      assertEquals(predicate, s.getPredicate().toString());
      assertEquals(object, s.getObject().toString());
    }

    // now delete it
    response = purgeRelationship(testPid).predicate(predicate).object(object, true).execute();
    assertEquals(200, response.getStatus());
    assertEquals("true", response.getEntity(String.class));

    // verify it's gone
    response = getRelationships(testPid).predicate(predicate).execute();
    assertEquals(200, response.getStatus());
    model = ModelFactory.createDefaultModel();
    model.read(response.getEntityInputStream(), null, FileUtils.langXML);
    it = model.listStatements();
    while (it.hasNext()) {
      s = it.next();
      assertFalse(predicate.equals(s.getPredicate().toString()));
      assertFalse(object.equals(s.getObject().toString()));
    }

    response = purgeRelationship(testPid).predicate(predicate).object(object, true).execute();
    assertEquals(200, response.getStatus());
    assertEquals("false", response.getEntity(String.class));
  }
 public Individual fillExistingDataPropertyStatementsForIndividual(
     Individual entity /*, boolean allowAnyNameSpace*/) {
   if (entity.getURI() == null) {
     return entity;
   } else {
     OntModel ontModel = getOntModelSelector().getABoxModel();
     ontModel.enterCriticalSection(Lock.READ);
     try {
       Resource ind = ontModel.getResource(entity.getURI());
       List<DataPropertyStatement> edList = new ArrayList<DataPropertyStatement>();
       StmtIterator stmtIt = ind.listProperties();
       while (stmtIt.hasNext()) {
         Statement st = (Statement) stmtIt.next();
         boolean addToList = /*allowAnyNameSpace ? st.getObject().canAs(Literal.class) :*/
             st.getObject().isLiteral()
                 && ((RDF.value.equals(st.getPredicate())
                         || VitroVocabulary.value.equals(st.getPredicate().getURI()))
                     || !(NONUSER_NAMESPACES.contains(st.getPredicate().getNameSpace())));
         if (addToList) {
             /* now want to expose Cornellemailnetid and potentially other properties so can at least control whether visible
             boolean isExternalId = false;
             ClosableIterator externalIdStmtIt = getOntModel().listStatements(st.getPredicate(), DATAPROPERTY_ISEXTERNALID, (Literal)null);
             try {
                 if (externalIdStmtIt.hasNext()) {
                     isExternalId = true;
                 }
             } finally {
                 externalIdStmtIt.close();
             }
             if (!isExternalId) { */
           DataPropertyStatement ed = new DataPropertyStatementImpl();
           Literal lit = (Literal) st.getObject();
           fillDataPropertyStatementWithJenaLiteral(ed, lit);
           ed.setDatapropURI(st.getPredicate().getURI());
           ed.setIndividualURI(ind.getURI());
           ed.setIndividual(entity);
           edList.add(ed);
           /* } */
         }
       }
       entity.setDataPropertyStatements(edList);
       return entity;
     } finally {
       ontModel.leaveCriticalSection();
     }
   }
 }
  /**
   * 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);
  }
Beispiel #14
0
 @Test
 public void test() {
   PropertyFilter filter = new PropertyFilter(TestData.foaf_firstname);
   log.info("Testing the {} class", filter.getClass());
   Set<Statement> output = TestData.alexdma.getModel().listStatements().filterKeep(filter).toSet();
   for (Statement statement : output) {
     assertTrue(statement.getPredicate().equals(TestData.foaf_firstname));
   }
 }
 public DataPropertyStatement(OWLObject<?> subject, Statement s) {
   super(subject, s);
   property = getOntology().getDataProperty(s.getPredicate().getURI());
   if (s.getObject() instanceof Literal) {
     literal = (Literal) s.getObject();
   } else {
     logger.warning("DataPropertyStatement: object is not a Literal !");
   }
 }
Beispiel #16
0
 private static void doStatement(StringBuffer json, Statement statement) {
   json.append("{\n    \"s\": ");
   doNode(json, statement.getSubject());
   json.append(",\n   \"p\": ");
   doNode(json, statement.getPredicate());
   json.append(",\n   \"o\": ");
   doNode(json, statement.getObject());
   json.append("}");
 }
Beispiel #17
0
 /** Converts all object occurances of rdfs:Resource with owl:Thing */
 private void convertRDFSResource() {
   for (StmtIterator it = model.listStatements(null, null, RDFS.Resource); it.hasNext(); ) {
     Statement s = it.nextStatement();
     s.getModel().add(s.getSubject(), s.getPredicate(), OWL.Thing);
     if (log.isLoggable(Level.FINE)) {
       log.fine("Replaced triple " + s + " with (x, x, owl:Thing)");
     }
     it.remove();
   }
 }
 public void testFindProperty() {
   StmtIterator iter = model.listStatements(new SimpleSelector(null, RDFS.label, (RDFNode) null));
   int i = 0;
   while (iter.hasNext()) {
     i++;
     Statement stmt = iter.nextStatement();
     assertEquals(RDFS.label, stmt.getPredicate());
   }
   assertEquals(2, i);
 }
 public void testFindPropertyAndObject() {
   StmtIterator iter = model.listStatements(new SimpleSelector(null, RDF.value, 123));
   int i = 0;
   while (iter.hasNext()) {
     i++;
     Statement stmt = iter.nextStatement();
     assertEquals(RDF.value, stmt.getPredicate());
     assertEquals(123, stmt.getInt());
   }
   assertEquals(2, i);
 }
 public static ObjectIntOpenHashMap<String> generateMapWithAllResources(Model model) {
   if (resourcesWithoutCounts == null) {
     resourcesWithoutCounts = new ObjectIntOpenHashMap<String>();
     StmtIterator stmtIter = model.listStatements();
     Statement s;
     while (stmtIter.hasNext()) {
       s = stmtIter.next();
       if (s.getSubject().isResource() && !s.getSubject().isAnon()) {
         resourcesWithoutCounts.putIfAbsent(s.getSubject().getURI(), 0);
       }
       if (s.getPredicate().isResource()) {
         resourcesWithoutCounts.putIfAbsent(s.getPredicate().getURI(), 0);
       }
       if (s.getObject().isResource() && !s.getObject().isAnon()) {
         resourcesWithoutCounts.putIfAbsent(s.getObject().asResource().getURI(), 0);
       }
     }
   }
   return resourcesWithoutCounts.clone();
 }
 public void removedStatement(com.hp.hpl.jena.rdf.model.Statement stmt) {
   //			if (!stmt.getSubject().equals(_resource))
   //				return;
   if (stmt.getPredicate().equals(hasContextProperty)) {
     if (!stmt.getObject().canAs(com.hp.hpl.jena.rdf.model.Resource.class)) return;
     com.hp.hpl.jena.rdf.model.Resource resource =
         (com.hp.hpl.jena.rdf.model.Resource)
             stmt.getObject().as(com.hp.hpl.jena.rdf.model.Resource.class);
     if (hasContext != null && hasContext.resource().equals(resource)) hasContext = null;
     if (listeners != null) {
       java.util.ArrayList consumers;
       synchronized (listeners) {
         consumers = (java.util.ArrayList) listeners.clone();
       }
       for (java.util.Iterator iter = consumers.iterator(); iter.hasNext(); ) {
         ExtendedUserBehaviourListener listener = (ExtendedUserBehaviourListener) iter.next();
         listener.hasContextChanged(ibspan.tss.um.ontology.ExtendedUserBehaviourImpl.this);
       }
     }
     return;
   }
   if (stmt.getPredicate().equals(hasUserBehaviourProperty)) {
     if (!stmt.getObject().canAs(com.hp.hpl.jena.rdf.model.Resource.class)) return;
     com.hp.hpl.jena.rdf.model.Resource resource =
         (com.hp.hpl.jena.rdf.model.Resource)
             stmt.getObject().as(com.hp.hpl.jena.rdf.model.Resource.class);
     if (hasUserBehaviour != null && hasUserBehaviour.resource().equals(resource))
       hasUserBehaviour = null;
     if (listeners != null) {
       java.util.ArrayList consumers;
       synchronized (listeners) {
         consumers = (java.util.ArrayList) listeners.clone();
       }
       for (java.util.Iterator iter = consumers.iterator(); iter.hasNext(); ) {
         ExtendedUserBehaviourListener listener = (ExtendedUserBehaviourListener) iter.next();
         listener.hasUserBehaviourChanged(ibspan.tss.um.ontology.ExtendedUserBehaviourImpl.this);
       }
     }
     return;
   }
 }
 public void doCleanLiterals(Model model) {
   Model retractionsModel = ModelFactory.createDefaultModel();
   Model additionsModel = ModelFactory.createDefaultModel();
   model.enterCriticalSection(Lock.WRITE);
   try {
     ClosableIterator<Statement> closeIt = model.listStatements();
     try {
       for (Iterator<Statement> stmtIt = closeIt; stmtIt.hasNext(); ) {
         Statement stmt = stmtIt.next();
         if (stmt.getObject().isLiteral()) {
           Literal lit = (Literal) stmt.getObject();
           String lex = lit.getLexicalForm();
           char[] chars = lex.toCharArray();
           char[] cleanChars = new char[chars.length];
           int cleanPos = 0;
           boolean badChar = false;
           for (int i = 0; i < chars.length; i++) {
             if (java.lang.Character.getNumericValue(chars[i]) > 31
                 && java.lang.Character.isDefined(chars[i])) {
               cleanChars[cleanPos] = chars[i];
               cleanPos++;
             } else {
               log.error("Bad char in " + lex);
               log.error("Numeric value " + java.lang.Character.getNumericValue(chars[i]));
               badChar = true;
             }
           }
           String cleanLex = new String(cleanChars);
           if (badChar) {
             retractionsModel.add(stmt);
             Literal newLit = null;
             if (lit.getLanguage() != null && lit.getLanguage().length() > 0) {
               newLit = additionsModel.createLiteral(cleanLex, lit.getLanguage());
             } else if (lit.getDatatype() != null) {
               newLit = additionsModel.createTypedLiteral(cleanLex, lit.getDatatype());
             } else {
               newLit = additionsModel.createLiteral(cleanLex);
             }
             additionsModel.add(stmt.getSubject(), stmt.getPredicate(), newLit);
           }
         }
       }
     } finally {
       closeIt.close();
     }
     model.remove(retractionsModel);
     model.add(additionsModel);
     log.debug("Cleaned " + additionsModel.size() + " literals");
   } finally {
     model.leaveCriticalSection();
   }
 }
Beispiel #23
0
 @Override
 public Iterable<Edge> getEdges() {
   final Set<Edge> edges = new HashSet<Edge>();
   final StmtIterator statements = model.listStatements();
   while (statements.hasNext()) {
     final Statement statement = statements.next();
     final Property predicate = statement.getPredicate();
     if (statement.getSubject().isResource() && statement.getObject().isResource()) {
       edges.add(new JenaEdge(model, predicate, statement.getSubject(), statement.getObject()));
     }
   }
   return edges;
 }
Beispiel #24
0
  /**
   * Gets NXRelations statement corresponding to the Jena statement.
   *
   * <p>Reified statements may be retrieved from the Jena graph and set as properties on NXRelations
   * statements.
   *
   * @param graph the jena graph
   * @param jenaStatement jena statement
   * @return NXRelations statement
   */
  private Statement getNXRelationsStatement(
      Model graph, com.hp.hpl.jena.rdf.model.Statement jenaStatement) {
    Node subject = getNXRelationsNode(jenaStatement.getSubject().asNode());
    Node predicate = getNXRelationsNode(jenaStatement.getPredicate().asNode());
    Node object = getNXRelationsNode(jenaStatement.getObject().asNode());
    Statement statement = new StatementImpl(subject, predicate, object);

    // take care of properties
    if (graph.isReified(jenaStatement)) {
      com.hp.hpl.jena.rdf.model.Resource reifiedStmt = graph.getAnyReifiedStatement(jenaStatement);
      StmtIterator it = reifiedStmt.listProperties();
      while (it.hasNext()) {
        com.hp.hpl.jena.rdf.model.Statement stmt = it.nextStatement();
        Node nuxNode = getNXRelationsNode(stmt.getPredicate().asNode());
        // ugly cast as a Resource
        Node value = getNXRelationsNode(stmt.getObject().asNode());
        statement.addProperty((Resource) nuxNode, value);
      }
    }

    return statement;
  }
  private void createViolatingTriple(Statement stmt, String resource) {
    Model m = ModelFactory.createDefaultModel();

    Resource subject = m.createResource(resource);
    m.add(new StatementImpl(subject, QPRO.exceptionDescription, DQM.ViolatingTriple));

    RDFNode violatedTriple = Commons.generateRDFBlankNode();
    m.add(new StatementImpl(violatedTriple.asResource(), RDF.type, RDF.Statement));
    m.add(new StatementImpl(violatedTriple.asResource(), RDF.subject, stmt.getSubject()));
    m.add(new StatementImpl(violatedTriple.asResource(), RDF.predicate, stmt.getPredicate()));
    m.add(new StatementImpl(violatedTriple.asResource(), RDF.object, stmt.getObject()));

    m.add(new StatementImpl(subject, DQM.hasViolatingTriple, violatedTriple));

    this._problemList.add(m);
  }
 private String renderStatement(Statement stmt) {
   String subjStr =
       (stmt.getSubject().getURI() != null)
           ? stmt.getSubject().getURI()
           : stmt.getSubject().getId().toString();
   String predStr = stmt.getPredicate().getURI();
   String objStr = "";
   RDFNode obj = stmt.getObject();
   if (obj.isLiteral()) {
     objStr = "\"" + (((Literal) obj).getLexicalForm());
   } else {
     objStr =
         (((Resource) stmt.getObject()).getURI() != null)
             ? ((Resource) stmt.getObject()).getURI()
             : ((Resource) stmt.getObject()).getId().toString();
   }
   return (subjStr + " : " + predStr + " : " + objStr);
 }
 public Collection<DataPropertyStatement> getDataPropertyStatementsForIndividualByDataPropertyURI(
     Individual entity, String datapropURI) {
   Collection<DataPropertyStatement> edList = new ArrayList<DataPropertyStatement>();
   if (entity.getURI() == null) {
     return edList;
   }
   try {
     getOntModel().enterCriticalSection(Lock.READ);
     OntResource ontRes =
         (VitroVocabulary.PSEUDO_BNODE_NS.equals(entity.getNamespace()))
             ? (OntResource)
                 getOntModel()
                     .createResource(new AnonId(entity.getLocalName()))
                     .as(OntResource.class)
             : getOntModel().getOntResource(entity.getURI());
     if (ontRes == null) {
       return edList;
     }
     ClosableIterator stmtIt;
     stmtIt =
         (datapropURI != null)
             ? ontRes.listProperties(getOntModel().getProperty(datapropURI))
             : ontRes.listProperties();
     try {
       while (stmtIt.hasNext()) {
         Statement st = (Statement) stmtIt.next();
         if (st.getObject().isLiteral()) {
           DataPropertyStatement ed = new DataPropertyStatementImpl();
           Literal lit = (Literal) st.getObject();
           fillDataPropertyStatementWithJenaLiteral(ed, lit);
           ed.setIndividualURI(entity.getURI());
           ed.setIndividual(entity);
           ed.setDatapropURI(st.getPredicate().getURI());
           edList.add(ed);
         }
       }
     } finally {
       stmtIt.close();
     }
   } finally {
     getOntModel().leaveCriticalSection();
   }
   return edList;
 }
Beispiel #28
0
  @Override
  public List<Entity> getEntities(String text) {
    List<Entity> list = new ArrayList<>();
    try {
      String foxJSONOutput = doTASK(text);

      JSONParser parser = new JSONParser();
      JSONArray jsonArray = (JSONArray) parser.parse(foxJSONOutput);
      String output =
          URLDecoder.decode((String) ((JSONObject) jsonArray.get(0)).get("output"), "UTF-8");

      String baseURI = "http://dbpedia.org";
      Model model = ModelFactory.createDefaultModel();
      RDFReader r = model.getReader("N3");
      r.read(model, new StringReader(output), baseURI);

      ResIterator iter = model.listSubjects();
      while (iter.hasNext()) {
        Resource next = iter.next();
        StmtIterator statementIter = next.listProperties();
        Entity ent = new Entity();
        while (statementIter.hasNext()) {
          Statement statement = statementIter.next();
          String predicateURI = statement.getPredicate().getURI();
          if (predicateURI.equals("http://www.w3.org/2000/10/annotation-ns#body")) {
            ent.label = statement.getObject().asLiteral().getString();
          } else if (predicateURI.equals("http://ns.aksw.org/scms/means")) {
            String uri = statement.getObject().asResource().getURI();
            String encode = uri.replaceAll(",", "%2C");
            ent.URI = encode;
          } else if (predicateURI.equals("http://ns.aksw.org/scms/beginIndex")) {
            ent.start = statement.getObject().asLiteral().getInt();
          } else if (predicateURI.equals("http://ns.aksw.org/scms/endIndex")) {
            ent.end = statement.getObject().asLiteral().getInt();
          }
        }
        list.add(ent);
      }

    } catch (IOException | ParseException e) {
      log.error("Could not call FOX for NER/NED", e);
    }
    return list;
  }
  protected List<String> doDataPropertyStmt(Statement stmt) {

    if (RDFS.label.equals(stmt.getPredicate())) {
      // If the property is rdfs:labe then we need to update
      // all the individuals related by object properties. This
      // does not need to account for context nodes as that
      // is handled in AdditionalURIsForContextNodex.
      if (stmt.getSubject().isURIResource()) {
        return allIndividualsRelatedByObjectPropertyStmts(stmt.getSubject().getURI());
      } else {
        log.debug("ignored bnode");
        return Collections.emptyList();
      }
    } else {
      // This class does not need to account for context nodes because that
      // is handled in AdditionalURIsForContextNodex.
      return Collections.emptyList();
    }
  }
  protected void operateOnTriple(final Statement t) throws RepositoryException {
    final Resource subject = t.getSubject();
    final Node subjectNode = session().getNode(idTranslator().getPathFromSubject(subject));

    // if this is a user-managed RDF type assertion, update the node's
    // mixins. If it isn't, treat it as a "data" property.
    if (t.getPredicate().equals(type) && t.getObject().isResource()) {
      final Resource mixinResource = t.getObject().asResource();
      if (!isManagedMixin.apply(mixinResource)) {
        LOGGER.debug("Operating on node: {} with mixin: {}.", subjectNode, mixinResource);
        operateOnMixin(mixinResource, subjectNode);
      } else {
        LOGGER.debug("Found repository-managed mixin on which we will not operate.");
      }
    } else {
      LOGGER.debug("Operating on node: {} from triple: {}.", subjectNode, t);
      operateOnProperty(t, subjectNode);
    }
  }