Ejemplo n.º 1
0
    @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;
    }
Ejemplo n.º 2
0
 public static void addConstantConstraint(Map<Var, NodeValue> map, Var var, NodeValue nodeValue) {
   if (map.containsKey(var)) {
     NodeValue oldValue = map.get(var);
     if (oldValue != null && !oldValue.equals(nodeValue)) {
       map.put(var, null);
     }
   } else {
     map.put(var, nodeValue);
   }
 }
Ejemplo n.º 3
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]";
  }
Ejemplo n.º 4
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);
  }
Ejemplo n.º 5
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);
  }
Ejemplo n.º 6
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);
    }
  }
Ejemplo n.º 7
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 + "'");
      }
    }
Ejemplo n.º 8
0
 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);
 }
Ejemplo n.º 9
0
 @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");
   }
 }
Ejemplo n.º 10
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);
    }
  }
Ejemplo n.º 11
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;
  }
Ejemplo n.º 12
0
  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);
  }
Ejemplo n.º 13
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);
    }
  }
Ejemplo n.º 14
0
  /*
   * See http://www.w3.org/TR/rdf-sparql-query paragraph 11.4.12
   *
   * "(LANGMATCHES) returns true if language-tag (first argument) matches language-range (second argument)
   * per the basic filtering scheme defined in [RFC4647] section 3.3.1. language-range is a basic language
   * range per Matching of Language Tags [RFC4647] section 2.1. A language-range of "*" matches any non-empty
   * language-tag string."
   *
   * @see http://www.w3.org/TR/rdf-sparql-query
   */
  private void convertLangMatches(E_LangMatches expr) {
    logger.debug("convertLangMatches " + expr.toString());

    expr.getArg1().visit(this);
    expr.getArg2().visit(this);
    Expression e2 = expression.pop();
    Expression e1 = expression.pop();

    if (e1 instanceof ConstantEx && e2 instanceof ConstantEx) {
      ConstantEx lang1 = (ConstantEx) e1;
      ConstantEx lang2 = (ConstantEx) e2;
      NodeValue nv1 = NodeValue.makeString(lang1.getNode().getLiteral().getLexicalForm());
      NodeValue nv2 = NodeValue.makeString(lang2.getNode().getLiteral().getLexicalForm());
      NodeValue match = NodeFunctions.langMatches(nv1, nv2);
      expression.push(match.equals(NodeValue.TRUE) ? Expression.TRUE : Expression.FALSE);
    } else {
      expression.push(Expression.FALSE);
    }
  }
Ejemplo n.º 15
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;
  }
Ejemplo n.º 16
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;
   }
 }
Ejemplo n.º 17
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;
  }
Ejemplo n.º 18
0
  // 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;
  }
Ejemplo n.º 19
0
 // -------- datatype
 public static NodeValue datatype(NodeValue nv) {
   return NodeValue.makeNode(datatype(nv.asNode()));
 }
Ejemplo n.º 20
0
  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;
  }
Ejemplo n.º 21
0
 public static NodeValue isURI(NodeValue nv) {
   return NodeValue.booleanReturn(isIRI(nv.asNode()));
 }
Ejemplo n.º 22
0
 public NodeValue getValue() {
   return NodeValue.makeInteger(count);
 }
Ejemplo n.º 23
0
 // -------- isBlank
 public static NodeValue isBlank(NodeValue nv) {
   return NodeValue.booleanReturn(isBlank(nv.asNode()));
 }
Ejemplo n.º 24
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);
  }
}
Ejemplo n.º 25
0
 // -------- isLiteral
 public static NodeValue isLiteral(NodeValue nv) {
   return NodeValue.booleanReturn(isLiteral(nv.asNode()));
 }
Ejemplo n.º 26
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);
 }
Ejemplo n.º 27
0
 public static NodeValue sameTerm(NodeValue nv1, NodeValue nv2) {
   return NodeValue.booleanReturn(sameTerm(nv1.asNode(), nv2.asNode()));
 }
Ejemplo n.º 28
0
  public void visit(NodeValue value) {
    logger.debug("visit NodeValue " + value);

    if (!convertable) {
      expression.push(Expression.FALSE); // prevent stack empty exceptions when conversion
      return; // fails in the middle of a multi-arg operator conversion
    }

    if (value.isDecimal()
        || value.isDouble()
        || value.isFloat()
        || value.isInteger()
        || value.isNumber()) {
      expression.push(new ConstantEx(value.asString(), value.asNode()));
    } else if (value.isDateTime()) {
      // Convert xsd:dateTime: CCYY-MM-DDThh:mm:ss
      // to SQL-92 TIMESTAMP: CCYY-MM-DD hh:mm:ss[.fraction]
      // TODO support time zones (WITH TIME ZONE columns)
      expression.push(new ConstantEx(value.asString().replace("T", " "), value.asNode()));
    } else {
      expression.push(new ConstantEx(value.asString(), value.asNode()));
    }
  }
Ejemplo n.º 29
0
 public static NodeValue rdfTermEquals(NodeValue nv1, NodeValue nv2) {
   return NodeValue.booleanReturn(rdfTermEquals(nv1.asNode(), nv2.asNode()));
 }
Ejemplo n.º 30
0
 // -------- str
 public static NodeValue str(NodeValue nv) {
   return NodeValue.makeString(str(nv.asNode()));
 }