Пример #1
0
 /** Return the lexical form of a literal node, error for other node types */
 protected String getString(Node n, RuleContext context) {
   if (n.isLiteral()) {
     return n.getLiteralLexicalForm();
   } else {
     throw new BuiltinException(this, context, getName() + " takes only literal arguments");
   }
 }
 @Test
 public void identicallyNamedNodesAreNotSameObject() {
   Node uriA = Node.createURI("http://slashdot.org/");
   Node uriB = Node.createURI("http://slashdot.org/");
   assertTrue(uriA.equals(uriB));
   assertTrue(uriA != uriB);
 }
Пример #3
0
/** @author Rowland Watkins ([email protected]) */
public class SWP_V {
  /** The namespace of the vocabulary as a string */
  public static final String NS = "http://www.w3.org/2004/03/trix/swp-verification";

  /**
   * The namespace of the vocabulary as a string
   *
   * @see #NS
   */
  public static String getURI() {
    return NS;
  }

  /** The namespace of the vocabulary as a resource */
  public static final Node NAMESPACE = Node.createURI(NS);

  public static final Node default_graph =
      Node.createURI("http://www.w3.org/2004/03/trix/swp-verification/verifiedSignatures");

  /** The object contains the status value of a signature for the subject graph. */
  public static final Node successful =
      Node.createURI("http://www.w3.org/2004/03/trix/swp-verification/successful");

  public static final Node notSuccessful =
      Node.createURI("http://www.w3.org/2004/03/trix/swp-verification/notSuccessful");
}
Пример #4
0
  /*
   * See http://www.w3.org/TR/rdf-sparql-query paragraph 11.4.4
   *
   * "(STR) Returns the lexical form of a literal; returns the codepoint representation of an IRI."
   *
   * @see http://www.w3.org/TR/rdf-sparql-query
   */
  private void convertStr(E_Str expr) {
    logger.debug("convertStr " + expr.toString());

    expr.getArg().visit(this);

    Expression arg = expression.pop();

    if (arg instanceof AttributeExprEx) {
      // make a new AttributeExprEx with changed NodeMaker, which returns plain literal
      // TODO this seems to work, but needs more testing.
      AttributeExprEx attribute = (AttributeExprEx) arg;
      TypedNodeMaker nodeMaker = (TypedNodeMaker) attribute.getNodeMaker();
      TypedNodeMaker newNodeMaker =
          new TypedNodeMaker(
              TypedNodeMaker.PLAIN_LITERAL, nodeMaker.valueMaker(), nodeMaker.isUnique());
      logger.debug("changing nodemaker " + nodeMaker + " to " + newNodeMaker);
      expression.push(
          new AttributeExprEx((Attribute) attribute.attributes().iterator().next(), newNodeMaker));
    } else if (arg instanceof ConstantEx) {
      ConstantEx constant = (ConstantEx) arg;
      Node node = constant.getNode();
      String lexicalForm = node.getLiteral().getLexicalForm();
      node = Node.createLiteral(lexicalForm);
      ConstantEx constantEx = new ConstantEx(NodeValue.makeNode(node).asString(), node);
      logger.debug("pushing " + constantEx);
      expression.push(constantEx);
    } else {
      conversionFailed(expr);
    }
  }
 @Test
 public void theEconomizerDoesntSquashOtherNodes() {
   Economizer<Node> e = new CacheEconomizer<Node>();
   Node uriA = e.economize(Node.createURI("http://slashdot.org/1"));
   Node uriB = e.economize(Node.createURI("http://slashdot.org/2"));
   assertTrue(uriA != uriB);
 }
 @Test
 public void theEconomizerChangesThat() {
   Economizer<Node> e = new CacheEconomizer<Node>();
   Node uriA = e.economize(Node.createURI("http://slashdot.org/"));
   Node uriB = e.economize(Node.createURI("http://slashdot.org/"));
   assertTrue(uriA == uriB);
 }
 @Override
 public Triple createValue() {
   System.out.println("selfdebug: create Triple value");
   Triple returnable = new Triple(Node.createAnon(), Node.createAnon(), Node.createAnon());
   System.out.println("selfdebug: Triple created");
   return returnable;
 }
Пример #8
0
  @Override
  public void newIndividual(String individualURI, String individualTypeURI, String graphURI)
      throws RDFServiceException {

    StringBuffer containsQuery = new StringBuffer("ASK { \n");
    if (graphURI != null) {
      containsQuery.append("  GRAPH <" + graphURI + "> { ");
    }
    containsQuery.append("<");
    containsQuery.append(individualURI);
    containsQuery.append("> ");
    containsQuery.append("?p ?o");
    if (graphURI != null) {
      containsQuery.append(" } \n");
    }
    containsQuery.append("\n}");

    if (sparqlAskQuery(containsQuery.toString())) {
      throw new RDFServiceException("individual already exists");
    } else {
      Triple triple =
          new Triple(
              Node.createURI(individualURI), RDF.type.asNode(), Node.createURI(individualTypeURI));
      // addTriple(triple, graphURI);
      ChangeSet cs = this.manufactureChangeSet();
      cs.addAddition(
          new ByteArrayInputStream(sparqlTriple(triple).getBytes()),
          ModelSerializationFormat.N3,
          graphURI);
      changeSetUpdate(cs);
    }
  }
Пример #9
0
 protected static String sparqlNodeUpdate(Node node, String varName) {
   if (node.isBlank()) {
     return "_:" + node.getBlankNodeLabel().replaceAll("\\W", "");
   } else {
     return sparqlNode(node, varName);
   }
 }
Пример #10
0
 private void setVars(Map<Var, Node> values, String fieldName) {
   if (values.isEmpty()) {
     return;
   }
   try {
     Field f = Query.class.getDeclaredField(fieldName);
     f.setAccessible(true);
     List<String> orig = (List<String>) f.get(query);
     List<String> lst = null;
     if (orig != null) {
       lst = new ArrayList<String>();
       for (String s : orig) {
         Node n = null;
         if (s.startsWith("?")) {
           Var v = Var.alloc(s.substring(1));
           n = values.get(v);
         }
         lst.add(n == null ? s : n.toString());
       }
       f.set(query, lst);
     }
   } catch (NoSuchFieldException e) {
     throw new IllegalStateException(e.getMessage(), e);
   } catch (SecurityException e) {
     throw new IllegalStateException(e.getMessage(), e);
   } catch (IllegalAccessException e) {
     throw new IllegalStateException(e.getMessage(), e);
   }
 }
Пример #11
0
 private Object maxOfList(Node lst, RuleContext context) {
   java.util.List<Node> l = Util.convertList(lst, context);
   Number max = null;
   XSDDateTime maxDate = null;
   for (int i = 0; l != null && i < l.size(); i++) {
     Node elt = (Node) l.get(i);
     if (elt != null && elt.isLiteral()) {
       Object v1 = elt.getLiteralValue();
       if (v1 instanceof Number) {
         if (max == null || max.doubleValue() < ((Number) v1).doubleValue()) {
           max = (Number) v1;
         }
       } else if (v1 instanceof XSDDateTime) {
         if (maxDate == null || maxDate.compareTo((XSDDateTime) v1) < 0) {
           maxDate = (XSDDateTime) v1;
         }
       } else {
         throw new BuiltinException(
             this, context, "Element of list input to max not a number: " + v1.toString());
       }
     } else {
       throw new BuiltinException(
           this, context, "Element of list input to max not a Literal: " + elt.toString());
     }
   }
   if (maxDate != null) {
     return maxDate;
   }
   return max;
 }
Пример #12
0
 @Override
 public RuleWrappedValueFunction<? extends BaseValueFunction> apply(RIFExternalExpr in) {
   Node opNode = in.getExpr().getCommand().getOp().getNode();
   throw new UnsupportedOperationException(
       String.format(
           "Cannot use the filtering predicate %s to supply a value.",
           opNode.isLiteral() ? opNode.getLiteralValue().toString() : opNode.getURI()));
 }
Пример #13
0
 @Override
 protected Node rename(Node uri) {
   if (uri.getNameSpace().equals(replaceNS))
     return Node.createURI(namespace + uri.getLocalName());
   if (uri.getURI().equals(replace))
     return Node.createURI(namespace.substring(0, namespace.length() - 1));
   return uri;
 }
Пример #14
0
  @Test
  public void testNextBinding() throws Exception {
    when(mockValue.getString()).thenReturn("x");
    final Binding binding = testObj.nextBinding();

    assertTrue(binding.contains(Var.alloc("a")));
    final Node a = binding.get(Var.alloc("a"));
    assertEquals("x", a.getLiteralLexicalForm());
  }
Пример #15
0
  public static String lang(Node node) {
    if (!node.isLiteral())
      NodeValue.raise(
          new ExprTypeException("lang: Not a literal: " + FmtUtils.stringForNode(node)));

    String s = node.getLiteralLanguage();
    if (s == null) s = "";
    return s;
  }
Пример #16
0
 private SWRLIndividualObject makeIndividalObject(final Node node) throws URISyntaxException {
   if (node.isVariable()) {
     final SWRLIndividualVariable var =
         swrlFactory.createIndividualVariable(new URI(varNS + node.getName()));
     vars.put(node.toString(), var);
     return var;
   }
   final OWLIndividual ind = owlModel.createIndividual(null, new URI(node.getURI()));
   return swrlFactory.wrapIndividual(ind);
 }
Пример #17
0
  public static String str(Node node) {
    if (node.isLiteral()) return node.getLiteral().getLexicalForm();
    if (node.isURI()) return node.getURI();
    //        if ( node.isBlank() )   return node.getBlankNodeId().getLabelString() ;
    //        if ( node.isBlank() )   return "" ;
    if (node.isBlank()) NodeValue.raise(new ExprTypeException("Blank node: " + node));

    NodeValue.raise(new ExprEvalException("Not a string: " + node));
    return "[undef]";
  }
Пример #18
0
  public static Node iri(Node nv, String baseIRI) {
    if (nv.isURI()) return nv;

    if (nv.isBlank()) {
      // Skolemization of blank nodes to IRIs : Don't ask, just don't ask.
      String x = nv.getBlankNodeLabel();
      return Node.createURI("_:" + x);
    }

    if (nv.isLiteral() && nv.getLiteralDatatype() == null && nv.getLiteralLanguage().equals("")) {
      // Plain literal
      IRI iri = null;
      String iriStr = nv.getLiteralLexicalForm();

      // Level of checking?
      if (baseIRI != null) {
        IRI base = iriFactory.create(baseIRI);
        iri = base.create(iriStr);
      } else iri = iriFactory.create(iriStr);

      if (!iri.isAbsolute()) throw new ExprEvalException("Relative IRI string: " + iriStr);
      if (warningsForIRIs && iri.hasViolation(false)) {
        String msg = "unknown violation from IRI library";
        Iterator<Violation> iter = iri.violations(false);
        if (iter.hasNext()) {
          Violation viol = iter.next();
          msg = viol.getShortMessage();
        }
        Log.warn(NodeFunctions.class, "Bad IRI: " + msg + ": " + iri);
      }
      return Node.createURI(iri.toString());
    }
    throw new ExprEvalException("Can't make an IRI from " + nv);
  }
  private static boolean matchNode(Item node, Item item, Match details) {
    if (isAny(item)) {
      details.anyMatches++;
      return true;
    }

    if (isAnyVar(item)) {
      details.varMatches++;
      return true;
    }

    if (node.isSymbol()) {
      // TERM in the thing to be matched means something concrete will be there.
      if (node.equals(TERM)) {
        if (item.equals(TERM)) {
          details.termMatches++;
          return true;
        }
        // Does not match LITERAL, URI, BNODE and VAR/ANY were done above.
        return false;
      }

      throw new ARQException("StatsMatcher: unexpected slot type: " + node);
    }

    if (!node.isNode()) return false;

    Node n = node.getNode();
    if (n.isConcrete()) {
      if (item.isNode() && item.getNode().equals(n)) {
        details.exactMatches++;
        return true;
      }

      if (isAnyTerm(item)) {
        details.termMatches++;
        return true;
      }

      if (isAnyURI(item) && n.isURI()) {
        details.termMatches++;
        return true;
      }
      if (isAnyLiteral(item) && n.isLiteral()) {
        details.termMatches++;
        return true;
      }
      if (isAnyBNode(item) && n.isBlank()) {
        details.termMatches++;
        return true;
      }
    }
    return false;
  }
Пример #20
0
 /**
  * this nodeToElement is pretty much identical to that of
  * graph.query.patternstagecompiler.compile.
  */
 private Element nodeToElement(Node X, Mapping map) {
   if (X.equals(Query.ANY)) return Element.ANY;
   if (X.isVariable()) {
     if (map.hasBound(X)) return new Bound(map.indexOf(X));
     else {
       freeVarCnt++;
       return new Free(X);
     }
   }
   return new Fixed(X);
 }
Пример #21
0
  // Replaced by getVarsMentioned
  @Deprecated
  public static Set<Node> getVariables(Iterable<Node> nodes) {
    Set<Node> result = new HashSet<Node>();
    for (Node node : nodes) {
      if (node.isVariable()) {
        result.add(node);
      }
    }

    return result;
  }
Пример #22
0
 private SWRLDataObject makeDataObject(final Node node) throws URISyntaxException {
   if (node.isVariable()) {
     final SWRLDataVariable var =
         swrlFactory.createDataVariable(new URI(varNS + node.getName()));
     vars.put(node.toString(), var);
     return var;
   }
   final OWLDataValue value =
       new OWLDataValueImpl(new LiteralImpl(node, (EnhGraph) owlModel.getImplementation()));
   return swrlFactory.wrapDataValue(value);
 }
Пример #23
0
  public static NodeValue strDatatype(NodeValue v1, NodeValue v2) {
    if (!v1.isString()) throw new ExprEvalException("Not a string (arg 1): " + v1);
    if (!v2.isIRI()) throw new ExprEvalException("Not an IRI (arg 2): " + v2);

    String lex = v1.asString();
    Node dt = v2.asNode();
    // Check?

    Node n = Node.createLiteral(lex, null, Node.getType(dt.getURI()));
    return NodeValue.makeNode(n);
  }
Пример #24
0
 @Override
 public void augmentBlock(
     TripleCollector arg0, String annotationBodyVar, String annotationHeadVar) {
   // This assumes subject indexing
   arg0.addTriple(
       Triple.create(Var.alloc(annotationBodyVar), TEXTMATCH, Node.createLiteral(searchTerm)));
 }
Пример #25
0
  /*
   * See http://www.w3.org/TR/rdf-sparql-query paragraph 11.4.7
   *
   * "(DATATYPE) Returns the datatype IRI of typedLit; returns xsd:string if the parameter is a simple literal."
   *
   * @see http://www.w3.org/TR/rdf-sparql-query
   */
  private void convertDataType(E_Datatype expr) {
    logger.debug("convertDataType " + expr.toString());

    expr.getArg().visit(this);

    Expression arg = expression.pop();

    if (arg instanceof AttributeExprEx) {
      AttributeExprEx variable = (AttributeExprEx) arg;
      NodeMaker nm = variable.getNodeMaker();
      DetermineNodeType filter = new DetermineNodeType();
      nm.describeSelf(filter);
      if (!filter.isLimittedToLiterals()) {
        // type error, return false?
        logger.warn("type error: " + variable + " is not a literal, returning FALSE");
        expression.push(Expression.FALSE);
        return;
      }
      RDFDatatype datatype = filter.getDatatype();
      logger.debug("datatype " + datatype);

      Node node =
          Node.createURI((datatype != null) ? datatype.getURI() : XSDDatatype.XSDstring.getURI());

      ConstantEx constantEx = new ConstantEx(NodeValue.makeNode(node).asString(), node);
      logger.debug("pushing " + constantEx);
      expression.push(constantEx);
    } else if (arg instanceof ConstantEx) {
      ConstantEx constant = (ConstantEx) arg;
      Node node = constant.getNode();
      if (!node.isLiteral()) {
        // type error, return false?
        logger.warn("type error: " + node + " is not a literal, returning FALSE");
        expression.push(Expression.FALSE);
        return;
      }
      RDFDatatype datatype = node.getLiteralDatatype();
      logger.debug("datatype " + datatype);
      node =
          Node.createURI((datatype != null) ? datatype.getURI() : XSDDatatype.XSDstring.getURI());
      ConstantEx constantEx = new ConstantEx(NodeValue.makeNode(node).asString(), node);
      logger.debug("pushing " + constantEx);
      expression.push(constantEx);
    } else {
      conversionFailed(expr);
    }
  }
Пример #26
0
  private Node walkTree(
      Model model,
      Dataset oldDataset,
      Node node,
      Node predicate,
      Query query,
      QuerySolution initialBinding,
      Set<Node> reached) {
    QuerySolutionMap localBinding = new QuerySolutionMap();
    localBinding.addAll(initialBinding);
    localBinding.add("arg1", model.asRDFNode(node));
    Dataset dataset = new DatasetWithDifferentDefaultModel(model, oldDataset);
    QueryExecution qexec = ARQFactory.get().createQueryExecution(query, dataset, localBinding);
    ResultSet rs = qexec.execSelect();
    try {
      if (rs.hasNext()) {
        List<String> resultVars = rs.getResultVars();
        String varName = resultVars.get(0);
        RDFNode resultNode = rs.next().get(varName);
        if (resultNode != null) {
          return resultNode.asNode();
        }
      }
    } finally {
      qexec.close();
    }

    // Recurse into parents
    ExtendedIterator<Triple> it = createIterator(model.getGraph(), node, predicate);
    try {
      while (it.hasNext()) {
        Node next = getNext(it.next());
        if ((next.isBlank() || next.isURI()) && !reached.contains(next)) {
          reached.add(next);
          Node nextResult =
              walkTree(model, oldDataset, next, predicate, query, initialBinding, reached);
          if (nextResult != null) {
            return nextResult;
          }
        }
      }
    } finally {
      it.close();
    }

    return null;
  }
  public SPDXChecksum(Model spdxModel, Node checksumNode) throws InvalidSPDXAnalysisException {
    this.model = spdxModel;
    this.checksumNode = checksumNode;
    if (checksumNode.isBlank()) {
      checksumResource = model.createResource(checksumNode.getBlankNodeId());
    } else if (checksumNode.isURI()) {
      checksumResource = model.createResource(checksumNode.getURI());
    } else {
      throw (new InvalidSPDXAnalysisException("Checksum node can not be a literal"));
    }
    // Algorithm
    Node p =
        spdxModel
            .getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CHECKSUM_ALGORITHM)
            .asNode();
    Triple m = Triple.createMatch(checksumNode, p, null);
    ExtendedIterator<Triple> tripleIter = spdxModel.getGraph().find(m);
    while (tripleIter.hasNext()) {
      Triple t = tripleIter.next();
      if (t.getObject().isLiteral()) {
        // The following is for compatibility with rdf generated with older
        // versions of the tool
        this.algorithm = t.getObject().toString(false);
      } else if (t.getObject().isURI()) {
        this.algorithm = URI_TO_ALGORITHM.get(t.getObject().getURI());
        if (this.algorithm == null) {
          this.algorithm = "UNKNOWN";
        }
      } else {
        throw (new InvalidSPDXAnalysisException(
            "Invalid checksum algorithm - must be one of the defined algorithms supported by SPDX."));
      }
    }

    // value
    p =
        spdxModel
            .getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CHECKSUM_VALUE)
            .asNode();
    m = Triple.createMatch(checksumNode, p, null);
    tripleIter = spdxModel.getGraph().find(m);
    while (tripleIter.hasNext()) {
      Triple t = tripleIter.next();
      this.value = t.getObject().toString(false);
    }
  }
Пример #28
0
 /** Convert a Node into an instance of the class */
 public EnhNode wrap(Node n, EnhGraph eg) {
   if (canWrap(n, eg)) {
     return new Thing(n, eg);
   } else {
     log.warn("Cannot convert node " + n.toString() + " to  Thing");
     return null;
   }
 }
Пример #29
0
 protected Object extractBinding(Map<String, Node> binds, int nodeIndex) {
   Node node = this.nodes[nodeIndex];
   if (node.isVariable()) {
     Node boundNode = binds.get(this.nodes[nodeIndex].getName());
     if (boundNode == null) {
       throw new UnsupportedOperationException("Unbound variable");
     }
     node = boundNode;
   }
   if (node.isConcrete()) {
     Node_Concrete lit = (Node_Concrete) node;
     if (lit.isLiteral()) return lit.getLiteralValue();
     else if (lit.isURI()) return lit.getURI();
     else if (lit.isBlank()) return lit.getBlankNodeLabel();
   }
   throw new UnsupportedOperationException("Incorrect node type for comparison: " + node);
 }
Пример #30
0
  /** Encoding of a node so it can be reconstructed */
  public static String serialize(Node n, String base, PrefixMap prefixMap) {
    // See also Nodec.
    // See also OutputLangUtils - merge and this is a buffering call.

    if (n == null) return "<<null>>";

    if (n.isBlank()) {
      String str = n.getBlankNodeLabel();
      // c.f. OutputLangUtils
      if (onlySafeBNodeLabels) str = safeBNodeLabel(str);
      return "_:" + str;
    }

    if (n.isLiteral()) return FmtUtils.stringForLiteral((Node_Literal) n, null);

    if (n.isURI()) {
      String uri = n.getURI();
      return stringForURI(uri, base, prefixMap);
    }

    // Safe name?
    if (n.isVariable()) return "?" + n.getName();
    //
    //        if ( n.equals(Node.ANY) )
    //            return "ANY" ;

    throw new TDBException("Failed to turn a node into a string: " + n);
    // return null ;
  }