org.apache.jena.rdf.model.RDFNode Java Examples

The following examples show how to use org.apache.jena.rdf.model.RDFNode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SPARQL.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * For use with {@link #sparql(String)} Extracts answer strings. Can be directly set as golden answers in an IQuestion.
 *
 * @param answers
 * @return
 */
public static Set<String> extractAnswerStrings(final Set<RDFNode> answers) {
	Set<String> set = Sets.newHashSet();
	for (RDFNode answ : answers) {
		if (answ.isResource()) {
			set.add(answ.asResource().getURI());
		} else if (answ.isLiteral()) {
			Literal l = (Literal) answ;
			try {
				set.add(l.getString());
			} catch (Exception e) {
				e.printStackTrace();
				set.add(l.getLexicalForm());
			}

		} else {
			set.add(answ.toString());
		}
	}
	return set;
}
 
Example #2
Source File: ValidationEngine.java    From shacl with Apache License 2.0 6 votes vote down vote up
public Resource createValidationResult(Constraint constraint, RDFNode focusNode, RDFNode value, Supplier<String> defaultMessage) {
	Resource result = createResult(SH.ValidationResult, constraint, focusNode);
	if(value != null) {
		result.addProperty(SH.value, value);
	}
	if(!constraint.getShape().isNodeShape()) {
		result.addProperty(SH.resultPath, SHACLPaths.clonePath(constraint.getShapeResource().getPath(), result.getModel()));
	}
	Collection<RDFNode> messages = constraint.getShape().getMessages();
	if(messages.size() > 0) {
		messages.stream().forEach(message -> result.addProperty(SH.resultMessage, message));
	}
	else if(defaultMessage != null) {
		result.addProperty(SH.resultMessage, defaultMessage.get());
	}
	return result;
}
 
Example #3
Source File: SHACLUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a shapes Model for a given input Model.
 * The shapes Model is the union of the input Model with all graphs referenced via
 * the sh:shapesGraph property (and transitive includes or shapesGraphs of those).
 * @param model  the Model to create the shapes Model for
 * @return a shapes graph Model
 */
private static Model createShapesModel(Dataset dataset) {
	
	Model model = dataset.getDefaultModel();
	Set<Graph> graphs = new HashSet<Graph>();
	Graph baseGraph = model.getGraph();
	graphs.add(baseGraph);
	
	for(Statement s : model.listStatements(null, SH.shapesGraph, (RDFNode)null).toList()) {
		if(s.getObject().isURIResource()) {
			String graphURI = s.getResource().getURI();
			Model sm = dataset.getNamedModel(graphURI);
			graphs.add(sm.getGraph());
			// TODO: Include includes of sm
		}
	}
	
	if(graphs.size() > 1) {
		MultiUnion union = new MultiUnion(graphs.iterator());
		union.setBaseGraph(baseGraph);
		return ModelFactory.createModelForGraph(union);
	}
	else {
		return model;
	}
}
 
Example #4
Source File: ClassConstraintExecutor.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void validate(Constraint constraint, ValidationEngine engine, Resource classNode, RDFNode focusNode, RDFNode valueNode) {
	if(valueNode.isLiteral()) {
		engine.createValidationResult(constraint, focusNode, valueNode, () -> "Value must be an instance of " + engine.getLabel(classNode));			
	}
	else {			
		ClassesCache cache = engine.getClassesCache();
		if(cache != null) {
			Predicate<Resource> pred = cache.getPredicate(classNode.inModel(valueNode.getModel()));
			if(!pred.test((Resource)valueNode)) {
				engine.createValidationResult(constraint, focusNode, valueNode, () -> "Value must be an instance of " + engine.getLabel(classNode));
			}
		}
		else if(!JenaUtil.hasIndirectType((Resource)valueNode, classNode)) {
			// No cache: possibly walk superclasses for each call
			engine.createValidationResult(constraint, focusNode, valueNode, () -> "Value must be an instance of " + engine.getLabel(classNode));
		}
	}
}
 
Example #5
Source File: ModelContainer.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
List<String> getValuesOfDataProperty(RDFNode subject, String predicateURI, Map<String, Object> args) {

        final List<String> valList = new ArrayList<>();

        final NodeIterator iterator = model.listObjectsOfProperty(subject.asResource(), getPropertyFromUri(predicateURI));

        while (iterator.hasNext()) {

            RDFNode data = iterator.next();

            if (data.isLiteral()) {
                if (!args.containsKey("lang") || args.get("lang").toString().equalsIgnoreCase(data.asLiteral().getLanguage())) {
                        valList.add(data.asLiteral().getString());
                }
            }
        }
        return valList;
    }
 
Example #6
Source File: CorrectnessTask.java    From IGUANA with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean compareNodes(RDFNode solutionNode, JSONObject varBinding) {
	if(solutionNode.asNode().isBlank()) {
		//check if varBinding is bNode
		return "bnode".equals(varBinding.get("type").toString());
	}
	else if(solutionNode.asNode().isLiteral()) {
		//check if literal is the same
		String expectedValue = varBinding.get("value").toString();
		String expectedLang = varBinding.containsKey("xml:lang")?varBinding.get("xml:lang").toString():null;
		String expectedDatatype = varBinding.containsKey("datatype")?varBinding.get("datatype").toString():null;
		return checkLiteral(expectedValue, expectedLang, expectedDatatype, solutionNode.asLiteral());
	}
	else if(solutionNode.asNode().isURI()) {
		//simple check if URI is the same as value
		return solutionNode.asResource().getURI().equals(varBinding.get("value"));
	}
	return false;
}
 
Example #7
Source File: RDFToTopicMapConverter.java    From ontopia with Apache License 2.0 6 votes vote down vote up
/**
 * Finds all RTM_IN_SCOPE properties for this property and returns a
 * collection containing the RDF URIs of the values as URILocators.
 */
private Collection getScope(RDFNode rdfprop, Model model)
  throws JenaException, MalformedURLException {

  Resource subject = (Resource) rdfprop;
  Property prop = model.getProperty(RTM_IN_SCOPE);
  NodeIterator it = model.listObjectsOfProperty(subject, prop);
  ArrayList scope = new ArrayList();

  while (it.hasNext()) {
    Object o = it.next();

    if (!(o instanceof Resource))
      throw new RDFMappingException("Scoping topic must be specified by a resource, not by " + o);

    Resource obj = (Resource) o;
    LocatorIF loc = new URILocator(obj.getURI());
    scope.add(loc);
  }

  return scope;
}
 
Example #8
Source File: SPARQLDataReader.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private void parseResultSet(DataStore dataStore, MetaData dataStoreMeta, ResultSet resultSet) {
	List<String> columnNames = resultSet.getResultVars();
	for (; resultSet.hasNext();) {
		QuerySolution row = resultSet.nextSolution();
		IRecord record = new Record(dataStore);
		for (int i = 0; i < columnNames.size(); i++) {
			IFieldMetaData fieldMeta = dataStoreMeta.getFieldMeta(i);

			String columnName = columnNames.get(i);
			RDFNode rdfNode = row.get(columnName);
			getValue(rdfNode, record);
			getMetaData(rdfNode, fieldMeta);
		}
		dataStore.appendRecord(record);
	}
}
 
Example #9
Source File: PathEvaluator.java    From shacl with Apache License 2.0 6 votes vote down vote up
public ExtendedIterator<RDFNode> eval(RDFNode focusNode, NodeExpressionContext context) {
	if(input == null) {
		ExtendedIterator<RDFNode> asserted = evalFocusNode(focusNode, context);
		return withDefaultValues(withInferences(asserted, focusNode, context), focusNode, context);
	}
	else {
		Iterator<RDFNode> it = input.eval(focusNode, context);
		if(it.hasNext()) {
			RDFNode first = it.next();
			ExtendedIterator<RDFNode> result = withDefaultValues(withInferences(evalFocusNode(first, context), first, context), first, context);
			while(it.hasNext()) {
				RDFNode n = it.next();
				result = result.andThen(withDefaultValues(withInferences(evalFocusNode(n, context), n, context), first, context));
			}
			return result;
		}
		else {
			return WrappedIterator.emptyIterator();
		}
	}
}
 
Example #10
Source File: JenaUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Turns a QuerySolution into a Binding. 
 * @param map  the input QuerySolution
 * @return a Binding or null if the input is null
 */
public static Binding asBinding(final QuerySolution map) {
	if(map != null) {
		BindingHashMap result = new BindingHashMap();
		Iterator<String> varNames = map.varNames();
		while(varNames.hasNext()) {
			String varName = varNames.next();
			RDFNode node = map.get(varName);
			if(node != null) {
				result.add(Var.alloc(varName), node.asNode());
			}
		}
		return result;
	}
	else {
		return null;
	}
}
 
Example #11
Source File: NodeKindConstraintExecutor.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public void executeConstraint(Constraint constraint, ValidationEngine engine, Collection<RDFNode> focusNodes) {
	long startTime = System.currentTimeMillis();
	RDFNode nodeKind = constraint.getParameterValue();
	Predicate<RDFNode> checker = checkers.get(nodeKind);
	if(checker == null) {
		throw new IllegalArgumentException("Unsupported sh:nodeKind " + nodeKind);
	}
	String message = "Value does not have node kind " + ((Resource)nodeKind).getLocalName();
	for(RDFNode focusNode : focusNodes) {
		for(RDFNode valueNode : engine.getValueNodes(constraint, focusNode)) {
			if(!checker.test(valueNode)) {
				engine.createValidationResult(constraint, focusNode, valueNode, () -> message);
			}
		}
		engine.checkCanceled();
	}
	addStatistics(constraint, startTime);
}
 
Example #12
Source File: ITER_Call_Select.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private List<List<NodeValue>> getListNodeValues(ResultSet result) {
    List<String> resultVars = result.getResultVars();
    List<List<NodeValue>> listNodeValues = new ArrayList<>();
    while (result.hasNext()) {
        List<NodeValue> nodeValues = new ArrayList<>();
        QuerySolution sol = result.next();
        for (String var : resultVars) {
            RDFNode rdfNode = sol.get(var);
            if (rdfNode != null) {
                NodeValue n = new NodeValueNode(rdfNode.asNode());
                nodeValues.add(n);
            } else {
                nodeValues.add(null);
            }
        }
        listNodeValues.add(nodeValues);
    }
    return listNodeValues;
}
 
Example #13
Source File: QALD4_EvaluationUtils.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Set<RDFNode> answersToRDFNode(final Set<String> answers) {
	Set<RDFNode> tmp = new HashSet<>();
	for (String s : answers) {
		tmp.add(new ResourceImpl(s));
	}
	return tmp;
}
 
Example #14
Source File: SHFactory.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static boolean isParameterizableConstraint(RDFNode node) {
	if(node instanceof Resource) {
		Resource r = (Resource) node;
		if(!r.hasProperty(RDF.type)) {
			return  node.getModel().contains(null, SH.property, node) ||
					node.getModel().contains(null, SH.parameter, node);
		}
		else if(r.hasProperty(RDF.type, SH.NodeShape) ||
				r.hasProperty(RDF.type, SH.PropertyShape) ||
				r.hasProperty(RDF.type, SH.Parameter)) {
			return true;
		}
	}
	return false;
}
 
Example #15
Source File: QualifiedValueShapeConstraintExecutor.java    From shacl with Apache License 2.0 5 votes vote down vote up
private boolean hasAnySiblingShape(ValidationEngine engine, Constraint constraint, RDFNode focusNode, RDFNode valueNode) {
    for(Resource sibling : siblings) {
    	Model results = hasShape(engine, constraint, focusNode, valueNode, sibling, true);
    	if(results == null) {
    		return true;
    	}
    }
    return false;
}
 
Example #16
Source File: MinCountConstraintExecutor.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public void executeConstraint(Constraint constraint, ValidationEngine engine, Collection<RDFNode> focusNodes) {
	long startTime = System.currentTimeMillis();
	for(RDFNode focusNode : focusNodes) {
		int count = engine.getValueNodes(constraint, focusNode).size();
		if(count < minCount) {
			engine.createValidationResult(constraint, focusNode, null,() -> "Property needs to have at least " + minCount + " values, but found " + count);
		}
		engine.checkCanceled();
	}
	addStatistics(constraint, startTime);
}
 
Example #17
Source File: FetcherFactory.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
public DataFetcher<String> idFetcher() {
    
    return environment -> {
        RDFNode thisNode = environment.getSource();

        if (thisNode.asResource().isURIResource()) {
            return thisNode.asResource().getURI();
        } else {
            return "_:" + thisNode.asNode().getBlankNodeLabel();
        }
    };
}
 
Example #18
Source File: UnionExpression.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public ExtendedIterator<RDFNode> eval(RDFNode focusNode, NodeExpressionContext context) {
	ExtendedIterator<RDFNode> result = NullIterator.instance();
       for(NodeExpression i : inputs) {
       	ExtendedIterator<RDFNode> it = i.eval(focusNode, context);
           result = result.andThen(it);
       }
	return result;
}
 
Example #19
Source File: SHACLObject.java    From shacl with Apache License 2.0 5 votes vote down vote up
public boolean nodeConformsToShape(JSTerm node, JSTerm shape) {
	try {
		if(RecursionGuard.start(node.getNode(), shape.getNode())) {
			return true;
		}
		else {
			List<RDFNode> focusNodes = Collections.singletonList(dataset.getDefaultModel().asRDFNode(node.getNode()));
			return ValidationEngineFactory.get().create(dataset, shapesGraphURI, shapesGraph, null).
				nodesConformToShape(focusNodes, shape.getNode());
		}
	}
	finally {
		RecursionGuard.end(node.getNode(), shape.getNode());
	}
}
 
Example #20
Source File: ExistsExpression.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public ExtendedIterator<RDFNode> eval(RDFNode focusNode, NodeExpressionContext context) {
	ExtendedIterator<RDFNode> it = evalInput(focusNode, context);
	RDFNode result = it.hasNext() ? JenaDatatypes.TRUE : JenaDatatypes.FALSE;
	it.close();
	return WrappedIterator.create(Collections.singletonList(result).iterator());
}
 
Example #21
Source File: RDFLabels.java    From shacl with Apache License 2.0 5 votes vote down vote up
/**
 * Renders a template call's label template into a label by inserting the
 * evaluated SPARQL expressions into appropriate spaces marked with {expression}.
 * Currently only simple variables are supported, e.g. {?test }. 
 * @param buffer  the StringBuffer to write to
 * @param labelTemplate  the labelTemplate
 * @param args  the arguments  a Map of pre-bound variables (supplied arguments)
 */
public static void appendTemplateCallLabel(StringBuffer buffer, String labelTemplate, Map<String, RDFNode> args) {
	for(int i = 0; i < labelTemplate.length(); i++) {
		if(i < labelTemplate.length() - 3 && labelTemplate.charAt(i) == '{' && labelTemplate.charAt(i + 1) == '?') {
			int varEnd = i + 2;
			while(varEnd < labelTemplate.length()) {
				if(labelTemplate.charAt(varEnd) == '}') {
					String varName = labelTemplate.substring(i + 2, varEnd);
					RDFNode varValue = args.get(varName);
					if(varValue instanceof Resource) {
						buffer.append(get().getLabel((Resource)varValue));
					}
					else if(varValue instanceof Literal) {
						buffer.append(varValue.asNode().getLiteralLexicalForm());
					}
					break;
				}
				else {
					varEnd++;
				}
			}
			i = varEnd;
		}
		else {
			buffer.append(labelTemplate.charAt(i));
		}
	}
}
 
Example #22
Source File: RdfListUtils.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to get the items of an rdf:List and throws an {@link IllegalArgumentException} if it is not a list
 */
public static Collection<RDFNode> getListItemsOrFail(RDFNode node) {

    if (!isList(node)) {
        throw new IllegalArgumentException("Resource not an rdf:List");
    }

    return getListItemsOrEmpty(node);
}
 
Example #23
Source File: StructuralMatcherImpl.java    From FCA-Map with GNU General Public License v3.0 5 votes vote down vote up
private <T extends RDFNode> String getRepresent(T r) {
  if (r.isURIResource() || r.isResource() || r.isAnon()) {
    return r.asNode().getURI();
  }
  else if (r.isLiteral()) {
    return r.asLiteral().getLexicalForm();
  }
  return "null";
}
 
Example #24
Source File: ModelContainer.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
List<RDFNode> getValuesOfObjectProperty(RDFNode subject, String predicateURI, String targetURI) {

        NodeIterator iterator = this.model.listObjectsOfProperty(subject.asResource(), getPropertyFromUri(predicateURI));
        List<RDFNode> rdfNodes = new ArrayList<>();
        iterator.forEachRemaining(node -> {
            if (!node.isLiteral()) {
                if(targetURI == null) {
                    rdfNodes.add(node);
                } else if(this.model.contains(node.asResource(), getPropertyFromUri(HGQLVocabulary.RDF_TYPE), getResourceFromUri(targetURI))) {
                    rdfNodes.add(node);
                }
            }
        });
        return rdfNodes;
    }
 
Example #25
Source File: RDFToTopicMapConverter.java    From ontopia with Apache License 2.0 5 votes vote down vote up
private void buildMappings(Model model) throws MalformedURLException {
  mappings = new HashMap();
  Property mapsTo = model.createProperty(RTM_MAPSTO);
  StmtIterator it = model.listStatements(null, mapsTo, (RDFNode) null);
  while (it.hasNext()) {
    Statement stmt = (Statement) it.next();
    StatementHandler mapper = getMapper(stmt.getSubject(), stmt.getObject(), model);
    mappings.put(stmt.getSubject().getURI(), mapper);
  }
  it.close();
}
 
Example #26
Source File: Binding.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
public Binding(Resource element, PatternParameter parameter, RDFNode value) {
    this.element = checkNotNull(element, "Element must not be null");
    this.parameter =checkNotNull(parameter, "parameter must not be null in Binding");
    this.value = checkNotNull(value, "value must not be null in Binding");

    //Validate biding
    if (!validateType()) {
        //throw new BindingException("Binding is of incorrect constraint type");
    }
}
 
Example #27
Source File: HGQLSchema.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
private String getTargetTypeName(RDFNode outputTypeNode) {
    String typeName = rdfSchema.getValueOfDataProperty(outputTypeNode, HGQL_HAS_NAME);
    if (typeName!=null) {
        return typeName;
    } else {
        RDFNode childOutputNode = rdfSchema.getValueOfObjectProperty(outputTypeNode, HGQL_OF_TYPE);
        return getTargetTypeName(childOutputNode);
    }
}
 
Example #28
Source File: HGQLSchema.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
private Boolean getIsList(RDFNode outputTypeNode) {
    RDFNode outputNode = rdfSchema.getValueOfObjectProperty(outputTypeNode, RDF_TYPE);
    String typeURI = outputNode.asResource().getURI();
    if (typeURI.equals(HGQL_LIST_TYPE)) { return true; }
    else {
        RDFNode childOutputNode = rdfSchema.getValueOfObjectProperty(outputTypeNode, HGQL_OF_TYPE);
        if (childOutputNode!=null) { return getIsList(childOutputNode); }
        else {
            return false;
        }
    }
}
 
Example #29
Source File: TestCaseGroup.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
static RDFNode getValue(ShaclLiteTestCaseResult result){
    if(ShaclTestCaseResult.class.isAssignableFrom(result.getClass())){
        Set<PropertyValuePair> values = ((ShaclTestCaseResult) result).getResultAnnotations().stream().filter(ra -> ra.getProperty().equals(SHACL.value)).collect(Collectors.toSet());
        if(! values.isEmpty()){
            return values.iterator().next().getValues().iterator().next();
        }
    }
    return result.getFailingNode(); // the default case concerns non property nodes which are grouped under the focus node iri
}
 
Example #30
Source File: ValidationEngine.java    From shacl with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a Set of all Shapes that should be evaluated for a given resource.
 * @param focusNode  the resource to get the shapes for
 * @param dataset  the Dataset containing the resource
 * @param shapesModel  the shapes Model
 * @return a Set of shape resources
 */
private Set<Resource> getShapesForNode(RDFNode focusNode, Dataset dataset, Model shapesModel) {

	Set<Resource> shapes = new HashSet<>();
	
	for(Shape rootShape : shapesGraph.getRootShapes()) {
		for(Target target : rootShape.getTargets()) {
			if(!(target instanceof InstancesTarget)) {
				if(target.contains(dataset, focusNode)) {
					shapes.add(rootShape.getShapeResource());
				}
			}
		}
	}
	
	// rdf:type / sh:targetClass
	if(focusNode instanceof Resource) {
		for(Resource type : JenaUtil.getAllTypes((Resource)focusNode)) {
			if(JenaUtil.hasIndirectType(type.inModel(shapesModel), SH.Shape)) {
				shapes.add(type);
			}
			for(Statement s : shapesModel.listStatements(null, SH.targetClass, type).toList()) {
				shapes.add(s.getSubject());
			}
		}
	}
	
	return shapes;
}