use of org.apache.jena.shacl.engine.ValidationContext in project jena by apache.
the class ShNot method validate.
@Override
public ReportItem validate(ValidationContext vCxt, Graph data, Node node) {
ValidationContext vCxt2 = ValidationContext.create(vCxt);
ValidationProc.execValidateShape(vCxt2, data, other, node);
boolean innerConforms = vCxt2.generateReport().conforms();
if (!innerConforms)
return null;
String msg = "Not[" + other + "] at focusNode " + displayStr(node);
return new ReportItem(msg, node);
}
use of org.apache.jena.shacl.engine.ValidationContext in project jena by apache.
the class ShXone method validate.
@Override
public ReportItem validate(ValidationContext vCxt, Graph data, Node node) {
int c = 0;
for (Shape sh : others) {
ValidationContext vCxt2 = ValidationContext.create(vCxt);
ValidationProc.execValidateShape(vCxt2, data, sh, node);
boolean innerConforms = vCxt2.generateReport().conforms();
if (innerConforms) {
c++;
// Choice: count all vs break as soon as error detected
// if ( c > 1 )
// break;
}
}
if (c == 1)
return null;
String msg = toString() + " has " + c + " conforming shapes at focusNode " + displayStr(node);
return new ReportItem(msg, node);
}
use of org.apache.jena.shacl.engine.ValidationContext in project webofneeds by researchstudio-sat.
the class Shacl2JavaInstanceFactory method instantiate.
/**
* Creates all instances for the given node / shape combination.
*
* @param node may be null, in which case all target nodes of the shape are
* chosen.
* @param shape
* @return the set of nodes reached during instantiation that have not been
* instantiated yet
*/
private Set<DataNodeAndShapes> instantiate(Node node, Shape shape, boolean forceApplyShape, InstantiationContext ctx) {
if (shape.getShapeNode().isBlank()) {
if (node == null) {
if (logger.isDebugEnabled()) {
logger.debug("Not instantiating entity for shape {}", shape.getShapeNode().getBlankNodeLabel());
}
} else {
throw new IllegalArgumentException(String.format("Cannot instantiate entity for node %s: shape %s is a blank node", node.getLocalName(), shape.getShapeNode().getBlankNodeLabel()));
}
}
Collection<Node> focusNodes;
if (node != null) {
if (!forceApplyShape) {
if (!isFocusNode(shape, node, ctx.getData())) {
return Collections.emptySet();
}
}
if (ctx.hasInstanceForFocusNode(node) && !ctx.isNewShapeForFocusNode(node, shape)) {
return Collections.emptySet();
}
if (logger.isDebugEnabled()) {
logger.debug("processing node {} with shape {}", node, shape);
}
focusNodes = Collections.singleton(node);
} else {
focusNodes = focusNodes(ctx.getData(), shape);
}
if (focusNodes.isEmpty()) {
return Collections.emptySet();
}
final Set<Node> finalFocusNodes = removeNodesInstantiatedInBaseContext(focusNodes).stream().filter(fnode -> {
// check if focusnode conforms to shape
ValidationContext vCtx = ctx.newValidationContext();
VLib.validateShape(vCtx, ctx.getData(), shape, fnode);
if (vCtx.hasViolation()) {
if (logger.isDebugEnabled()) {
logger.debug("skipping node {} as it does not conform to shape {}", fnode, shape.getShapeNode());
}
return false;
} else {
if (logger.isDebugEnabled()) {
logger.debug("accepting node {} as it conforms to shape {}", fnode, shape.getShapeNode());
}
}
return true;
}).collect(Collectors.toSet());
String shapeURI = shape.getShapeNode().getURI();
Set<Class<?>> classesForShape = ctx.getClassesForShape(shapeURI);
if (classesForShape == null) {
if (logger.isDebugEnabled()) {
logger.debug("No class found to instantiate for shape {}.", shape.getShapeNode().getLocalName());
logger.debug("Instantiation context:");
logger.debug(ctx.getFormattedState());
}
throw new IllegalArgumentException(String.format("No class found to instantiate for shape %s, more information is logged on loglevel debug", shape.getShapeNode().getLocalName()));
}
Set ret = classesForShape.stream().map(classForShape -> {
// our shape might reference other shapes via sh:node (maybe through other
// operators such as sh:or)
// * we remember them for wiring
// * we return them as dependencies to instantiate
Set<Shape> allRelevantShapes = ShapeUtils.getNodeShapes((NodeShape) shape, shapes);
Map<Path, Set<PropertyShape>> propertyShapesPerPath = getPropertyShapesByPath(allRelevantShapes);
allRelevantShapes.add(shape);
return finalFocusNodes.parallelStream().map(focusNode -> {
try {
Object instance = null;
if (logger.isDebugEnabled()) {
logger.debug("attempting to instantiate focus node {} with shape {}", focusNode, shape.getShapeNode());
}
instance = instantiate(shape, shapeURI, focusNode, classForShape, ctx);
if (instance == null) {
// maybe another shape works better
return Collections.emptySet();
}
ctx.addInstanceForFocusNode(focusNode, instance);
ctx.setFocusNodeForInstance(instance, focusNode);
ctx.setClassForInstance(instance, classForShape);
ctx.addShapesForFocusNode(focusNode, allRelevantShapes);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(String.format("Cannot instantiate %s for shape %s", classForShape.getName(), shape.getShapeNode().getLocalName()) + ": no parameterless constructor found", e);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
throw new IllegalArgumentException(String.format("Cannot instantiate %s for shape %s - %s: %s", classForShape.getName(), shape.getShapeNode().getLocalName(), e.getClass().getSimpleName(), e.getMessage()), e);
}
if (logger.isDebugEnabled()) {
logger.debug("Collecting dependencies of focus node {}", focusNode);
}
return propertyShapesPerPath.entrySet().parallelStream().map(pathToShapes -> {
Path path = pathToShapes.getKey();
Set<PropertyShape> propertyShapes = pathToShapes.getValue();
if (logger.isDebugEnabled()) {
logger.debug("\tcollecting new focus nodes via path {} ", path);
}
Set<Node> valueNodes = ShaclPaths.valueNodes(ctx.getData(), focusNode, path);
if (valueNodes.isEmpty()) {
return Collections.emptySet();
}
return valueNodes.stream().map(valueNode -> propertyShapes.stream().map(ctx::getNodeShapesForPropertyShape).map(nodeShapeNodes -> new DataNodeAndShapes(valueNode, nodeShapeNodes)).collect(Collectors.toSet())).reduce(CollectionUtils::union).orElse(Collections.emptySet());
}).reduce(CollectionUtils::union).orElse(Collections.emptySet());
}).reduce(CollectionUtils::union).orElse(Collections.emptySet());
}).reduce(CollectionUtils::union).orElse(Collections.emptySet());
return ret;
}
use of org.apache.jena.shacl.engine.ValidationContext in project webofneeds by researchstudio-sat.
the class IndividualsGenerator method generateIndividuals.
private TypeSpec generateIndividuals(Shapes shapes, Shacl2JavaConfig config) {
Set<String> individualNames = new HashSet<>();
ResettableErrorHandler err = new ResettableErrorHandler();
ValidationContext vCtx = ValidationContext.create(shapes, shapes.getGraph(), err);
TypeSpec.Builder individualsTypeBuilder = TypeSpec.classBuilder("Individuals").addModifiers(PUBLIC).addAnnotation(AnnotationSpec.builder(Individuals.class).build());
StreamSupport.stream(Spliterators.spliteratorUnknownSize(shapes.iteratorAll(), Spliterator.ORDERED), false).distinct().forEach(shape -> {
// find focus nodes in the shapes graph itself
Collection<Node> focusNodes = focusNodes(shapes.getGraph(), shape);
for (Node focusNode : focusNodes) {
if (focusNode.isBlank() || focusNode.isLiteral()) {
continue;
}
err.reset();
VLib.validateShape(vCtx, shapes.getGraph(), shape, focusNode);
if (err.isError() || err.isFatal()) {
continue;
}
String name = NameUtils.enumConstantName(focusNode.getURI());
if (individualNames.contains(name)) {
name = NameUtils.enumConstantName(focusNode.getURI()) + "_" + NameUtils.enumConstantName(NameUtils.classNameForShape(shape, config));
if (individualNames.contains(name)) {
throw new IllegalStateException("Name clash while creating individual: " + name);
}
}
individualNames.add(name);
String typeName = NameUtils.classNameForShape(shape, config);
ClassName type = ClassName.get(config.getPackageName(), typeName);
// remember so we can inject individuals into shape-classes
individualClassNames.put(focusNode, type);
FieldSpec fieldSpec = FieldSpec.builder(type, name).addModifiers(PUBLIC, STATIC, FINAL).addAnnotation(AnnotationSpec.builder(ClassName.get(Individual.class)).addMember("value", "$S", focusNode.getURI()).build()).addAnnotation(AnnotationSpec.builder(ShapeNode.class).addMember("value", "{ $S }", shape.getShapeNode().getURI()).build()).initializer("new $T($S)", type, focusNode.getURI()).build();
individualsTypeBuilder.addField(fieldSpec);
}
});
return individualsTypeBuilder.build();
}
Aggregations