Search in sources :

Example 1 with CollectionUtils

use of won.shacl2java.util.CollectionUtils in project webofneeds by researchstudio-sat.

the class Shacl2JavaInstanceFactory method instantiateAll.

private void instantiateAll(InstantiationContext ctx) {
    Set<DataNodeAndShapes> toInstantiate = null;
    while (toInstantiate == null || toInstantiate.size() > 0) {
        if (toInstantiate == null) {
            Set<Shape> shapeSet = new HashSet();
            Iterator<Shape> it = shapes.iteratorAll();
            while (it.hasNext()) {
                shapeSet.add(it.next());
            }
            toInstantiate = shapeSet.stream().map(shape -> {
                return instantiate(null, shape, false, ctx);
            }).reduce(CollectionUtils::union).orElseGet(() -> Collections.emptySet());
            toInstantiate = deduplicate(toInstantiate);
        } else {
            toInstantiate = toInstantiate.parallelStream().map(dataNodeAndShapes -> {
                if (dataNodeAndShapes.getShapeNodes().isEmpty()) {
                    return StreamSupport.stream(shapes.spliterator(), true).map(shape -> instantiate(dataNodeAndShapes.getDataNode(), shape, false, ctx)).reduce(CollectionUtils::union).orElseGet(() -> Collections.emptySet());
                } else {
                    return dataNodeAndShapes.getShapeNodes().parallelStream().map(shapeNode -> instantiate(dataNodeAndShapes.getDataNode(), shapes.getShape(shapeNode), true, ctx)).reduce(CollectionUtils::union).orElseGet(() -> Collections.emptySet());
                }
            }).reduce(CollectionUtils::union).orElseGet(() -> Collections.emptySet());
            toInstantiate = deduplicate(toInstantiate);
        }
    }
    ctx.getInstancesByNode().stream().forEach(entry -> {
        Node node = entry.getKey();
        Set<Object> instances = entry.getValue();
        for (Object instance : instances) {
            if (logger.isDebugEnabled()) {
                logger.debug("wiring dependencies of instance {} ", node);
            }
            wireDependencies(instance, ctx);
        }
    });
}
Also used : PropertyPath(won.shacl2java.annotation.PropertyPath) java.util(java.util) NodeFactory(org.apache.jena.graph.NodeFactory) PathParser(org.apache.jena.sparql.path.PathParser) InstantiationContext(won.shacl2java.instantiation.InstantiationContext) ValidationContext(org.apache.jena.shacl.engine.ValidationContext) LoggerFactory(org.slf4j.LoggerFactory) Graph(org.apache.jena.graph.Graph) NameUtils.setterNameForField(won.shacl2java.util.NameUtils.setterNameForField) PropertyShape(org.apache.jena.shacl.parser.PropertyShape) Path(org.apache.jena.sparql.path.Path) NameUtils.adderNameForFieldNameInPlural(won.shacl2java.util.NameUtils.adderNameForFieldNameInPlural) ShapeUtils(won.shacl2java.util.ShapeUtils) Shape(org.apache.jena.shacl.parser.Shape) StreamSupport(java.util.stream.StreamSupport) NameUtils(won.shacl2java.util.NameUtils) URI(java.net.URI) NodeShape(org.apache.jena.shacl.parser.NodeShape) java.lang.reflect(java.lang.reflect) Logger(org.slf4j.Logger) VLib.focusNodes(org.apache.jena.shacl.validation.VLib.focusNodes) MethodHandles(java.lang.invoke.MethodHandles) PrefixMapping(org.apache.jena.shared.PrefixMapping) Individuals(won.shacl2java.annotation.Individuals) CollectionUtils(won.shacl2java.util.CollectionUtils) Collectors(java.util.stream.Collectors) ShaclPaths(org.apache.jena.shacl.engine.ShaclPaths) VLib(org.apache.jena.shacl.validation.VLib) DerivedInstantiationContext(won.shacl2java.instantiation.DerivedInstantiationContext) ShapeNode(won.shacl2java.annotation.ShapeNode) GraphEntity(won.shacl2java.runtime.model.GraphEntity) Stream(java.util.stream.Stream) VLib.isFocusNode(org.apache.jena.shacl.validation.VLib.isFocusNode) Individual(won.shacl2java.annotation.Individual) DataNodeAndShapes(won.shacl2java.instantiation.DataNodeAndShapes) Node(org.apache.jena.graph.Node) io.github.classgraph(io.github.classgraph) Shapes(org.apache.jena.shacl.Shapes) GraphFactory(org.apache.jena.sparql.graph.GraphFactory) PropertyShape(org.apache.jena.shacl.parser.PropertyShape) Shape(org.apache.jena.shacl.parser.Shape) NodeShape(org.apache.jena.shacl.parser.NodeShape) ShapeNode(won.shacl2java.annotation.ShapeNode) VLib.isFocusNode(org.apache.jena.shacl.validation.VLib.isFocusNode) Node(org.apache.jena.graph.Node) DataNodeAndShapes(won.shacl2java.instantiation.DataNodeAndShapes) CollectionUtils(won.shacl2java.util.CollectionUtils)

Example 2 with CollectionUtils

use of won.shacl2java.util.CollectionUtils 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;
}
Also used : PropertyPath(won.shacl2java.annotation.PropertyPath) java.util(java.util) NodeFactory(org.apache.jena.graph.NodeFactory) PathParser(org.apache.jena.sparql.path.PathParser) InstantiationContext(won.shacl2java.instantiation.InstantiationContext) ValidationContext(org.apache.jena.shacl.engine.ValidationContext) LoggerFactory(org.slf4j.LoggerFactory) Graph(org.apache.jena.graph.Graph) NameUtils.setterNameForField(won.shacl2java.util.NameUtils.setterNameForField) PropertyShape(org.apache.jena.shacl.parser.PropertyShape) Path(org.apache.jena.sparql.path.Path) NameUtils.adderNameForFieldNameInPlural(won.shacl2java.util.NameUtils.adderNameForFieldNameInPlural) ShapeUtils(won.shacl2java.util.ShapeUtils) Shape(org.apache.jena.shacl.parser.Shape) StreamSupport(java.util.stream.StreamSupport) NameUtils(won.shacl2java.util.NameUtils) URI(java.net.URI) NodeShape(org.apache.jena.shacl.parser.NodeShape) java.lang.reflect(java.lang.reflect) Logger(org.slf4j.Logger) VLib.focusNodes(org.apache.jena.shacl.validation.VLib.focusNodes) MethodHandles(java.lang.invoke.MethodHandles) PrefixMapping(org.apache.jena.shared.PrefixMapping) Individuals(won.shacl2java.annotation.Individuals) CollectionUtils(won.shacl2java.util.CollectionUtils) Collectors(java.util.stream.Collectors) ShaclPaths(org.apache.jena.shacl.engine.ShaclPaths) VLib(org.apache.jena.shacl.validation.VLib) DerivedInstantiationContext(won.shacl2java.instantiation.DerivedInstantiationContext) ShapeNode(won.shacl2java.annotation.ShapeNode) GraphEntity(won.shacl2java.runtime.model.GraphEntity) Stream(java.util.stream.Stream) VLib.isFocusNode(org.apache.jena.shacl.validation.VLib.isFocusNode) Individual(won.shacl2java.annotation.Individual) DataNodeAndShapes(won.shacl2java.instantiation.DataNodeAndShapes) Node(org.apache.jena.graph.Node) io.github.classgraph(io.github.classgraph) Shapes(org.apache.jena.shacl.Shapes) GraphFactory(org.apache.jena.sparql.graph.GraphFactory) PropertyPath(won.shacl2java.annotation.PropertyPath) Path(org.apache.jena.sparql.path.Path) PropertyShape(org.apache.jena.shacl.parser.PropertyShape) PropertyShape(org.apache.jena.shacl.parser.PropertyShape) Shape(org.apache.jena.shacl.parser.Shape) NodeShape(org.apache.jena.shacl.parser.NodeShape) ShapeNode(won.shacl2java.annotation.ShapeNode) VLib.isFocusNode(org.apache.jena.shacl.validation.VLib.isFocusNode) Node(org.apache.jena.graph.Node) DataNodeAndShapes(won.shacl2java.instantiation.DataNodeAndShapes) ValidationContext(org.apache.jena.shacl.engine.ValidationContext)

Aggregations

io.github.classgraph (io.github.classgraph)2 MethodHandles (java.lang.invoke.MethodHandles)2 java.lang.reflect (java.lang.reflect)2 URI (java.net.URI)2 java.util (java.util)2 Collectors (java.util.stream.Collectors)2 Stream (java.util.stream.Stream)2 StreamSupport (java.util.stream.StreamSupport)2 Graph (org.apache.jena.graph.Graph)2 Node (org.apache.jena.graph.Node)2 NodeFactory (org.apache.jena.graph.NodeFactory)2 Shapes (org.apache.jena.shacl.Shapes)2 ShaclPaths (org.apache.jena.shacl.engine.ShaclPaths)2 ValidationContext (org.apache.jena.shacl.engine.ValidationContext)2 NodeShape (org.apache.jena.shacl.parser.NodeShape)2 PropertyShape (org.apache.jena.shacl.parser.PropertyShape)2 Shape (org.apache.jena.shacl.parser.Shape)2 VLib (org.apache.jena.shacl.validation.VLib)2 VLib.focusNodes (org.apache.jena.shacl.validation.VLib.focusNodes)2 VLib.isFocusNode (org.apache.jena.shacl.validation.VLib.isFocusNode)2