private void writeNode(RDFNode node) throws IOException {
   Node n = node.asNode();
   if (n.isURI()) {
     write("      <uri>" + escape(n.getURI()) + "</uri>\n");
     return;
   }
   if (n.isBlank()) {
     write("      <id>" + escape(n.getBlankNodeId().toString()) + "</id>\n");
     return;
   }
   if (!n.isLiteral()) {
     throw new JenaException("Don't know how to serialize node " + n);
   }
   if (n.getLiteral().getDatatypeURI() != null) {
     write(
         "      <typedLiteral datatype=\""
             + escape(n.getLiteral().getDatatypeURI())
             + "\">"
             + escape(n.getLiteral().getLexicalForm())
             + "</typedLiteral>\n");
     return;
   }
   if (n.getLiteral().language() == null || "".equals(n.getLiteral().language())) {
     write("      <plainLiteral>" + escape(n.getLiteral().getLexicalForm()) + "</plainLiteral>\n");
     return;
   }
   write(
       "      <plainLiteral xml:lang=\""
           + n.getLiteral().language()
           + "\">"
           + escape(n.getLiteral().getLexicalForm())
           + "</plainLiteral>\n");
 }
    @Override
    public NodeValue exec(NodeValue v) {
      // http://www.w3.org/TR/xpath-functions/#casting
      String s = null;
      Node n = v.asNode();

      if (n.isBlank()) throw new ExprEvalException("CastXSD: Can't cast blank nodes: " + v);

      if (n.isURI()) {
        if (castType.equals(XSDDatatype.XSDstring)) s = n.getURI();
        else
          throw new ExprEvalException(
              "CastXSD: Can't cast node: " + v + " to " + castType.getURI());
      } else if (n.isLiteral())
        // What if there is a lang tag?
        s = n.getLiteralLexicalForm();
      else
        throw new ExprEvalException(
            "CastXSD: Can't cast node: " + v + "(not a literal, not URI to string)");

      if (s == null && v.isString()) s = v.getString();

      if (s == null)
        throw new ExprEvalException("CastXSD: Can't cast: " + v + "(has no string appearance)");

      //        // Special case - non-normalised xsd:booleans use 0 and 1.
      //        if ( v.isBoolean() )
      //        {
      //            if ( s.equals("0") ) s = "false" ;
      //            if ( s.equals("1") ) s = "true" ;
      //        }

      NodeValue r = cast(s, v, castType);
      return r;
    }
Beispiel #3
0
 protected static String sparqlNodeUpdate(Node node, String varName) {
   if (node.isBlank()) {
     return "_:" + node.getBlankNodeLabel().replaceAll("\\W", "");
   } else {
     return sparqlNode(node, varName);
   }
 }
  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);
  }
  /** 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 ;
  }
  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]";
  }
  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;
  }
  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);
    }
  }
Beispiel #10
0
 /**
  * Gets NXRelations node instance given Jena node.
  *
  * @param jenaNodeInst
  * @return NXRelations node instance
  */
 private Node getNXRelationsNode(com.hp.hpl.jena.graph.Node jenaNodeInst) {
   if (jenaNodeInst == null) {
     return null;
   }
   Node nuxNode = null;
   if (jenaNodeInst.isBlank()) {
     AnonId anonId = jenaNodeInst.getBlankNodeId();
     String id = anonId.getLabelString();
     nuxNode = NodeFactory.createBlank(id);
   } else if (jenaNodeInst.isLiteral()) {
     LiteralLabel label = jenaNodeInst.getLiteral();
     String value = label.getLexicalForm();
     String type = jenaNodeInst.getLiteralDatatypeURI();
     String language = jenaNodeInst.getLiteralLanguage();
     if (type != "") {
       nuxNode = NodeFactory.createTypedLiteral(value, type);
     } else if (language != "") {
       nuxNode = NodeFactory.createLiteral(value, language);
     } else {
       nuxNode = NodeFactory.createLiteral(value);
     }
   } else if (jenaNodeInst.isURI()) {
     String uri = jenaNodeInst.getURI();
     // try to find corresponding prefix
     // TODO AT: maybe take namespaces from relation service?
     for (Map.Entry<String, String> ns : namespaces.entrySet()) {
       String base = ns.getValue();
       if (uri.startsWith(base)) {
         String localName = uri.substring(base.length());
         nuxNode = NodeFactory.createQNameResource(base, localName);
         break;
       }
     }
     if (nuxNode == null) {
       // default to resource
       nuxNode = NodeFactory.createResource(uri);
     }
   } else {
     throw new IllegalArgumentException(
         "Cannot translate non concrete Jena node into NXRelations node");
   }
   return nuxNode;
 }
Beispiel #11
0
  /**
   * Map a Jena graph node to a Mulgara value.
   *
   * @param x The Jena Node to convert.
   * @param session A session to use for blank node persistence.
   * @return A Mulgara Value.
   * @throws URISyntaxException When creating a URIReference that refers to an invalid URI.
   */
  static Value n2v(Node x, Session session) throws URISyntaxException {
    if (x.isURI()) return new URIReferenceImpl(new URI(x.getURI()));

    if (x.isLiteral()) {
      // The return types are Mulgara LiteralImpl
      if (x.getLiteralDatatypeURI() != null) {
        return new LiteralImpl(x.getLiteralLexicalForm(), new URI(x.getLiteralDatatypeURI()));
      }
      if (x.getLiteralLanguage() != null) {
        return new LiteralImpl(x.getLiteralLexicalForm(), x.getLiteralLanguage());
      }
      return new LiteralImpl(x.getLiteralLexicalForm());
    }

    if (x.isBlank()) {
      // is this a previously encountered Jena-allocated node?
      Value bn = nodesToValues.get(x);
      if (bn != null) return bn;

      // May be a Mulgara-allocated bNode (and so we we have seen before)
      String blankLabel = x.getBlankNodeLabel();
      if (blankLabel.startsWith(LABEL)) {
        long id = Long.parseLong(blankLabel.substring(LABEL_LEN));
        return new BlankNodeImpl(BlankNodeImpl.counterToNode(id));
      }

      // It's not - it's a Jena one.
      if (skolemizedBlankNodes) {
        String skol = bNodeScheme + x.getBlankNodeLabel();
        return new URIReferenceImpl(new URI(skol));
      }

      // Not a Mulgara-allocated bNode.  Create a new mapping.
      BlankNodeImpl v = new BlankNodeImpl();

      nodesToValues.put(x, v);
      valuesToNodes.put(v.getNodeId(), x);
      return v;
    }

    throw new RuntimeException("Can't convert from Jena node : " + x);
  }
  /*
   * See http://www.w3.org/TR/rdf-sparql-query paragraph 11.4.3
   *
   * "(ISBLANK) Returns true if term is a blank node. Returns false otherwise."
   *
   * @see http://www.w3.org/TR/rdf-sparql-query
   */
  private void convertIsBlank(E_IsBlank expr) {
    logger.debug("convertIsBlank " + 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);
      expression.push(filter.isLimittedToBlankNodes() ? Expression.TRUE : Expression.FALSE);
    } else if (arg instanceof ConstantEx) {
      ConstantEx constant = (ConstantEx) arg;
      Node node = constant.getNode();
      expression.push(node.isBlank() ? Expression.TRUE : Expression.FALSE);
    } else {
      conversionFailed(expr);
    }
  }
Beispiel #13
0
  private ResultSetRewindable convertToStrings(ResultSetRewindable resultsActual) {
    List<Binding> bindings = new ArrayList<Binding>();
    while (resultsActual.hasNext()) {
      Binding b = resultsActual.nextBinding();
      BindingMap b2 = BindingFactory.create();

      for (String vn : resultsActual.getResultVars()) {
        Var v = Var.alloc(vn);
        Node n = b.get(v);
        String s;
        if (n == null) s = "";
        else if (n.isBlank()) s = "_:" + n.getBlankNodeLabel();
        else s = NodeFunctions.str(n);
        b2.add(v, NodeFactory.createLiteral(s));
      }
      bindings.add(b2);
    }
    ResultSet rs =
        new ResultSetStream(
            resultsActual.getResultVars(), null, new QueryIterPlainWrapper(bindings.iterator()));
    return ResultSetFactory.makeRewindable(rs);
  }
Beispiel #14
0
 protected static String sparqlNode(Node node, String varName) {
   if (node == null || node.isVariable()) {
     return varName;
   } else if (node.isBlank()) {
     return "<fake:blank>"; // or throw exception?
   } else if (node.isURI()) {
     StringBuffer uriBuff = new StringBuffer();
     return uriBuff.append("<").append(node.getURI()).append(">").toString();
   } else if (node.isLiteral()) {
     StringBuffer literalBuff = new StringBuffer();
     literalBuff.append("\"");
     pyString(literalBuff, node.getLiteralLexicalForm());
     literalBuff.append("\"");
     if (node.getLiteralDatatypeURI() != null) {
       literalBuff.append("^^<").append(node.getLiteralDatatypeURI()).append(">");
     } else if (node.getLiteralLanguage() != null && node.getLiteralLanguage().length() > 0) {
       literalBuff.append("@").append(node.getLiteralLanguage());
     }
     return literalBuff.toString();
   } else {
     return varName;
   }
 }
 public static boolean isBlank(Node node) {
   return node.isBlank();
 }