Esempio n. 1
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");
 }
Esempio n. 2
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 ;
  }
    @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;
    }
Esempio n. 4
0
 @Override
 protected Node rename(Node uri) {
   if (uri.getNameSpace().equals(replaceNS))
     return Node.createURI(namespace + uri.getLocalName());
   if (uri.getURI().equals(replace))
     return Node.createURI(namespace.substring(0, namespace.length() - 1));
   return uri;
 }
 @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()));
 }
Esempio n. 6
0
 /**
  * Gets Jena statement selector corresponding to the NXRelations statement.
  *
  * @param graph the jena graph
  * @param nuxStatement NXRelations statement
  * @return jena statement selector
  */
 private static SimpleSelector getJenaSelector(Model graph, Statement nuxStatement) {
   com.hp.hpl.jena.rdf.model.Resource subjResource = null;
   com.hp.hpl.jena.graph.Node subject = getJenaNode(nuxStatement.getSubject());
   if (subject != null && subject.isURI()) {
     subjResource = graph.getResource(subject.getURI());
   }
   Property predProp = null;
   com.hp.hpl.jena.graph.Node predicate = getJenaNode(nuxStatement.getPredicate());
   if (predicate != null && predicate.isURI()) {
     predProp = graph.getProperty(predicate.getURI());
   }
   com.hp.hpl.jena.graph.Node object = getJenaNode(nuxStatement.getObject());
   RDFNode objRDF = null;
   if (object != null) {
     objRDF = graph.asRDFNode(object);
   }
   return new SimpleSelector(subjResource, predProp, objRDF);
 }
 @Override
 public Graph getGraph(Node graphNode) {
   Model model = dataset.getNamedModel(graphNode.getURI());
   if (model != null) {
     return getControlledUpdateGraph(model.getGraph());
   } else {
     return null;
   }
 }
 private SWRLIndividualObject makeIndividalObject(final Node node) throws URISyntaxException {
   if (node.isVariable()) {
     final SWRLIndividualVariable var =
         swrlFactory.createIndividualVariable(new URI(varNS + node.getName()));
     vars.put(node.toString(), var);
     return var;
   }
   final OWLIndividual ind = owlModel.createIndividual(null, new URI(node.getURI()));
   return swrlFactory.wrapIndividual(ind);
 }
Esempio n. 9
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]";
  }
  @Override
  public Iterator<Triple> apply(final T input) {

    try {
      final Node propertyDefinitionNode = getResource(input).asNode();

      LOGGER.trace(
          "Adding triples for nodeType: {} with child nodes: {}",
          context.getURI(),
          propertyDefinitionNode.getURI());

      return new RdfStream(
          create(propertyDefinitionNode, type.asNode(), Property.asNode()),
          create(propertyDefinitionNode, domain.asNode(), context),
          create(propertyDefinitionNode, label.asNode(), createLiteral(input.getName())));
    } catch (final RepositoryException e) {
      throw propagate(e);
    }
  }
Esempio n. 11
0
  @Override
  public Iterator<Quad> find(Node graph, Node subject, Node predicate, Node object) {
    if (!isVar(subject) && !isVar(predicate) && !isVar(object) && !isVar(graph)) {
      if (contains(subject, predicate, object, graph)) {
        return new SingletonIterator(new Triple(subject, predicate, object));
      } else {
        return WrappedIterator.create(Collections.EMPTY_LIST.iterator());
      }
    }
    StringBuffer findQuery = new StringBuffer("SELECT * WHERE { \n");
    String graphURI = !isVar(graph) ? graph.getURI() : null;
    findQuery.append("  GRAPH ");
    if (graphURI != null) {
      findQuery.append("  <" + graphURI + ">");
    } else {
      findQuery.append("?g");
    }
    findQuery.append(" { ");
    findQuery
        .append(SparqlGraph.sparqlNode(subject, "?s"))
        .append(" ")
        .append(SparqlGraph.sparqlNode(predicate, "?p"))
        .append(" ")
        .append(SparqlGraph.sparqlNode(object, "?o"));
    findQuery.append("  } ");
    findQuery.append("\n}");

    // log.info(findQuery.toString());

    ResultSet rs = null;

    try {
      rs =
          JSONInput.fromJSON(
              rdfService.sparqlSelectQuery(findQuery.toString(), RDFService.ResultFormat.JSON));
    } catch (RDFServiceException rdfse) {
      throw new RuntimeException(rdfse);
    }

    List<Quad> quadlist = new ArrayList<Quad>();
    while (rs.hasNext()) {
      QuerySolution soln = rs.nextSolution();
      Quad q =
          new Quad(
              isVar(graph) ? soln.get("?g").asNode() : graph,
              isVar(subject) ? soln.get("?s").asNode() : subject,
              isVar(predicate) ? soln.get("?p").asNode() : predicate,
              isVar(object) ? soln.get("?o").asNode() : object);
      // log.info(t);
      quadlist.add(q);
    }
    // log.info(triplist.size() + " results");
    return WrappedIterator.create(quadlist.iterator());
  }
Esempio n. 12
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);
  }
  public SPDXChecksum(Model spdxModel, Node checksumNode) throws InvalidSPDXAnalysisException {
    this.model = spdxModel;
    this.checksumNode = checksumNode;
    if (checksumNode.isBlank()) {
      checksumResource = model.createResource(checksumNode.getBlankNodeId());
    } else if (checksumNode.isURI()) {
      checksumResource = model.createResource(checksumNode.getURI());
    } else {
      throw (new InvalidSPDXAnalysisException("Checksum node can not be a literal"));
    }
    // Algorithm
    Node p =
        spdxModel
            .getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CHECKSUM_ALGORITHM)
            .asNode();
    Triple m = Triple.createMatch(checksumNode, p, null);
    ExtendedIterator<Triple> tripleIter = spdxModel.getGraph().find(m);
    while (tripleIter.hasNext()) {
      Triple t = tripleIter.next();
      if (t.getObject().isLiteral()) {
        // The following is for compatibility with rdf generated with older
        // versions of the tool
        this.algorithm = t.getObject().toString(false);
      } else if (t.getObject().isURI()) {
        this.algorithm = URI_TO_ALGORITHM.get(t.getObject().getURI());
        if (this.algorithm == null) {
          this.algorithm = "UNKNOWN";
        }
      } else {
        throw (new InvalidSPDXAnalysisException(
            "Invalid checksum algorithm - must be one of the defined algorithms supported by SPDX."));
      }
    }

    // value
    p =
        spdxModel
            .getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CHECKSUM_VALUE)
            .asNode();
    m = Triple.createMatch(checksumNode, p, null);
    tripleIter = spdxModel.getGraph().find(m);
    while (tripleIter.hasNext()) {
      Triple t = tripleIter.next();
      this.value = t.getObject().toString(false);
    }
  }
  public void compute(Quad quad) {
    //		logger.debug("Assessing {}", quad.asTriple().toString());

    Node predicate = quad.getPredicate(); // retrieve predicate
    Node object = quad.getObject(); // retrieve object

    // checking if classes are found in the property position
    //		logger.info("Is the used predicate {} actually a class?", predicate.getURI());
    this.totalPropertiesCount++;
    if (seenProperties.containsKey(predicate.toString())) {
      if (!(seenProperties.get(predicate.toString()))) {
        this.misplacedPropertiesCount++;
        this.createProblemModel(quad.getSubject(), predicate, DQM.MisplacedClass);
      }
    } else {
      if ((VocabularyLoader.isClass(predicate)) && (VocabularyLoader.checkTerm(predicate))) {
        this.misplacedPropertiesCount++;
        this.createProblemModel(quad.getSubject(), predicate, DQM.MisplacedClass);
        seenProperties.put(predicate.toString(), false);
      }
      seenProperties.put(predicate.toString(), true);
    }

    // checking if properties are found in the object position
    if ((object.isURI())
        && (predicate.getURI().equals(RDF.type.getURI()))
        && (VocabularyLoader.checkTerm(object))) {
      //			logger.info("Checking {} for misplaced class", object.getURI());
      this.totalClassesCount++;
      if (seenClasses.containsKey(object.toString())) {
        if (!(seenClasses.get(object.toString()))) {
          this.misplacedClassesCount++;
          this.createProblemModel(quad.getSubject(), object, DQM.MisplacedProperty);
        }
      } else {
        if (VocabularyLoader.isProperty(object)) {
          this.misplacedClassesCount++;
          this.createProblemModel(quad.getSubject(), object, DQM.MisplacedProperty);
          seenClasses.put(object.toString(), false);
        }
        seenClasses.put(object.toString(), true);
      }
    }
  }
Esempio n. 15
0
 /**
  * Gets NXRelations node instance given Jena node.
  *
  * @param jenaNodeInst
  * @return NXRelations node instance
  */
 private Node getNXRelationsNode(com.hp.hpl.jena.graph.Node jenaNodeInst) {
   if (jenaNodeInst == null) {
     return null;
   }
   Node nuxNode = null;
   if (jenaNodeInst.isBlank()) {
     AnonId anonId = jenaNodeInst.getBlankNodeId();
     String id = anonId.getLabelString();
     nuxNode = NodeFactory.createBlank(id);
   } else if (jenaNodeInst.isLiteral()) {
     LiteralLabel label = jenaNodeInst.getLiteral();
     String value = label.getLexicalForm();
     String type = jenaNodeInst.getLiteralDatatypeURI();
     String language = jenaNodeInst.getLiteralLanguage();
     if (type != "") {
       nuxNode = NodeFactory.createTypedLiteral(value, type);
     } else if (language != "") {
       nuxNode = NodeFactory.createLiteral(value, language);
     } else {
       nuxNode = NodeFactory.createLiteral(value);
     }
   } else if (jenaNodeInst.isURI()) {
     String uri = jenaNodeInst.getURI();
     // try to find corresponding prefix
     // TODO AT: maybe take namespaces from relation service?
     for (Map.Entry<String, String> ns : namespaces.entrySet()) {
       String base = ns.getValue();
       if (uri.startsWith(base)) {
         String localName = uri.substring(base.length());
         nuxNode = NodeFactory.createQNameResource(base, localName);
         break;
       }
     }
     if (nuxNode == null) {
       // default to resource
       nuxNode = NodeFactory.createResource(uri);
     }
   } else {
     throw new IllegalArgumentException(
         "Cannot translate non concrete Jena node into NXRelations node");
   }
   return nuxNode;
 }
Esempio n. 16
0
  /**
   * Map a Jena graph node to a Mulgara value.
   *
   * @param x The Jena Node to convert.
   * @param session A session to use for blank node persistence.
   * @return A Mulgara Value.
   * @throws URISyntaxException When creating a URIReference that refers to an invalid URI.
   */
  static Value n2v(Node x, Session session) throws URISyntaxException {
    if (x.isURI()) return new URIReferenceImpl(new URI(x.getURI()));

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

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

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

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

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

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

    throw new RuntimeException("Can't convert from Jena node : " + x);
  }
Esempio n. 17
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. 18
0
 protected static String sparqlNode(Node node, String varName) {
   if (node == null || node.isVariable()) {
     return varName;
   } else if (node.isBlank()) {
     return "<fake:blank>"; // or throw exception?
   } else if (node.isURI()) {
     StringBuffer uriBuff = new StringBuffer();
     return uriBuff.append("<").append(node.getURI()).append(">").toString();
   } else if (node.isLiteral()) {
     StringBuffer literalBuff = new StringBuffer();
     literalBuff.append("\"");
     pyString(literalBuff, node.getLiteralLexicalForm());
     literalBuff.append("\"");
     if (node.getLiteralDatatypeURI() != null) {
       literalBuff.append("^^<").append(node.getLiteralDatatypeURI()).append(">");
     } else if (node.getLiteralLanguage() != null && node.getLiteralLanguage().length() > 0) {
       literalBuff.append("@").append(node.getLiteralLanguage());
     }
     return literalBuff.toString();
   } else {
     return varName;
   }
 }
  private static int countContainerMember(
      Graph graph, Node container, Node containerType, Node member, boolean stopEarly) {
    if (graph == null) {
      Log.warn(GraphContainerUtils.class, "containerMember called with null graph");
      return 0;
    }

    if (container == null) {
      Log.warn(GraphContainerUtils.class, "containerMember called with null list");
      return 0;
    }
    if (member == null) {
      Log.warn(GraphContainerUtils.class, "containerMember called with null member");
      return 0;
    }

    if (!isContainer(graph, container, containerType)) return 0;

    int count = 0;
    ExtendedIterator<Triple> iter = graph.find(container, Node.ANY, member);
    try {
      for (; iter.hasNext(); ) {
        Triple t = iter.next();
        Node p = t.getPredicate();
        String u = p.getURI();

        if (u.matches(membershipPattern)) {
          count++;
          if (stopEarly) return count;
        }
      }
    } finally {
      iter.close();
    }
    return count;
  }
  public List<AlphaResultUnion> calculateAlphaSTG(
      Collection<Triple> triples, AbstractConceptMapping cm) throws Exception {
    List<AlphaResultUnion> alphaResultUnionList = new Vector<AlphaResultUnion>();

    Triple firstTriple = triples.iterator().next();
    Node tpSubject = firstTriple.getSubject();
    SQLLogicalTable alphaSubject = this.calculateAlphaSubject(tpSubject, cm);
    // String logicalTableAlias = cm.getLogicalTableAlias();
    String logicalTableAlias = alphaSubject.getAlias();
    //		if(logicalTableAlias == null || logicalTableAlias.equals("")) {
    //			cm.setLogicalTableAlias(alphaSubject.getAlias());
    //		}

    // mapping projection of corresponding predicates

    for (Triple tp : triples) {
      Node tpPredicate = tp.getPredicate();
      List<SQLJoinTable> alphaPredicateObjects = new Vector<SQLJoinTable>();
      List<SQLLogicalTable> alphaPredicateObjects2 = new Vector<SQLLogicalTable>();
      if (tpPredicate.isURI()) {
        String tpPredicateURI = tpPredicate.getURI();

        Collection<String> mappedClassURIs = cm.getMappedClassURIs();
        boolean processableTriplePattern = true;
        if (tp.getObject().isURI()) {
          String objectURI = tp.getObject().getURI();
          if (RDF.type.getURI().equals(tpPredicateURI) && mappedClassURIs.contains(objectURI)) {
            processableTriplePattern = false;
          }
        }

        if (processableTriplePattern) {
          List<SQLJoinTable> alphaPredicateObjectAux =
              calculateAlphaPredicateObjectSTG(tp, cm, tpPredicateURI, logicalTableAlias);
          if (alphaPredicateObjectAux != null) {
            alphaPredicateObjects.addAll(alphaPredicateObjectAux);
          }

          List<SQLLogicalTable> alphaPredicateObjectAux2 =
              calculateAlphaPredicateObjectSTG2(tp, cm, tpPredicateURI, logicalTableAlias);
          if (alphaPredicateObjectAux2 != null) {
            alphaPredicateObjects2.addAll(alphaPredicateObjectAux2);
          }

          AlphaResult alphaResult =
              new AlphaResult(alphaSubject, alphaPredicateObjects, tpPredicateURI);
          // alphaResult.setAlphaPredicateObjects2(alphaPredicateObjectAux2);

          AlphaResultUnion alphaTP = new AlphaResultUnion(alphaResult);
          alphaResultUnionList.add(alphaTP);
        }
      } else if (tpPredicate.isVariable()) {
        Collection<AbstractPropertyMapping> pms = cm.getPropertyMappings();
        AlphaResultUnion alphaTP = new AlphaResultUnion();
        for (AbstractPropertyMapping pm : pms) {
          String tpPredicateURI = pm.getMappedPredicateName();
          List<SQLJoinTable> alphaPredicateObjectAux =
              calculateAlphaPredicateObjectSTG(tp, cm, tpPredicateURI, logicalTableAlias);
          if (alphaPredicateObjectAux != null) {
            alphaPredicateObjects.addAll(alphaPredicateObjectAux);
          }

          List<SQLLogicalTable> alphaPredicateObjectAux2 =
              calculateAlphaPredicateObjectSTG2(tp, cm, tpPredicateURI, logicalTableAlias);
          if (alphaPredicateObjectAux2 != null) {
            alphaPredicateObjects2.addAll(alphaPredicateObjectAux2);
          }

          AlphaResult alphaResult =
              new AlphaResult(alphaSubject, alphaPredicateObjects, tpPredicateURI);
          // alphaResult.setAlphaPredicateObjects2(alphaPredicateObjectAux2);

          alphaTP.add(alphaResult);
        }

        if (alphaTP != null) {
          alphaResultUnionList.add(alphaTP);
        }

      } else {
        String errorMessage = "Predicate has to be either an URI or a variable";
        throw new QueryTranslationException(errorMessage);
      }
    }

    return alphaResultUnionList;
  }
Esempio n. 21
0
  @Override
  public void compute(Quad quad) {
    logger.debug("Computing : {} ", quad.asTriple().toString());

    Node subject = quad.getSubject();
    Node object = quad.getObject();

    if (quad.getObject().equals(FOAF.Document.asNode())) {
      docs.putIfAbsent(subject.toString(), new DigitalSignature());
    }

    if (quad.getPredicate().equals(ASSURANCE.asNode())) {
      DigitalSignature ds;
      if (endorsements.containsKey(object.getURI())) {
        ds = endorsements.get(object.getURI());
      } else {
        ds = new DigitalSignature();
        ds.endorcement = object.getURI();
      }

      ds.assurance = subject.getURI();

      docs.put(subject.toString(), ds);
      endorsements.put(object.getURI(), ds);
    }

    if (quad.getPredicate().equals(ENDORSER.asNode())) {
      DigitalSignature ds;
      if (endorsements.containsKey(object.getURI())) {
        ds = endorsements.get(object.getURI());
      } else {
        ds = new DigitalSignature();
        ds.endorcement = subject.getURI();
      }

      ds.endorcer = object.getURI();
    }

    if (quad.getObject().equals(ENDORSEMENT.asNode())) {
      DigitalSignature ds = new DigitalSignature();
      ds.endorcement = subject.getURI();

      endorsements.putIfAbsent(subject.getURI(), ds);
    }
  }
Esempio n. 22
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));
  }
Esempio n. 23
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)));
  }
 @Override
 public boolean containsGraph(Node graphNode) {
   return dataset.containsNamedModel(graphNode.getURI());
 }
Esempio n. 25
0
 @Override
 public RDFServiceGraph getGraph(Node arg0) {
   return new RDFServiceGraph(rdfService, arg0.getURI());
 }
Esempio n. 26
0
 private Graph getGraphFor(Node g) {
   return (g == Node.ANY)
       ? new RDFServiceGraph(rdfService)
       : new RDFServiceGraph(rdfService, g.getURI());
 }
Esempio n. 27
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;
  }