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

The following examples show how to use org.apache.jena.rdf.model.RDFNode. These examples are extracted from open source projects. 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 Project: shacl   Author: TopQuadrant   File: ValidationEngine.java    License: 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 #2
Source Project: shacl   Author: TopQuadrant   File: SHACLUtil.java    License: 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 #3
Source Project: hypergraphql   Author: hypergraphql   File: ModelContainer.java    License: 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 #4
Source Project: IGUANA   Author: dice-group   File: CorrectnessTask.java    License: 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 #5
Source Project: ontopia   Author: ontopia   File: RDFToTopicMapConverter.java    License: 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 #6
Source Project: Knowage-Server   Author: KnowageLabs   File: SPARQLDataReader.java    License: 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 #7
Source Project: shacl   Author: TopQuadrant   File: PathEvaluator.java    License: 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 #8
Source Project: NLIWOD   Author: dice-group   File: SPARQL.java    License: 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 #9
Source Project: sparql-generate   Author: sparql-generate   File: ITER_Call_Select.java    License: 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 #10
Source Project: shacl   Author: TopQuadrant   File: NodeKindConstraintExecutor.java    License: 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 #11
Source Project: shacl   Author: TopQuadrant   File: JenaUtil.java    License: 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 #12
Source Project: shacl   Author: TopQuadrant   File: ClassConstraintExecutor.java    License: 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 #13
Source Project: RDFUnit   Author: AKSW   File: Binding.java    License: 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 #14
Source Project: FCA-Map   Author: icgw   File: StructuralMatcherImpl.java    License: 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 #15
Source Project: hypergraphql   Author: hypergraphql   File: FetcherFactory.java    License: 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 #16
Source Project: shacl   Author: TopQuadrant   File: PathEvaluator.java    License: Apache License 2.0 5 votes vote down vote up
private ExtendedIterator<RDFNode> withDefaultValues(ExtendedIterator<RDFNode> base, RDFNode focusNode, NodeExpressionContext context) {
	if(isInverse || predicate == null || base.hasNext()) {
		return base;
	}
	else {
		Map<Node,NodeExpression> map = context.getShapesGraph().getDefaultValueNodeExpressionsMap(predicate);
		if(map.isEmpty()) {
			return base;
		}
		else {
			ExtendedIterator<RDFNode> result = WrappedIterator.emptyIterator();
			int count = 0;
			for(Resource type : JenaUtil.getAllTypes((Resource)focusNode)) {
				NodeExpression expr = map.get(type.asNode());
				if(expr != null) {
					result = result.andThen(expr.eval(focusNode, context));
					count++;
				}
			}
			if(count > 1) {
				// Filter out duplicates in case multiple sh:defaultValue expressions exist
				return DistinctExpression.distinct(result);
			}
			else {
				return result;
			}
		}
	}
}
 
Example #17
Source Project: Server.Java   Author: LinkedDataFragments   File: TriplePatternElementParserForJena.java    License: MIT License 5 votes vote down vote up
/**
 *
 * @param label
 * @param typeURI
 * @return
 */
@Override
public RDFNode createTypedLiteral( final String label,
                                   final String typeURI )
{
    final RDFDatatype dt = TypeMapper.getInstance()
                                     .getSafeTypeByName( typeURI );
    return ResourceFactory.createTypedLiteral( label, dt );
}
 
Example #18
Source Project: Server.Java   Author: LinkedDataFragments   File: SparqlBasedRequestProcessorForTPFs.java    License: MIT License 5 votes vote down vote up
/**
 *
 * @param request
 * @return
 * @throws IllegalArgumentException
 */
@Override
protected Worker getTPFSpecificWorker(
        final ITriplePatternFragmentRequest<RDFNode,String,String> request )
                                            throws IllegalArgumentException
{
    return new Worker( request );
}
 
Example #19
Source Project: shacl   Author: TopQuadrant   File: RuleUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static List<Shape> getShapesWithTargetNode(RDFNode focusNode, ShapesGraph shapesGraph) {
	// TODO: Not a particularly smart algorithm - walks all shapes that have rules
	List<Shape> shapes = new ArrayList<>();
	for(Shape shape : shapesGraph.getRootShapes()) {
		if(shape.getShapeResource().hasProperty(SH.rule) && shape.getShapeResource().hasTargetNode(focusNode)) {
			shapes.add(shape);
		}
	}
	return shapes;
}
 
Example #20
Source Project: shacl   Author: TopQuadrant   File: UnionExpression.java    License: 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 #21
Source Project: shacl   Author: TopQuadrant   File: SHFactory.java    License: 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 #22
Source Project: RDFUnit   Author: AKSW   File: ComponentParameterWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters(name= "{index}: Pattern: {0}")
public static Collection<Object[]> resources() throws RdfReaderException {
    Model model = RdfReaderFactory.createResourceReader(Resources.SHACL_CORE_CCs).read();
    Collection<Object[]> parameters = new ArrayList<>();
    for (RDFNode node: model.listObjectsOfProperty(SHACL.parameter).toList()) {
        parameters.add(new Object[] {node});
    }
    return parameters;
}
 
Example #23
Source Project: rdf2neo   Author: Rothamsted   File: RdfDataManager.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Gets a Cypher ID by applying an {@link DefaultIri2IdConverter ID conversion function} to an IRI taken from a 
 * {@link Resource} RDF/Jena node, or to a lexical value taken from a {@link Literal} RDF/Jena node. 
 * 
 * Helper method used in other methods in this class.
 */
protected String getCypherId ( RDFNode node, Function<String, String> idConverter )
{
	if ( node == null ) return null;
	
	String id = node.canAs ( Resource.class )
		? node.as ( Resource.class ).getURI ()
		: node.asLiteral ().getLexicalForm ();
				
	if ( idConverter != null ) id = idConverter.apply ( id );
	
	return id;
}
 
Example #24
Source Project: shacl   Author: TopQuadrant   File: ValidationEngine.java    License: 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;
}
 
Example #25
Source Project: shacl   Author: TopQuadrant   File: QualifiedValueShapeConstraintExecutor.java    License: 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 #26
Source Project: shacl   Author: TopQuadrant   File: SHACLObject.java    License: 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 #27
Source Project: hypergraphql   Author: semantic-integration   File: ModelContainer.java    License: 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 #28
Source Project: ontopia   Author: ontopia   File: RDFToTopicMapConverter.java    License: 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 #29
Source Project: hypergraphql   Author: semantic-integration   File: HGQLSchema.java    License: 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 #30
Source Project: hypergraphql   Author: semantic-integration   File: HGQLSchema.java    License: 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;
        }
    }
}