/** 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; }
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"); }
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); }
/** * 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); }
public static String str(Node node) { if (node.isLiteral()) return node.getLiteral().getLexicalForm(); if (node.isURI()) return node.getURI(); // if ( node.isBlank() ) return node.getBlankNodeId().getLabelString() ; // if ( node.isBlank() ) return "" ; if (node.isBlank()) NodeValue.raise(new ExprTypeException("Blank node: " + node)); NodeValue.raise(new ExprEvalException("Not a string: " + node)); return "[undef]"; }
private static boolean matchNode(Item node, Item item, Match details) { if (isAny(item)) { details.anyMatches++; return true; } if (isAnyVar(item)) { details.varMatches++; return true; } if (node.isSymbol()) { // TERM in the thing to be matched means something concrete will be there. if (node.equals(TERM)) { if (item.equals(TERM)) { details.termMatches++; return true; } // Does not match LITERAL, URI, BNODE and VAR/ANY were done above. return false; } throw new ARQException("StatsMatcher: unexpected slot type: " + node); } if (!node.isNode()) return false; Node n = node.getNode(); if (n.isConcrete()) { if (item.isNode() && item.getNode().equals(n)) { details.exactMatches++; return true; } if (isAnyTerm(item)) { details.termMatches++; return true; } if (isAnyURI(item) && n.isURI()) { details.termMatches++; return true; } if (isAnyLiteral(item) && n.isLiteral()) { details.termMatches++; return true; } if (isAnyBNode(item) && n.isBlank()) { details.termMatches++; return true; } } return false; }
private Node walkTree( Model model, Dataset oldDataset, Node node, Node predicate, Query query, QuerySolution initialBinding, Set<Node> reached) { QuerySolutionMap localBinding = new QuerySolutionMap(); localBinding.addAll(initialBinding); localBinding.add("arg1", model.asRDFNode(node)); Dataset dataset = new DatasetWithDifferentDefaultModel(model, oldDataset); QueryExecution qexec = ARQFactory.get().createQueryExecution(query, dataset, localBinding); ResultSet rs = qexec.execSelect(); try { if (rs.hasNext()) { List<String> resultVars = rs.getResultVars(); String varName = resultVars.get(0); RDFNode resultNode = rs.next().get(varName); if (resultNode != null) { return resultNode.asNode(); } } } finally { qexec.close(); } // Recurse into parents ExtendedIterator<Triple> it = createIterator(model.getGraph(), node, predicate); try { while (it.hasNext()) { Node next = getNext(it.next()); if ((next.isBlank() || next.isURI()) && !reached.contains(next)) { reached.add(next); Node nextResult = walkTree(model, oldDataset, next, predicate, query, initialBinding, reached); if (nextResult != null) { return nextResult; } } } } finally { it.close(); } return null; }
public SPDXChecksum(Model spdxModel, Node checksumNode) throws InvalidSPDXAnalysisException { this.model = spdxModel; this.checksumNode = checksumNode; if (checksumNode.isBlank()) { checksumResource = model.createResource(checksumNode.getBlankNodeId()); } else if (checksumNode.isURI()) { checksumResource = model.createResource(checksumNode.getURI()); } else { throw (new InvalidSPDXAnalysisException("Checksum node can not be a literal")); } // Algorithm Node p = spdxModel .getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CHECKSUM_ALGORITHM) .asNode(); Triple m = Triple.createMatch(checksumNode, p, null); ExtendedIterator<Triple> tripleIter = spdxModel.getGraph().find(m); while (tripleIter.hasNext()) { Triple t = tripleIter.next(); if (t.getObject().isLiteral()) { // The following is for compatibility with rdf generated with older // versions of the tool this.algorithm = t.getObject().toString(false); } else if (t.getObject().isURI()) { this.algorithm = URI_TO_ALGORITHM.get(t.getObject().getURI()); if (this.algorithm == null) { this.algorithm = "UNKNOWN"; } } else { throw (new InvalidSPDXAnalysisException( "Invalid checksum algorithm - must be one of the defined algorithms supported by SPDX.")); } } // value p = spdxModel .getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CHECKSUM_VALUE) .asNode(); m = Triple.createMatch(checksumNode, p, null); tripleIter = spdxModel.getGraph().find(m); while (tripleIter.hasNext()) { Triple t = tripleIter.next(); this.value = t.getObject().toString(false); } }
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); } } }
/** * 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; }
/** * 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); }
private void onePattern(Item elt) { Item pat = elt.getList().get(0); if (pat.isNode()) { // (<uri> weight) Node n = pat.getNode(); if (!n.isURI()) { log.warn("Not a preicate URI: " + pat.toString()); return; } addAbbreviation(elt); } else if (pat.isSymbol()) { if (pat.equals(OTHER)) { double d = elt.getList().get(1).getDouble(); DefaultMatch = d; return; } if (pat.equals(BNODE) || pat.equals(LITERAL)) { log.warn("Not a match for a predicate URI: " + pat.toString()); return; } if (pat.equals(TERM) || pat.equals(VAR) || pat.equals(ANY)) addAbbreviation(elt); else { log.warn("Not understood: " + pat); return; } } else if (pat.isList() && pat.getList().size() == 3) { // It's of the form ((S P O) weight) Item w = elt.getList().get(1); Pattern pattern = new Pattern( ((Number) (w.getNode().getLiteralValue())).doubleValue(), intern(pat.getList().get(0)), intern(pat.getList().get(1)), intern(pat.getList().get(2))); addPattern(pattern); } else { log.warn("Unrecognized pattern: " + pat); } }
/* * See http://www.w3.org/TR/rdf-sparql-query paragraph 11.4.2 * * "(ISIRI) Returns true if term is an IRI. Returns false otherwise." * * @see http://www.w3.org/TR/rdf-sparql-query */ private void convertIsIRI(E_IsIRI expr) { logger.debug("convertIsIRI " + expr.toString()); expr.getArg().visit(this); Expression arg = expression.pop(); if (arg instanceof AttributeExprEx) { AttributeExprEx variable = (AttributeExprEx) arg; NodeMaker nm = variable.getNodeMaker(); DetermineNodeType filter = new DetermineNodeType(); nm.describeSelf(filter); expression.push(filter.isLimittedToURIs() ? Expression.TRUE : Expression.FALSE); } else if (arg instanceof ConstantEx) { ConstantEx constant = (ConstantEx) arg; Node node = constant.getNode(); expression.push(node.isURI() ? Expression.TRUE : Expression.FALSE); } else { conversionFailed(expr); } }
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; } }
/* * 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)); }
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))); }
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; }
public static boolean isIRI(Node node) { if (node.isURI()) return true; return false; }
/** * 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; }