Java Code Examples for org.apache.jena.rdf.model.Resource#hasProperty()

The following examples show how to use org.apache.jena.rdf.model.Resource#hasProperty() . 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: ModelWrapper.java    From FCA-Map with GNU General Public License v3.0 6 votes vote down vote up
private void acquireInstances() {
  // XXX: remove instances of DBkWik:Image and SKOS:Concept, Template. Under consideration.
  ResIterator it = null;

  if (m_inferred) {
    it = m_inferred_model.listSubjects();
  } else {
    it = m_raw_model.listSubjects();
  }

  while (it.hasNext()) {
    Resource r = it.nextResource();
    if (DBkWik.ownAsResource(r) && !DBkWik.ownAsTemplate(r) &&
        !r.hasProperty(RDF.type, SKOS.Concept) &&
        !r.hasProperty(RDF.type, DBkWik.Image)) {
      m_instances.add(r);
    }
  }
}
 
Example 2
Source File: RuleEngine.java    From shacl with Apache License 2.0 6 votes vote down vote up
public void executeAll() throws InterruptedException {
	List<Shape> ruleShapes = new ArrayList<>();
	for(Shape shape : shapesGraph.getRootShapes()) {
		if(shape.getShapeResource().hasProperty(SH.rule)) {
			ruleShapes.add(shape);
		}
		else {
			for(Resource ps : JenaUtil.getResourceProperties(shape.getShapeResource(), SH.property)) {
				if(ps.hasProperty(SH.values)) {
					ruleShapes.add(shape);
					break;
				}
			}
		}
	}
	executeShapes(ruleShapes, null);
}
 
Example 3
Source File: SHACLFunctionDriver.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public DeclarativeFunctionFactory create(Resource shaclFunction) {
	if(jsPreferred) {
		if(shaclFunction.hasProperty(SH.jsLibrary)) {
			return new SHACLJSARQFunction(shaclFunction.as(SHJSFunction.class));
		}
		else {
			return new SHACLSPARQLARQFunction(shaclFunction.as(SHSPARQLFunction.class));
		}
	}
	else if(shaclFunction.hasProperty(SH.ask) || shaclFunction.hasProperty(SH.select)) {
		return new SHACLSPARQLARQFunction(shaclFunction.as(SHSPARQLFunction.class));
	}
	else {
		return new SHACLJSARQFunction(shaclFunction.as(SHJSFunction.class));
	}
}
 
Example 4
Source File: SHACLUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static SHPropertyShape getPropertyConstraintAtClass(Resource cls, Property predicate) {
	for(Resource c : JenaUtil.getAllSuperClassesStar(cls)) {
		for(Resource arg : JenaUtil.getResourceProperties(c, SH.property)) {
			if(arg.hasProperty(SH.path, predicate)) {
				return SHFactory.asPropertyShape(arg);
			}
		}
	}
	return null;
}
 
Example 5
Source File: SHACLUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static SHParameter getParameterAtClass(Resource cls, Property predicate) {
	for(Resource c : JenaUtil.getAllSuperClassesStar(cls)) {
		for(Resource arg : JenaUtil.getResourceProperties(c, SH.parameter)) {
			if(arg.hasProperty(SH.path, predicate)) {
				return SHFactory.asParameter(arg);
			}
		}
	}
	return null;
}
 
Example 6
Source File: PrefixUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static String getNamespace(Resource ontology, String prefix) {
	for(Resource declaration : JenaUtil.getResourceProperties(ontology, SH.declare)) {
		if(declaration.hasProperty(SH.prefix, prefix)) {
			return JenaUtil.getStringProperty(declaration, SH.namespace);
		}
	}
	return null;
}
 
Example 7
Source File: Validate.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void run(String[] args) throws IOException {
	Model dataModel = getDataModel(args);
	Model shapesModel = getShapesModel(args);
	if(shapesModel == null) {
		shapesModel = dataModel;
	}
	Resource report = ValidationUtil.validateModel(dataModel, shapesModel, true);
	report.getModel().write(System.out, FileUtils.langTurtle);

	if(report.hasProperty(SH.conforms, JenaDatatypes.FALSE)) {
		// See https://github.com/TopQuadrant/shacl/issues/56
		System.exit(1);
	}
}
 
Example 8
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 9
Source File: SHACLPaths.java    From shacl with Apache License 2.0 5 votes vote down vote up
private static void appendPathBlankNode(StringBuffer sb, Resource path, String separator) {
	if(path.hasProperty(RDF.first)) {
		Iterator<RDFNode> it = path.as(RDFList.class).iterator();
		while(it.hasNext()) {
			Resource item = (Resource) it.next();
			appendNestedPath(sb, item, SEQUENCE_PATH_SEPARATOR);
			if(it.hasNext()) {
				sb.append(" ");
				sb.append(separator);
				sb.append(" ");
			}
		}
	}
	else if(path.hasProperty(SH.inversePath)) {
		sb.append("^");
		if(path.getProperty(SH.inversePath).getObject().isAnon()) {
			sb.append("(");
			appendPath(sb, path.getPropertyResourceValue(SH.inversePath));
			sb.append(")");
		}
		else {
			appendPath(sb, path.getPropertyResourceValue(SH.inversePath));
		}
	}
	else if(path.hasProperty(SH.alternativePath)) {
		appendNestedPath(sb, path.getPropertyResourceValue(SH.alternativePath), ALTERNATIVE_PATH_SEPARATOR);
	}
	else if(path.hasProperty(SH.zeroOrMorePath)) {
		appendNestedPath(sb, path.getPropertyResourceValue(SH.zeroOrMorePath), SEQUENCE_PATH_SEPARATOR);
		sb.append("*");
	}
	else if(path.hasProperty(SH.oneOrMorePath)) {
		appendNestedPath(sb, path.getPropertyResourceValue(SH.oneOrMorePath), SEQUENCE_PATH_SEPARATOR);
		sb.append("+");
	}
	else if(path.hasProperty(SH.zeroOrOnePath)) {
		appendNestedPath(sb, path.getPropertyResourceValue(SH.zeroOrOnePath), SEQUENCE_PATH_SEPARATOR);
		sb.append("?");
	}
}
 
Example 10
Source File: AbstractJSExecutor.java    From shacl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private void createValidationResultFromJSObject(ValidationEngine engine, Constraint constraint, RDFNode focusNode,
		Resource messageHolder, QuerySolution bindings, Object ro) {
	Resource result = createValidationResult(engine, constraint, focusNode);
	if(ro instanceof Map) {
		Object value = ((Map)ro).get("value");
		if(value instanceof JSTerm) {
			Node resultValueNode = JSFactory.getNode(value);
			if(resultValueNode != null) {
				result.addProperty(SH.value, result.getModel().asRDFNode(resultValueNode));
			}
		}
		Object message = ((Map)ro).get("message");
		if(message instanceof String) {
			result.addProperty(SH.resultMessage, (String)message);
		}
		Object path = ((Map)ro).get("path");
		if(path != null) {
			Node pathNode = JSFactory.getNode(path);
			if(pathNode != null && pathNode.isURI()) {
				result.addProperty(SH.resultPath, result.getModel().asRDFNode(pathNode));
			}
		}
	}
	else if(ro instanceof String) {
		result.addProperty(SH.resultMessage, (String)ro);
	}
	if(!result.hasProperty(SH.resultMessage)) {
		addDefaultMessages(engine, constraint, messageHolder, constraint.getComponent(), result, bindings, ro instanceof Map ? (Map)ro : null);
	}
}
 
Example 11
Source File: TestExecutionReader.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
private Collection<TestCaseResult> getResults(Resource resource, TestCaseExecutionType executionType) {
    Resource typeToSearch = null;
    ElementReader<? extends TestCaseResult> reader = null;
    // Results
    switch (executionType) {
        case statusTestCaseResult:
            typeToSearch = RDFUNITv.StatusTestCaseResult;
            reader = StatusTestCaseResultReader.create();
            break;
        case aggregatedTestCaseResult:
            typeToSearch = RDFUNITv.AggregatedTestResult;
            reader = AggregatedTestCaseResultReader.create();
            break;
        case shaclTestCaseResult:
            typeToSearch = SHACL.ValidationResult;
            reader = ShaclTestCaseResultReader.create();
            break;
        case shaclLiteTestCaseResult:
            typeToSearch = SHACL.ValidationResult;
            reader = ShaclLiteTestCaseResultReader.create();
            break;
        default:
            throw new IllegalArgumentException("unsupported execution type: " + executionType.toString());
    }
    checkNotNull(typeToSearch);
    checkNotNull(reader);


    Collection<TestCaseResult> results = new ArrayList<>();
    for (Resource r: resource.getModel().listResourcesWithProperty(RDF.type, typeToSearch).toList()) {
        if (r.hasProperty(PROV.wasGeneratedBy, resource)) {
            results.add(reader.read(r));
        }
    }

    return results;
}
 
Example 12
Source File: RDFLabels.java    From shacl with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the label for a given Resource.
 * @param resource  the Resource to get the label of
 * @return the label (never null)
 */
public String getLabel(Resource resource) {
	if(resource.isURIResource() && resource.getModel() != null) {
		String qname = resource.getModel().qnameFor(resource.getURI());
		if(qname != null) {
			return qname;
		}
		else {
			return "<" + resource.getURI() + ">";
		}
	}
	else if(resource.isAnon() && resource.getModel() != null && resource.hasProperty(RDF.first)) {
		StringBuffer buffer = new StringBuffer("[");
		Iterator<RDFNode> members = resource.as(RDFList.class).iterator();
		while(members.hasNext()) {
			RDFNode member = members.next();
			buffer.append(RDFLabels.get().getNodeLabel(member));
			if(members.hasNext()) {
				buffer.append(", ");
			}
		}
		buffer.append("]");
		return buffer.toString();
	}
	else if(resource.isAnon()) {
		return getBlankNodeLabel(resource);
	}
	else {
		return resource.toString();
	}
}
 
Example 13
Source File: BatchShapeTargetReader.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
private List<ShapeTarget> collectImplicitClassTarget(Resource resource) {
    if (resource.hasProperty(RDF.type, RDFS.Class) || resource.hasProperty(RDF.type, OWL.Class)) {
        return Collections.singletonList(
                ShapeTargetCore.create(ShapeTargetType.ClassTarget, resource
        ));
    } else {
        return Collections.emptyList();
    }
}
 
Example 14
Source File: FunctionTestCaseType.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Model results) {
	Resource testCase = getResource();
	
	FunctionRegistry oldFR = FunctionRegistry.get();
	CurrentThreadFunctionRegistry threadFR = new CurrentThreadFunctionRegistry(oldFR);
	FunctionRegistry.set(ARQ.getContext(), threadFR);
	CurrentThreadFunctions old = CurrentThreadFunctionRegistry.register(testCase.getModel());

	try {
		for(TestCaseContextFactory contextFactory : contextFactories) {
			TestCaseContext context = contextFactory.createContext();
			String expression = JenaUtil.getStringProperty(testCase, DASH.expression);
			Statement expectedResultS = testCase.getProperty(DASH.expectedResult);
			String queryString = "SELECT (" + expression + " AS ?result) WHERE {}";
			Query query = ARQFactory.get().createQuery(testCase.getModel(), queryString);
			context.setUpTestContext();
			try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, testCase.getModel())) {
			    ResultSet rs = qexec.execSelect();
			    if(!rs.hasNext()) {
			        if(expectedResultS != null) {
			            createFailure(results,
			                          "Expression returned no result, but expected: " + expectedResultS.getObject(),
			                          context);
			            return;
			        }
			    }
			    else {
			        RDFNode actual = rs.next().get("result");
			        if(expectedResultS == null) {
			            if(actual != null) {
			                createFailure(results,
			                              "Expression returned a result, but none expected: " + actual, context);
			                return;
			            }
			        }
			        else if(testCase.hasProperty(DASH.expectedResultIsTTL, JenaDatatypes.TRUE)) {
			        	Graph expectedGraph = parseGraph(expectedResultS.getObject());
			        	Graph actualGraph = parseGraph(actual);
			        	if(!expectedGraph.isIsomorphicWith(actualGraph)) {
				            createFailure(results,
			                          "Mismatching result graphs. Expected: " + expectedResultS.getObject() + ". Found: " + actual, context);
				            return;
			        	}
			        }
			        else if(!expectedResultS.getObject().equals(actual)) {
			            createFailure(results,
			                          "Mismatching result. Expected: " + expectedResultS.getObject() + ". Found: " + actual, context);
			            return;
			        }
			    }
			}
			finally {
				context.tearDownTestContext();
			}
		}
	}
	finally {
		CurrentThreadFunctionRegistry.unregister(old);
		FunctionRegistry.set(ARQ.getContext(), oldFR);
	}
	
	createResult(results, DASH.SuccessTestCaseResult);
}
 
Example 15
Source File: Skolemizer.java    From Processor with Apache License 2.0 4 votes vote down vote up
public SortedSet<ClassPrecedence> match(Ontology ontology, Resource resource, Property property, int level)
{
    if (ontology == null) throw new IllegalArgumentException("Ontology cannot be null");
    if (resource == null) throw new IllegalArgumentException("Resource cannot be null");
    if (property == null) throw new IllegalArgumentException("Property cannot be null");

    SortedSet<ClassPrecedence> matchedClasses = new TreeSet<>();
    ResIterator it = ontology.getOntModel().listResourcesWithProperty(LDT.path);
    try
    {
        while (it.hasNext())
        {
            Resource ontClassRes = it.next();
            OntClass ontClass = ontology.getOntModel().getOntResource(ontClassRes).asClass();
            // only match templates defined in this ontology - maybe reverse loops?
            if (ontClass.getIsDefinedBy() != null && ontClass.getIsDefinedBy().equals(ontology) &&
                    resource.hasProperty(property, ontClass))
            {
                ClassPrecedence precedence = new ClassPrecedence(ontClass, level * -1);
                if (log.isTraceEnabled()) log.trace("Resource {} matched OntClass {}", resource, ontClass);
                matchedClasses.add(precedence);
            } 
        }
    }
    finally
    {
        it.close();
    }

    ExtendedIterator<OntResource> imports = ontology.listImports();
    try
    {
        while (imports.hasNext())
        {
            OntResource importRes = imports.next();
            if (importRes.canAs(Ontology.class))
            {
                Ontology importedOntology = importRes.asOntology();
                // traverse imports recursively
                Set<ClassPrecedence> matchedImportClasses = match(importedOntology, resource, property, level + 1);
                matchedClasses.addAll(matchedImportClasses);
            }
        }
    }
    finally
    {
        imports.close();
    }
    
    return matchedClasses;
}
 
Example 16
Source File: SHFactory.java    From shacl with Apache License 2.0 4 votes vote down vote up
public static boolean isParameter(Resource resource) {
	return resource.hasProperty(RDF.type, SH.Parameter) ||
			(!resource.hasProperty(RDF.type) && resource.getModel().contains(null, SH.parameter, resource));
}
 
Example 17
Source File: SHFactory.java    From shacl with Apache License 2.0 4 votes vote down vote up
public static boolean isPropertyShape(Resource resource) {
	return resource.hasProperty(RDF.type, SH.PropertyShape) ||
			resource.getModel().contains(null, SH.property, resource);
}
 
Example 18
Source File: SPARQLTargetLanguage.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
public boolean canHandle(Resource executable) {
	return executable.hasProperty(SH.select) && ExecutionPlatform.canExecute(executable);
}
 
Example 19
Source File: ClassesCache.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
public boolean test(Resource instance) {
	return instance.hasProperty(RDF.type, cls);
}
 
Example 20
Source File: TestCaseType.java    From shacl with Apache License 2.0 2 votes vote down vote up
/**
 * Can be overridden to check the properties of the resource
 * and return false if it is to be excluded from the list
 * of cases to test.
 */
protected boolean filterTestCase(Resource possibleTestCase) {
	return !possibleTestCase.hasProperty(SH.deactivated, JenaDatatypes.TRUE);
}