Esempio n. 1
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);
    }
  }
 protected NodeValue cast(String s, NodeValue nv, XSDDatatype castType2) {
   // Plain cast.
   if (!castType.isValid(s))
     throw new ExprEvalException("CastXSD: Not a valid literal form: " + s);
   // Unfortunately, validity testing happens in NodeValue.makeNode as well.
   return NodeValue.makeNode(s, castType);
 }
Esempio n. 3
0
    protected NodeValue cast(String s, NodeValue nv, XSDDatatype castType2) {
      if (whitespaceSurroundAllowed)
        // Maybe more convenient, but is not strictly correct.
        s = s.trim();
      else {
        // Correct mode.  No white space allowed around values types numeric, boolean, dateTime, ...
        // See also "JenaParameters.enableWhitespaceCheckingOfTypedLiterals" which defaults to false
        // (accept surrounding whitespace)
        // This CastXSD - not need to check it is an XSD datatype.
        // if ( castType.getURI().startsWith(XSDDatatype.XSD) &&

        if (castType instanceof XSDBaseNumericType
            || castType.equals(XSDDatatype.XSDfloat)
            || castType.equals(XSDDatatype.XSDdouble)
            || castType.equals(XSDDatatype.XSDboolean)
            || castType instanceof XSDAbstractDateTimeType) // Includes durations, and Gregorian
        {
          if (s.startsWith(" ") || s.endsWith(" "))
            throw new ExprEvalException(
                "CastXSD: Not a valid literal form (has whitespace): '" + s + "'");
        }
      }

      // Plain cast.
      try {
        if (!castType.isValid(s))
          throw new ExprEvalException("CastXSD: Not a valid literal form: '" + s + "'");
        // Unfortunately, validity testing happens in NodeValue.makeNode as well.
        // but better error messages this way.
        return NodeValue.makeNode(s, castType);
      } catch (RuntimeException ex) {
        throw new ExprEvalException("CastXSD: Not a strictly valid literal form: '" + s + "'");
      }
    }
 @Override
 protected NodeValue exec(Node[] nodes, FunctionEnv env) {
   Node startNode = nodes[0];
   Node predicate = nodes[1];
   Node function = nodes[2];
   Model model = ModelFactory.createModelForGraph(env.getActiveGraph());
   QuerySolutionMap initialBinding = new QuerySolutionMap();
   StringBuffer expression = new StringBuffer("<" + function + ">(?arg1");
   for (int i = 3; i < nodes.length; i++) {
     expression.append(", ");
     expression.append("?");
     String varName = "arg" + (i - 1);
     expression.append(varName);
     if (nodes[i] != null) {
       initialBinding.add(varName, model.asRDFNode(nodes[i]));
     }
   }
   expression.append(")");
   Query query = ARQFactory.get().createExpressionQuery(expression.toString());
   Node result =
       walkTree(
           model,
           DatasetImpl.wrap(env.getDataset()),
           startNode,
           predicate,
           query,
           initialBinding,
           new HashSet<Node>());
   if (result != null) {
     return NodeValue.makeNode(result);
   } else {
     throw new ExprEvalException("No result");
   }
 }
Esempio n. 5
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);
    }
  }
Esempio n. 6
0
  /*
   * See http://www.w3.org/TR/rdf-sparql-query paragraph 11.4.6
   *
   * "(LANG) Returns the language tag of ltrl, if it has one. It returns "" if ltrl has no language tag."
   * @see http://www.w3.org/TR/rdf-sparql-query
   */
  private void convertLang(E_Lang expr) {
    logger.debug("convertLang " + 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);
      String lang = filter.getLanguage();
      logger.debug("lang " + lang);
      if (lang == null) lang = "";

      // NodeValue.makeString(lang); TODO better?
      Node node = Node.createLiteral(lang);

      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;
      }
      String lang = node.getLiteralLanguage();
      logger.debug("lang " + lang);
      if (lang == null) lang = "";

      node = Node.createLiteral(lang);

      ConstantEx constantEx = new ConstantEx(NodeValue.makeNode(node).asString(), node);
      logger.debug("pushing " + constantEx);
      expression.push(constantEx);
    } else {
      conversionFailed(expr);
    }
  }
Esempio n. 7
0
  public static NodeValue strLang(NodeValue v1, NodeValue v2) {
    if (!v1.isString()) throw new ExprEvalException("Not a string (arg 1): " + v1);
    if (!v2.isString()) throw new ExprEvalException("Not a string (arg 2): " + v2);

    String lex = v1.asString();
    String lang = v2.asString();
    // Check?

    Node n = Node.createLiteral(lex, lang, null);
    return NodeValue.makeNode(n);
  }
Esempio n. 8
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);
  }
Esempio n. 9
0
 /* (non-Javadoc)
  * @see com.hp.hpl.jena.sparql.function.FunctionBase2#exec(com.hp.hpl.jena.sparql.expr.NodeValue, com.hp.hpl.jena.sparql.expr.NodeValue)
  */
 @Override
 public NodeValue exec(NodeValue uri, NodeValue pattern) {
   if (uri.asNode().isVariable()) {
     return uri;
   }
   // Simulate the identity
   Node nuri = uri.asNode();
   String result = null;
   String regexPattern = pattern.asUnquotedString();
   try {
     result = getSameAs(nuri.getURI(), regexPattern);
     if (result == null) {
       Logger.getAnonymousLogger().log(Level.INFO, "No results found for uri:" + nuri);
       return NodeValue.makeNode(nuri);
     } else {
       return NodeValue.makeNode(Node.createURI(result));
     }
   } catch (Exception e) {
     return uri;
   }
 }
Esempio n. 10
0
  /**
   * Delivers the corresponding sql-expression for a sparql-var
   *
   * @param exprVar - a sparql-expr-var
   * @return List<Expression> - the equivalent sql-expressions
   */
  private List<Expression> toExpression(ExprVar exprVar) {
    ArrayList<Expression> result = new ArrayList<Expression>();

    if (this.nodeRelation != null && exprVar != null) {
      // get the nodemaker for the expr-var
      NodeMaker nodeMaker = nodeRelation.nodeMaker(exprVar.asVar());
      if (nodeMaker instanceof TypedNodeMaker) {
        TypedNodeMaker typedNodeMaker = (TypedNodeMaker) nodeMaker;
        Iterator<ProjectionSpec> it = typedNodeMaker.projectionSpecs().iterator();
        if (!it.hasNext()) {
          logger.debug("no projection spec for " + exprVar + ", assuming constant");
          Node node = typedNodeMaker.makeNode(null);
          result.add(new ConstantEx(NodeValue.makeNode(node).asString(), node));
        }
        while (it.hasNext()) {
          ProjectionSpec projectionSpec = it.next();

          if (projectionSpec == null) return Collections.emptyList();

          if (projectionSpec instanceof Attribute) {
            result.add(new AttributeExprEx((Attribute) projectionSpec, nodeMaker));
          } else {
            // projectionSpec is a ExpressionProjectionSpec
            ExpressionProjectionSpec expressionProjectionSpec =
                (ExpressionProjectionSpec) projectionSpec;
            Expression expression = expressionProjectionSpec.toExpression();
            if (expression instanceof SQLExpression) result.add(((SQLExpression) expression));
            else return Collections.emptyList();
          }
        }
      } else if (nodeMaker instanceof FixedNodeMaker) {
        FixedNodeMaker fixedNodeMaker = (FixedNodeMaker) nodeMaker;
        Node node = fixedNodeMaker.makeNode(null);
        result.add(new ConstantEx(NodeValue.makeNode(node).asString(), node));
      }
    }

    return result;
  }
Esempio n. 11
0
  @Override
  public NodeValue exec(NodeValue v) {
    if (!v.isString()) {
      ALog.warn(this, "date: argument not a string: " + v);
      throw new ExprEvalException("date: argument not a string: " + v);
    }

    String lexicalForm = v.getString();

    // Quite picky about format
    if (!lexicalForm.matches("\\d{4}-\\d{2}-\\d{2}")) {
      ALog.warn(this, "date: argument not in date format: " + v);
      throw new ExprEvalException("date: argument not in date format: " + v);
    }

    lexicalForm = lexicalForm + "T00:00:00Z";

    NodeValue nv = NodeValue.makeNode(lexicalForm, XSDDatatype.XSDdateTime);
    return nv;
  }
Esempio n. 12
0
 // -------- datatype
 public static NodeValue datatype(NodeValue nv) {
   return NodeValue.makeNode(datatype(nv.asNode()));
 }
Esempio n. 13
0
 // -------- IRI
 public static NodeValue iri(NodeValue nv, String baseIRI) {
   if (isIRI(nv.asNode())) return nv;
   Node n2 = iri(nv.asNode(), baseIRI);
   return NodeValue.makeNode(n2);
 }
Esempio n. 14
0
/** Implementation of node-centric functions. */
public class NodeFunctions {
  private static final NodeValue xsdString = NodeValue.makeNode(XSD.xstring.asNode());

  // -------- sameTerm

  public static NodeValue sameTerm(NodeValue nv1, NodeValue nv2) {
    return NodeValue.booleanReturn(sameTerm(nv1.asNode(), nv2.asNode()));
  }

  public static boolean sameTerm(Node n1, Node n2) {
    if (n1.equals(n2)) return true;
    if (n1.isLiteral() && n2.isLiteral()) {
      // But language tags are case insensitive.
      String lang1 = n1.getLiteralLanguage();
      String lang2 = n2.getLiteralLanguage();

      if (!lang1.equals("") && lang1.equalsIgnoreCase(lang2)) {
        // Two language tags, equal by case insensitivity.
        boolean b = n1.getLiteralLexicalForm().equals(n2.getLiteralLexicalForm());
        if (b) return true;
      }
    }
    return false;
  }

  // -------- RDFterm-equals

  public static NodeValue rdfTermEquals(NodeValue nv1, NodeValue nv2) {
    return NodeValue.booleanReturn(rdfTermEquals(nv1.asNode(), nv2.asNode()));
  }

  // Exact as defined by SPARQL spec.
  public static boolean rdfTermEquals(Node n1, Node n2) {
    if (n1.equals(n2)) return true;

    if (n1.isLiteral() && n2.isLiteral()) {
      // Two literals, may be sameTerm by language tag case insensitivity.
      String lang1 = n1.getLiteralLanguage();
      String lang2 = n2.getLiteralLanguage();

      if (!lang1.equals("") && lang1.equalsIgnoreCase(lang2)) {
        // Two language tags, equal by case insensitivity.
        boolean b = n1.getLiteralLexicalForm().equals(n2.getLiteralLexicalForm());
        if (b) return true;
      }
      // Two literals, different terms, different language tags.
      NodeValue.raise(new ExprEvalException("Mismatch in RDFterm-equals: " + n1 + ", " + n2));
    }
    // One or both not a literal.
    return false;
  }

  // -------- str
  public static NodeValue str(NodeValue nv) {
    return NodeValue.makeString(str(nv.asNode()));
  }

  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]";
  }

  // -------- datatype
  public static NodeValue datatype(NodeValue nv) {
    return NodeValue.makeNode(datatype(nv.asNode()));
  }

  public static Node datatype(Node node) {
    if (!node.isLiteral()) {
      NodeValue.raise(new ExprTypeException("datatype: Not a literal: " + node));
      return null;
    }

    String s = node.getLiteralDatatypeURI();
    boolean plainLiteral = (s == null || s.equals(""));

    if (plainLiteral) {
      boolean simpleLiteral =
          (node.getLiteralLanguage() == null || node.getLiteralLanguage().equals(""));
      if (!simpleLiteral)
        NodeValue.raise(new ExprTypeException("datatype: Literal has language tag: " + node));
      return XSD.xstring.asNode();
    }
    return Node.createURI(s);
  }

  // -------- lang

  public static NodeValue lang(NodeValue nv) {
    return NodeValue.makeString(lang(nv.asNode()));
  }

  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;
  }

  // -------- langMatches
  public static NodeValue langMatches(NodeValue nv, NodeValue nvPattern) {
    return langMatches(nv, nvPattern.getString());
  }

  public static NodeValue langMatches(NodeValue nv, String langPattern) {
    Node node = nv.asNode();
    if (!node.isLiteral()) {
      NodeValue.raise(new ExprTypeException("langMatches: not a literal: " + node));
      return null;
    }

    String nodeLang = node.getLiteralLexicalForm();

    if (langPattern.equals("*")) {
      if (nodeLang == null || nodeLang.equals("")) return NodeValue.FALSE;
      return NodeValue.TRUE;
    }

    // See RFC 3066 (it's "tag (-tag)*)"

    String[] langElts = nodeLang.split("-");
    String[] langRangeElts = langPattern.split("-");

    /*
     * Here is the logic to compare language code.
     * There is a match if the language matches the
     * parts of the pattern - the language may be longer than
     * the pattern.
     */

    /* RFC 4647 basic filtering.
     *
     * To do extended:
     * 1. Remove any -*- (but not *-)
     * 2. Compare primary tags.
     * 3. Is the remaining range a subsequence of the remaining language tag?
     */

    //        // Step one: remove "-*-" (but not "*-")
    //        int j = 1 ;
    //        for ( int i = 1 ; i < langRangeElts.length ; i++ )
    //        {
    //            String range = langRangeElts[i] ;
    //            if ( range.equals("*") )
    //                continue ;
    //            langRangeElts[j] = range ;
    //            j++ ;
    //        }
    //
    //        // Null fill any free space.
    //        for ( int i = j ; i < langRangeElts.length ; i++ )
    //            langRangeElts[i] = null ;

    // This is basic specific.

    if (langRangeElts.length > langElts.length)
      // Lang tag longer than pattern tag => can't match
      return NodeValue.FALSE;
    for (int i = 0; i < langRangeElts.length; i++) {
      String range = langRangeElts[i];
      if (range == null) break;
      // Language longer than range
      if (i >= langElts.length) break;
      String lang = langElts[i];
      if (range.equals("*")) continue;
      if (!range.equalsIgnoreCase(lang)) return NodeValue.FALSE;
    }
    return NodeValue.TRUE;
  }

  // -------- isURI/isIRI

  public static NodeValue isIRI(NodeValue nv) {
    return NodeValue.booleanReturn(isIRI(nv.asNode()));
  }

  public static boolean isIRI(Node node) {
    if (node.isURI()) return true;
    return false;
  }

  public static NodeValue isURI(NodeValue nv) {
    return NodeValue.booleanReturn(isIRI(nv.asNode()));
  }

  public static boolean isURI(Node node) {
    return isIRI(node);
  }

  // -------- isBlank
  public static NodeValue isBlank(NodeValue nv) {
    return NodeValue.booleanReturn(isBlank(nv.asNode()));
  }

  public static boolean isBlank(Node node) {
    return node.isBlank();
  }

  // -------- isLiteral
  public static NodeValue isLiteral(NodeValue nv) {
    return NodeValue.booleanReturn(isLiteral(nv.asNode()));
  }

  public static boolean isLiteral(Node node) {
    return node.isLiteral();
  }

  private static final IRIFactory iriFactory = IRIFactory.iriImplementation();
  public static boolean warningsForIRIs = false;

  // -------- IRI
  public static NodeValue iri(NodeValue nv, String baseIRI) {
    if (isIRI(nv.asNode())) return nv;
    Node n2 = iri(nv.asNode(), baseIRI);
    return NodeValue.makeNode(n2);
  }

  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);
  }

  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);
  }

  public static NodeValue strLang(NodeValue v1, NodeValue v2) {
    if (!v1.isString()) throw new ExprEvalException("Not a string (arg 1): " + v1);
    if (!v2.isString()) throw new ExprEvalException("Not a string (arg 2): " + v2);

    String lex = v1.asString();
    String lang = v2.asString();
    // Check?

    Node n = Node.createLiteral(lex, lang, null);
    return NodeValue.makeNode(n);
  }
}