コード例 #1
0
 /**
  * This method is invoked when the builtin is called in a rule body.
  *
  * @param args the array of argument values for the builtin, this is an array of Nodes, some of
  *     which may be Node_RuleVariables.
  * @param length the length of the argument list, may be less than the length of the args array
  *     for some rule engines
  * @param context an execution context giving access to other relevant data
  * @return return true if the buildin predicate is deemed to have succeeded in the current
  *     environment
  */
 public boolean bodyCall(Node[] args, int length, RuleContext context) {
   checkArgs(length, context);
   BindingEnvironment env = context.getEnv();
   Node n1 = getArg(0, args, context);
   Node n2 = getArg(1, args, context);
   if (n1.isLiteral() && n2.isLiteral()) {
     Object v1 = n1.getLiteralValue();
     Object v2 = n2.getLiteralValue();
     Node sum = null;
     if (v1 instanceof Number && v2 instanceof Number) {
       Number nv1 = (Number) v1;
       Number nv2 = (Number) v2;
       if (v1 instanceof Float
           || v1 instanceof Double
           || v2 instanceof Float
           || v2 instanceof Double) {
         sum = Util.makeDoubleNode(nv1.doubleValue() - nv2.doubleValue());
       } else {
         sum = Util.makeLongNode(nv1.longValue() - nv2.longValue());
       }
       return env.bind(args[2], sum);
     }
   }
   // Doesn't (yet) handle partially bound cases
   return false;
 }
コード例 #2
0
  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;
  }
コード例 #3
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;
    }
コード例 #4
0
ファイル: Regex.java プロジェクト: jljohnson/lyo.dependencies
 /** 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");
   }
 }
コード例 #5
0
ファイル: Max.java プロジェクト: brfeddersen/sadlos2
 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;
 }
コード例 #6
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 ;
  }
コード例 #7
0
 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");
 }
コード例 #8
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);
  }
コード例 #9
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()));
 }
コード例 #10
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;
  }
コード例 #11
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]";
  }
コード例 #12
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;
  }
コード例 #13
0
  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;
  }
コード例 #14
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);
    }
  }
コード例 #15
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);
  }
コード例 #16
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);
    }
  }
コード例 #17
0
ファイル: JenaGraph.java プロジェクト: GlearDev/nuxeo
 /**
  * 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;
 }
コード例 #18
0
ファイル: Jenara.java プロジェクト: anukat2015/mulgara
  /**
   * 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);
  }
コード例 #19
0
ファイル: RDFServiceImpl.java プロジェクト: drspeedo/Vitro
 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;
   }
 }
コード例 #20
0
  /*
   * See http://www.w3.org/TR/rdf-sparql-query paragraph 11.4.4
   *
   * "(ISLITERAL) Returns true if term is a literal. Returns false otherwise."
   *
   * @see http://www.w3.org/TR/rdf-sparql-query
   */
  private void convertIsLiteral(E_IsLiteral expr) {
    logger.debug("convertIsLiteral " + expr.toString());

    expr.getArg().visit(this);

    Expression arg = expression.pop();

    logger.debug("arg " + arg);

    if (arg instanceof AttributeExprEx) {
      AttributeExprEx variable = (AttributeExprEx) arg;
      NodeMaker nm = variable.getNodeMaker();

      DetermineNodeType filter = new DetermineNodeType();
      nm.describeSelf(filter);
      expression.push(filter.isLimittedToLiterals() ? Expression.TRUE : Expression.FALSE);
    } else if (arg instanceof ConstantEx) {
      ConstantEx constant = (ConstantEx) arg;
      Node node = constant.getNode();
      expression.push(node.isLiteral() ? Expression.TRUE : Expression.FALSE);
    } else {
      conversionFailed(expr);
    }
  }
コード例 #21
0
  /**
   * Builds up statements like [] rr:template "http://data.example.com/department/{DEPTNO}" or []
   * rr:class ex:Department and returns them as a Statement List.
   *
   * @param r2rml the target com.hp.hpl.jena.rdf.model.Model
   * @param mappingData the target that should be mapped to relational structures (subject,
   *     predicate or object)
   * @param varDefs the construction definition of the target value based in the actual database
   *     value and some additional data like prefix strings or certain functions like uri( ... )
   * @return a List<Statement> containing all the subject map statements
   */
  private List<Statement> buildMapStatements(Model r2rml, Node mappingData, VarDefinition varDefs) {

    List<Statement> results = new ArrayList<Statement>();

    // a blank node []
    Resource mapSubject = ResourceFactory.createResource();
    // rr:template or rr:column or rr:constant
    Property mapPredicate;
    // a literal like "http://data.example.com/department/{DEPTNO}" or
    // simply "DEPTNO" (column name) or a constant "Foo bar!!"
    // (or in rare cases a URI, which is handled separately)
    Literal mapObject;

    // template or column or constant
    if (mappingData.isVariable()) {
      Collection<RestrictedExpr> restrictions = varDefs.getDefinitions((Var) mappingData);
      List<PredicateAndObject> mapPredicateAndObjects = processRestrictions(restrictions);

      for (PredicateAndObject result : mapPredicateAndObjects) {

        mapPredicate = result.getPrediacte();
        Statement resultStatement;
        RDFNode rawObject = result.getRawObject();

        // object is literal
        if (rawObject.isLiteral()) {
          mapObject = rawObject.asLiteral();
          resultStatement = r2rml.createStatement(mapSubject, mapPredicate, mapObject);

          // object is blank node
        } else if (rawObject.isAnon()) {
          Resource mapResObject = rawObject.asResource();
          resultStatement = r2rml.createStatement(mapSubject, mapPredicate, mapResObject);

          // object is resource
        } else {
          Resource mapResObject = rawObject.asResource();
          resultStatement = r2rml.createStatement(mapSubject, mapPredicate, mapResObject);
        }

        results.add(resultStatement);
      }

      // everything that is not a variable is handled as a constant
    } else if (mappingData.isConcrete()) {
      // URIs and Literals have to be handled separately since the methods
      // to retrieve the respective value are different

      Statement resultStatement;

      // URI
      if (mappingData.isURI()) {
        /*
         * This case is somewhat special since the mapObject is not a
         * Literal. So, this needs some special handling:
         * - the Literal mapObject will not be used
         * - a special mapObject_uri Resource will be created
         * - the result will be created, appended to the List and
         *   returned to not go through any further ordinary processing
         */

        Resource mapObject_uri = ResourceFactory.createResource(mappingData.getURI());
        mapPredicate = ResourceFactory.createProperty(rrNamespace, "constant");

        resultStatement = r2rml.createStatement(mapSubject, mapPredicate, mapObject_uri);
        results.add(resultStatement);

        return results;

        // Literal
      } else if (mappingData.isLiteral()) {

        mapObject = ResourceFactory.createPlainLiteral(mappingData.getLiteral().toString(false));

        // else (e.g. blank node)
      } else { // mapSubject.isBlank() == true
        /*
         * Hmm... I think this violates the standard. So lean back and
         *  enjoy the trace...
         */

        mapObject = null;
      }

      mapPredicate = ResourceFactory.createProperty(rrPrefix, "constant");

      resultStatement = r2rml.createStatement(mapSubject, mapPredicate, mapObject);
      results.add(resultStatement);
    }

    return results;
  }
コード例 #22
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;
  }
コード例 #23
0
  /*
   * See http://www.w3.org/TR/rdf-sparql-query paragraph 11.4.11
   *
   * "(SAMETERM) Returns TRUE if term1 and term2 are the same RDF term as defined
   * in Resource Description Framework (RDF): Concepts and Abstract Syntax [CONCEPTS]; returns FALSE otherwise."
   *
   * @see http://www.w3.org/TR/rdf-sparql-query
   * @see http://www.w3.org/TR/rdf-concepts/
   */
  private void convertSameTerm(E_SameTerm expr) {
    logger.debug("convertSameTerm " + expr.toString());

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

    // TODO Expression.FALSE and Expression.TRUE are not constants
    if (e1.equals(Expression.FALSE)) e1 = CONSTANT_FALSE;
    else if (e1.equals(Expression.TRUE)) e1 = CONSTANT_TRUE;
    if (e2.equals(Expression.FALSE)) e2 = CONSTANT_FALSE;
    else if (e2.equals(Expression.TRUE)) e2 = CONSTANT_TRUE;

    if (e1 instanceof AttributeExprEx && e2 instanceof Constant
        || e2 instanceof AttributeExprEx && e1 instanceof Constant) {

      AttributeExprEx variable;
      ConstantEx constant;

      if (e1 instanceof AttributeExprEx) {
        variable = (AttributeExprEx) e1;
        constant = (ConstantEx) e2;
      } else {
        variable = (AttributeExprEx) e2;
        constant = (ConstantEx) e1;
      }

      logger.debug("isEqual(" + variable + ", " + constant + ")");

      NodeMaker nm = variable.getNodeMaker();

      if (nm instanceof TypedNodeMaker) {
        ValueMaker vm = ((TypedNodeMaker) nm).valueMaker();
        Node node = constant.getNode();
        logger.debug("checking " + node + " with " + nm);

        boolean empty = nm.selectNode(node, RelationalOperators.DUMMY).equals(NodeMaker.EMPTY);
        logger.debug("result " + new Boolean(empty));
        if (!empty) {
          if (node.isURI()) expression.push(vm.valueExpression(node.getURI()));
          else if (node.isLiteral()) expression.push(vm.valueExpression(constant.value()));
          else conversionFailed(expr); // TODO blank nodes?
          return;
        } else {
          expression.push(Expression.FALSE);
          return;
        }
      } else {
        logger.warn("nm is not a TypedNodemaker");
      }
    } else if (e1 instanceof ConstantEx && e2 instanceof ConstantEx) {
      logger.debug("isEqual(" + e1 + ", " + e2 + ")");
      ConstantEx constant1 = (ConstantEx) e1;
      ConstantEx constant2 = (ConstantEx) e2;
      boolean equals = NodeFunctions.sameTerm(constant1.getNode(), constant2.getNode());
      logger.debug("constants same? " + new Boolean(equals));
      expression.push(equals ? Expression.TRUE : Expression.FALSE);
      return;
    } else if (e1 instanceof AttributeExprEx && e2 instanceof AttributeExprEx) {
      logger.debug("isEqual(" + e1 + ", " + e2 + ")");
      AttributeExprEx variable1 = (AttributeExprEx) e1;
      AttributeExprEx variable2 = (AttributeExprEx) e2;

      NodeMaker nm1 = variable1.getNodeMaker();
      NodeMaker nm2 = variable2.getNodeMaker();

      NodeSetConstraintBuilder nodeSet = new NodeSetConstraintBuilder();
      nm1.describeSelf(nodeSet);
      nm2.describeSelf(nodeSet);

      if (nodeSet.isEmpty()) {
        logger.debug("nodes " + nm1 + " " + nm2 + " incompatible");
        expression.push(Expression.FALSE);
        return;
      }
    }

    expression.push(Equality.create(e1, e2));
  }
コード例 #24
0
 public static boolean isLiteral(Node node) {
   return node.isLiteral();
 }
コード例 #25
0
 public boolean canWrap(Node n, EnhGraph eg) {
   return n.isLiteral();
 }
コード例 #26
0
  private void convertNotEquals(E_NotEquals expr) {
    logger.debug("convertNotEquals " + expr.toString());

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

    // TODO Expression.FALSE and Expression.TRUE are not constants
    if (e1.equals(Expression.FALSE)) e1 = CONSTANT_FALSE;
    else if (e1.equals(Expression.TRUE)) e1 = CONSTANT_TRUE;
    if (e2.equals(Expression.FALSE)) e2 = CONSTANT_FALSE;
    else if (e2.equals(Expression.TRUE)) e2 = CONSTANT_TRUE;

    if (e1 instanceof AttributeExprEx && e2 instanceof Constant
        || e2 instanceof AttributeExprEx && e1 instanceof Constant) {
      AttributeExprEx variable;
      ConstantEx constant;

      if (e1 instanceof AttributeExprEx) {
        variable = (AttributeExprEx) e1;
        constant = (ConstantEx) e2;
      } else {
        variable = (AttributeExprEx) e2;
        constant = (ConstantEx) e1;
      }

      logger.debug("isNotEqual(" + variable + ", " + constant + ")");

      NodeMaker nm = variable.getNodeMaker();

      if (nm instanceof TypedNodeMaker) {
        ValueMaker vm = ((TypedNodeMaker) nm).valueMaker();
        Node node = constant.getNode();
        logger.debug("checking " + node + " with " + nm);
        if (XSD.isNumeric(node)) {
          DetermineNodeType filter = new DetermineNodeType();
          nm.describeSelf(filter);
          RDFDatatype datatype = filter.getDatatype();
          if (datatype != null && XSD.isNumeric(datatype)) {
            RDFDatatype numericType = XSD.getNumericType(datatype, node.getLiteralDatatype());
            nm = cast(nm, numericType);
            node = XSD.cast(node, numericType);
          }
        }
        boolean empty = nm.selectNode(node, RelationalOperators.DUMMY).equals(NodeMaker.EMPTY);
        logger.debug("result " + new Boolean(empty));
        if (!empty) {
          if (node.isURI()) expression.push(new Negation(vm.valueExpression(node.getURI())));
          else if (node.isLiteral()) {
            if (XSD.isSupported(node.getLiteralDatatype()))
              expression.push(new Negation(vm.valueExpression(constant.value())));
            else // type = boolean or an unknown type
            conversionFailed("cannot compare values of type " + node.getLiteralDatatypeURI(), expr);
          } else conversionFailed(expr); // TODO blank nodes?
          return;
        } else {
          expression.push(Expression.TRUE);
          return;
        }
      }
    } else if (e1 instanceof ConstantEx && e2 instanceof ConstantEx) {
      logger.debug("isNotEqual(" + e1 + ", " + e2 + ")");
      Node c1 = ((ConstantEx) e1).getNode();
      Node c2 = ((ConstantEx) e2).getNode();
      boolean equals;
      if (XSD.isNumeric(c1) && XSD.isNumeric(c2)) {
        RDFDatatype datatype = XSD.getNumericType(c1.getLiteralDatatype(), c2.getLiteralDatatype());
        equals = XSD.cast(c1, datatype).equals(XSD.cast(c2, datatype));
      } else if (isSimpleLiteral(c1) && isSimpleLiteral(c2)) {
        equals = c1.getLiteralValue().equals(c2.getLiteralValue());
      } else if (XSD.isString(c1) && XSD.isString(c2)) {
        equals = c1.getLiteralValue().equals(c2.getLiteralValue());
      } else {
        try {
          equals = NodeFunctions.rdfTermEquals(c1, c2);
        } catch (ExprEvalException e) {
          equals = false;
        }
      }
      logger.debug("constants equal? " + new Boolean(equals));
      expression.push(equals ? Expression.FALSE : Expression.TRUE);
      return;
    } else if (e1 instanceof AttributeExprEx && e2 instanceof AttributeExprEx) {
      logger.debug("isNotEqual(" + e1 + ", " + e2 + ")");
      AttributeExprEx variable1 = (AttributeExprEx) e1;
      AttributeExprEx variable2 = (AttributeExprEx) e2;

      NodeMaker nm1 = variable1.getNodeMaker();
      NodeMaker nm2 = variable2.getNodeMaker();

      DetermineNodeType filter1 = new DetermineNodeType();
      nm1.describeSelf(filter1);
      RDFDatatype datatype1 = filter1.getDatatype();

      DetermineNodeType filter2 = new DetermineNodeType();
      nm2.describeSelf(filter2);
      RDFDatatype datatype2 = filter2.getDatatype();

      if (datatype1 != null
          && XSD.isNumeric(datatype1)
          && datatype2 != null
          && XSD.isNumeric(datatype2)) {
        RDFDatatype numericType = XSD.getNumericType(filter1.getDatatype(), filter2.getDatatype());
        nm1 = cast(nm1, numericType);
        nm2 = cast(nm2, numericType);
      }

      NodeSetConstraintBuilder nodeSet = new NodeSetConstraintBuilder();
      nm1.describeSelf(nodeSet);
      nm2.describeSelf(nodeSet);

      if (nodeSet.isEmpty()) {
        logger.debug("nodes " + nm1 + " " + nm2 + " incompatible");
        expression.push(Expression.TRUE);
        return;
      }
    }

    expression.push(new Negation(Equality.create(e1, e2)));
  }
コード例 #27
0
  static boolean isSimpleLiteral(Node node) {
    if (!node.isLiteral()) return false;

    return node.getLiteralDatatype() == null && "".equals(node.getLiteralLanguage());
  }
コード例 #28
0
 public EnhNode wrap(Node n, EnhGraph eg) {
   if (!n.isLiteral()) throw new LiteralRequiredException(n);
   return new LiteralImpl(n, eg);
 }
コード例 #29
0
ファイル: Max.java プロジェクト: brfeddersen/sadlos2
 /**
  * This method is invoked when the builtin is called in a rule body.
  *
  * @param args the array of argument values for the builtin, this is an array of Nodes, some of
  *     which may be Node_RuleVariables.
  * @param length the length of the argument list, may be less than the length of the args array
  *     for some rule engines
  * @param context an execution context giving access to other relevant data
  * @return return true if the buildin predicate is deemed to have succeeded in the current
  *     environment
  */
 @SuppressWarnings("unused")
 public boolean bodyCall(Node[] args, int length, RuleContext context) {
   checkArgs(length, context);
   BindingEnvironment env = context.getEnv();
   Object maxVal = null;
   Node min = null;
   boolean allLongs = true;
   if (length >= 3) {
     for (int i = 0; i < length; i++) {
       Node n1 = getArg(i, args, context);
       if (n1.isLiteral()) {
         Object v1 = n1.getLiteralValue();
         if (v1 instanceof Number) {
           Number nv1 = (Number) v1;
           if (maxVal == null) {
             maxVal = nv1;
           } else {
             if (v1 instanceof Float || v1 instanceof Double) {
               double pwd = nv1.doubleValue();
               if (pwd > ((Number) maxVal).doubleValue()) {
                 maxVal = nv1;
               }
               allLongs = false;
             } else if (v1 instanceof Integer || v1 instanceof Long) {
               long pwd = nv1.longValue();
               if (pwd > ((Number) maxVal).doubleValue()) {
                 maxVal = nv1;
               }
             }
           }
         } else if (v1 instanceof XSDDateTime) {
           if (maxVal == null) {
             maxVal = v1;
           } else if (maxVal instanceof XSDDateTime) {
             if (((XSDDateTime) maxVal).compareTo((XSDDateTime) v1) < 0) {
               maxVal = v1;
             }
           } else {
             throw new BuiltinException(
                 this,
                 context,
                 "Can't compare datetime ("
                     + v1.toString()
                     + ") with non-datetime value ("
                     + maxVal.toString()
                     + ")");
           }
         } else {
           return false;
         }
       }
     } // end for
   } else {
     Node n1 = getArg(0, args, context);
     if (n1 == null || n1.equals(RDF.Nodes.nil)) {
       return false;
     } else {
       maxVal = maxOfList(n1, context);
     }
   }
   if (maxVal == null) {
     return false;
   }
   if (maxVal instanceof Float) {
     min = Utils.makeFloatNode(((Number) maxVal).floatValue());
   } else if (maxVal instanceof Double) {
     min = Util.makeDoubleNode(((Number) maxVal).doubleValue());
   } else if (maxVal instanceof XSDDateTime) {
     min = Utils.makeXSDDateTimeNode((XSDDateTime) maxVal);
   } else if (maxVal instanceof Integer) {
     min = Util.makeIntNode(((Number) maxVal).intValue());
   } else {
     min = Util.makeLongNode(((Number) maxVal).longValue());
   }
   return env.bind(args[length - 1], min);
 }
コード例 #30
0
  /** Deconstruct the node or list object argument and make a SpatialMatch */
  @Override
  protected SpatialMatch objectToStruct(PropFuncArg argObject) {

    if (argObject.isNode()) {
      log.warn("Object not a List: " + argObject);
      return null;
    }

    List<Node> list = argObject.getArgList();

    if (list.size() < 4 || list.size() > 5)
      throw new SpatialIndexException("Change in object list size");

    int idx = 0;

    Node x = list.get(idx);
    if (!x.isLiteral()) {
      log.warn("Latitude 1 is not a literal " + list);
      return null;
    }
    if (!SpatialValueUtil.isDecimal(x.getLiteral())) {
      log.warn("Latitude 1 is not a decimal " + list);
      return null;
    }
    Double latitude1 = Double.parseDouble(x.getLiteralLexicalForm());

    idx++;

    x = list.get(idx);
    if (!x.isLiteral()) {
      log.warn("Longitude 1 is not a literal " + list);
      return null;
    }
    if (!SpatialValueUtil.isDecimal(x.getLiteral())) {
      log.warn("Longitude 1 is not a decimal " + list);
      return null;
    }
    Double longtitude1 = Double.parseDouble(x.getLiteralLexicalForm());

    idx++;

    x = list.get(idx);
    if (!x.isLiteral()) {
      log.warn("Latitude 2 is not a literal " + list);
      return null;
    }
    if (!SpatialValueUtil.isDecimal(x.getLiteral())) {
      log.warn("Latitude 2 is not a decimal " + list);
      return null;
    }
    Double latitude2 = Double.parseDouble(x.getLiteralLexicalForm());

    idx++;

    x = list.get(idx);
    if (!x.isLiteral()) {
      log.warn("Longitude 2 is not a literal " + list);
      return null;
    }
    if (!SpatialValueUtil.isDecimal(x.getLiteral())) {
      log.warn("Longitude 2 is not a decimal " + list);
      return null;
    }
    Double longtitude2 = Double.parseDouble(x.getLiteralLexicalForm());

    idx++;
    int limit = -1;

    if (idx < list.size()) {
      x = list.get(idx);

      if (!x.isLiteral()) {
        log.warn("Limit is not a literal " + list);
        return null;
      }

      LiteralLabel lit = x.getLiteral();

      if (!XSDDatatype.XSDinteger.isValidLiteral(lit)) {
        log.warn("Limit is not an integer " + list);
        return null;
      }

      int v = NodeFactoryExtra.nodeToInt(x);
      limit = (v < 0) ? -1 : v;

      idx++;
      if (idx < list.size()) {
        log.warn("Limit is not the last parameter " + list);
        return null;
      }
    }

    SpatialMatch match =
        new SpatialMatch(
            latitude1, longtitude1, latitude2, longtitude2, limit, getSpatialOperation());

    if (log.isDebugEnabled()) log.debug("Trying SpatialMatch: " + match.toString());
    return match;
  }