예제 #1
0
  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);
    }
  }
예제 #2
0
  private void fillMap(
      Resource s, Model model, Map<Resource, SortedSet<Statement>> resource2Statements) {

    // get all statements with subject s
    ExtendedIterator<Statement> it = model.listStatements(s, null, (RDFNode) null);

    // filter statement if necessary
    if (!dropFilters.isEmpty()) {
      Iterator<Filter<Statement>> iter = dropFilters.iterator();
      Filter<Statement> keepFilter = iter.next();
      it = it.filterKeep(keepFilter);
      while (iter.hasNext()) {
        it = it.filterKeep(iter.next());
        //				keepFilter = keepFilter.and(iter.next());
      }
      //			it = it.filterKeep(keepFilter);
    }

    SortedSet<Statement> statements = resource2Statements.get(s);
    if (statements == null) {
      statements = new TreeSet<Statement>(comparator);
      resource2Statements.put(s, statements);
    }

    while (it.hasNext()) {
      Statement st = it.next();
      statements.add(st);
      if ((st.getObject().isResource()) && !resource2Statements.containsKey(st.getObject())) {
        fillMap(st.getObject().asResource(), model, resource2Statements);
      }
    }
  }
예제 #3
0
  public List<ReMSerialisation> getReMSerialisations() throws OREException {
    try {
      List<ReMSerialisation> serialisations = new ArrayList<ReMSerialisation>();
      StmtIterator itr = res.listProperties(ORE.isDescribedBy);
      while (itr.hasNext()) {
        Statement statement = itr.nextStatement();
        Resource resource = (Resource) statement.getObject();
        StmtIterator itr2 = resource.listProperties(DC.format);
        StmtIterator itr3 = resource.listProperties(OREX.isAuthoritativeFor);
        String mime = "application/octet-stream";
        if (itr2.hasNext()) {
          Statement stmt = itr2.nextStatement();
          mime = ((Literal) stmt.getObject()).getLexicalForm();
        }
        boolean authoritative = false;
        if (itr3.hasNext()) {
          authoritative = true;
        }
        ReMSerialisation serialisation = new ReMSerialisation(mime, new URI(resource.getURI()));
        serialisation.setAuthoritative(authoritative);

        serialisations.add(serialisation);
      }
      return serialisations;
    } catch (URISyntaxException e) {
      throw new OREException(e);
    }
  }
예제 #4
0
 @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();
 }
  private String getTemplate(Individual ind, OntModel displayOntModel) {
    if (ind == null) return "defaultBody";

    // check vitroDisplay:requiresBodyTemplate
    displayOntModel.enterCriticalSection(Model.READ);
    StmtIterator it =
        displayOntModel.listStatements(
            ind, DisplayVocabulary.REQUIRES_BODY_TEMPLATE, (RDFNode) null);
    // NodeIterator it = ind.listPropertyValues(DisplayVocabulary.REQUIRES_BODY_TEMPLATE);
    try {
      while (it.hasNext()) {
        Statement stmt = it.nextStatement();
        if (stmt.getObject().isLiteral()) {
          String template = ((Literal) stmt.getObject().as(Literal.class)).getLexicalForm();
          if (template != null && template.length() > 0) {
            return template;
          }
        }
      }
    } finally {
      it.close();
      displayOntModel.leaveCriticalSection();
    }
    return "defaultBody";
  }
예제 #6
0
  @Test
  public void testChildren() throws RepositoryException {
    when(mockRes1.getPath()).thenReturn(RDF_PATH + "/res1");
    when(mockRes2.getPath()).thenReturn(RDF_PATH + "/res2");
    when(mockRes3.getPath()).thenReturn(RDF_PATH + "/res3");
    when(mockResourceNode.hasNodes()).thenReturn(true);
    final Stream<FedoraResource> first = of(mockRes1, mockRes2, mockRes3);
    final Stream<FedoraResource> second = of(mockRes1, mockRes2, mockRes3);
    when(mockResource.getChildren()).thenReturn(first).thenReturn(second);

    try (final ChildrenRdfContext context = new ChildrenRdfContext(mockResource, idTranslator)) {
      final Model results = context.collect(toModel());
      final Resource subject = idTranslator.reverse().convert(mockResource);

      final StmtIterator stmts =
          results.listStatements(subject, RdfLexicon.HAS_CHILD_COUNT, (RDFNode) null);

      assertTrue("There should have been a statement!", stmts.hasNext());
      final Statement stmt = stmts.nextStatement();
      assertTrue("Object should be a literal! " + stmt.getObject(), stmt.getObject().isLiteral());
      assertEquals(3, stmt.getInt());

      assertFalse("There should not have been a second statement!", stmts.hasNext());
    }
  }
예제 #7
0
  public Alignment buildAlignment(
      Statement stmt, AlignmentType alignmentType, ThesaurusConcept concept) {
    logger.debug("Building alignment " + stmt.getObject().toString());

    Alignment alignment = new Alignment();
    alignment.setIdentifier(generatorService.generate(Alignment.class));
    alignment.setAlignmentType(alignmentType);
    alignment.setAndRelation(false);
    alignment.setCreated(concept.getCreated());
    alignment.setModified(concept.getModified());
    alignment.setSourceConcept(concept);

    if (alignmentType.isResource()) {

      Set<AlignmentResource> targetResources = new HashSet<AlignmentResource>();
      AlignmentResource targetResource = new AlignmentResource();

      String externalTargetResource = stmt.getObject().toString();

      targetResource.setAlignment(alignment);
      targetResource.setExternalTargetResource(externalTargetResource);

      targetResources.add(targetResource);
      alignment.setTargetResources(targetResources);

    } else {

      Set<AlignmentConcept> targetConcepts = new HashSet<AlignmentConcept>();

      AlignmentConcept targetConcept = new AlignmentConcept();
      targetConcept.setAlignment(alignment);

      String targetConceptId = stmt.getObject().toString();
      ThesaurusConcept internalTargetConcept =
          thesaurusConceptService.getThesaurusConceptById(targetConceptId);
      if (internalTargetConcept != null) {
        targetConcept.setInternalTargetConcept(internalTargetConcept);
        alignment.setInternalTargetThesaurus(internalTargetConcept.getThesaurus());
      } else {
        // Check if the concept has an ark indentifier.

        Matcher arkMt = arkPt.matcher(targetConceptId);
        Matcher urlMt = urlPt.matcher(targetConceptId);

        if (arkMt.find()) {
          setExternalThesaurus(alignment, arkMt.group());
        } else if (urlMt.find()) {
          setExternalThesaurus(alignment, urlMt.group());
        }
        targetConcept.setExternalTargetConcept(targetConceptId);
      }

      targetConcepts.add(targetConcept);
      alignment.setTargetConcepts(targetConcepts);
    }
    return alignment;
  }
 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 !");
   }
 }
  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;
    }
  }
  protected List<String> doObjectPropertyStmt(Statement stmt) {
    // Only need to consider the object since the subject
    // will already be updated in search index as part of
    // SearchReindexingListener.

    // Also, context nodes are not handled here. They are
    // taken care of in AdditionalURIsForContextNodex.
    if (stmt.getObject().isURIResource())
      return Collections.singletonList(stmt.getObject().as(Resource.class).getURI());
    else return Collections.emptyList();
  }
예제 #11
0
 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();
   }
 }
예제 #12
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;
 }
 protected Set<ValueFactory> getValueFactory(RDFNode valueNode, OntModel displayOntModel) {
   // maybe use jenabean or owl2java for this?
   if (valueNode.isResource()) {
     Resource res = (Resource) valueNode.as(Resource.class);
     Statement stmt = res.getProperty(DisplayVocabulary.JAVA_CLASS_NAME);
     if (stmt == null || !stmt.getObject().isLiteral()) {
       log.debug("Cannot build value factory: java class was " + stmt.getObject());
       return Collections.emptySet();
     }
     String javaClassName = ((Literal) stmt.getObject().as(Literal.class)).getLexicalForm();
     if (javaClassName == null || javaClassName.length() == 0) {
       log.debug("Cannot build value factory: no java class was set.");
       return Collections.emptySet();
     }
     Class<?> clazz;
     Object newObj;
     try {
       clazz = Class.forName(javaClassName);
     } catch (ClassNotFoundException e) {
       log.debug("Cannot build value factory: no class found for " + javaClassName);
       return Collections.emptySet();
     }
     try {
       newObj = clazz.newInstance();
     } catch (Exception e) {
       log.debug(
           "Cannot build value factory: exception while creating object of java class "
               + javaClassName
               + " "
               + e.getMessage());
       return Collections.emptySet();
     }
     if (newObj instanceof ValueFactory) {
       ValueFactory valueFactory = (ValueFactory) newObj;
       return Collections.singleton(valueFactory);
     } else {
       log.debug(
           "Cannot build value factory: "
               + javaClassName
               + " does not implement "
               + ValueFactory.class.getName());
       return Collections.emptySet();
     }
   } else {
     log.debug("Cannot build value factory for " + valueNode);
     return Collections.emptySet();
   }
 }
 public List<DataPropertyStatement> getDataPropertyStatements(
     DataProperty dp, int startIndex, int endIndex) {
   getOntModel().enterCriticalSection(Lock.READ);
   List<DataPropertyStatement> dpss = new ArrayList<DataPropertyStatement>();
   try {
     Property prop = ResourceFactory.createProperty(dp.getURI());
     ClosableIterator dpsIt = getOntModel().listStatements(null, prop, (Literal) null);
     try {
       int count = 0;
       while ((dpsIt.hasNext()) && ((endIndex < 0) || (count < endIndex))) {
         ++count;
         Statement stmt = (Statement) dpsIt.next();
         if (startIndex < 0 || startIndex <= count) {
           Literal lit = (Literal) stmt.getObject();
           DataPropertyStatement dps = new DataPropertyStatementImpl();
           dps.setDatapropURI(dp.getURI());
           dps.setIndividualURI(stmt.getSubject().getURI());
           fillDataPropertyStatementWithJenaLiteral(dps, lit);
           dpss.add(dps);
         }
       }
     } finally {
       dpsIt.close();
     }
   } finally {
     getOntModel().leaveCriticalSection();
   }
   return dpss;
 }
예제 #15
0
 private void writeTriple(Statement stmt) throws IOException {
   write("    <triple>\n");
   writeNode(stmt.getSubject());
   writeNode(stmt.getPredicate());
   writeNode(stmt.getObject());
   write("    </triple>\n");
 }
 public ibspan.tss.um.ontology.UserBehaviourContext getHasContext() throws JastorException {
   if (hasContext != null) return hasContext;
   com.hp.hpl.jena.rdf.model.Statement stmt = _model.getProperty(_resource, hasContextProperty);
   if (stmt == null) return null;
   if (!stmt.getObject().canAs(com.hp.hpl.jena.rdf.model.Resource.class))
     throw new JastorInvalidRDFNodeException(
         uri()
             + ": hasContext getProperty() in ibspan.tss.um.ontology.ExtendedUserBehaviour model not Resource",
         stmt.getObject());
   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 =
       ibspan.tss.um.ontology.UserModellingFactory.getUserBehaviourContext(resource, _model);
   return hasContext;
 }
예제 #17
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;
  }
  @Override
  public List<String> findAdditionalURIsToIndex(Statement stmt) {
    if (stmt == null) return Collections.emptyList();

    if (stmt.getObject().isLiteral()) return doDataPropertyStmt(stmt);
    else return doObjectPropertyStmt(stmt);
  }
예제 #19
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;
  }
  Map<String, Object> getValues(
      Individual ind,
      OntModel displayOntModel,
      OntModel assertionModel,
      Map<String, Object> baseValues) {
    if (ind == null) return Collections.emptyMap();

    /* Figure out what ValueFactories are specified in the display ontology for this individual. */
    Set<ValueFactory> valueFactories = new HashSet<ValueFactory>();
    displayOntModel.enterCriticalSection(Model.READ);
    StmtIterator stmts = ind.listProperties(DisplayVocabulary.REQUIRES_VALUES);
    try {
      while (stmts.hasNext()) {
        Statement stmt = stmts.nextStatement();
        RDFNode obj = stmt.getObject();
        valueFactories.addAll(getValueFactory(obj, displayOntModel));
      }
    } finally {
      stmts.close();
      displayOntModel.leaveCriticalSection();
    }

    /* Get values from the ValueFactories. */
    HashMap<String, Object> values = new HashMap<String, Object>();
    values.putAll(baseValues);
    for (ValueFactory vf : valueFactories) {
      values.putAll(vf.getValues(assertionModel, values));
    }
    return values;
  }
 @Override
 public void remove() {
   if (stmt == null) throw new NoSuchElementException();
   ((ContainerI) seq).remove(index - numDeleted, stmt.getObject());
   stmt = null;
   numDeleted++;
 }
예제 #22
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);
  }
 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();
     }
   }
 }
예제 #24
0
  /**
   * 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));
  }
  @Override
  public void indexStatement(Statement s) {
    if (!indexThisStatement(s)) return;

    try {
      Node subject = s.getSubject().asNode();

      if (!s.getObject().isLiteral() || !LARQ.isString(s.getLiteral())) return;

      Node object = s.getObject().asNode();

      // Note: if a subject occurs twice with an indexable string,
      // there will be two hits later.
      index.index(subject, object.getLiteralLexicalForm());
    } catch (Exception e) {
      throw new ARQLuceneException("indexStatement", e);
    }
  }
예제 #26
0
 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);
 }
예제 #27
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("}");
 }
예제 #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;
  }
 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;
 }
예제 #30
0
 public void testFindObject() {
   StmtIterator iter = model.listStatements(new SimpleSelector(null, null, RDFS.Resource));
   int i = 0;
   while (iter.hasNext()) {
     i++;
     Statement stmt = iter.nextStatement();
     assertEquals(RDFS.Resource, stmt.getObject());
   }
   assertEquals(2, i);
 }