All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.aksw.jenax.arq.aggregation.AccGraph Maven / Gradle / Ivy

The newest version!
package org.aksw.jenax.arq.aggregation;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.aksw.jenax.arq.util.triple.TripleUtils;
import org.apache.jena.graph.Graph;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.Triple;
import org.apache.jena.sparql.core.Var;
import org.apache.jena.sparql.engine.binding.Binding;
import org.apache.jena.sparql.expr.NodeValue;
import org.apache.jena.sparql.function.FunctionEnv;
import org.apache.jena.sparql.graph.GraphFactory;
import org.apache.jena.sparql.modify.TemplateLib;
import org.apache.jena.sparql.syntax.Template;

public class AccGraph
    implements Acc
{
    protected Graph graph;
    protected Template template;
    protected Node reverse;

    public AccGraph(Template template) {
       this(template, NodeValue.FALSE.asNode());
    }

    public AccGraph(Template template, Node reverse) {
        this(GraphFactory.createDefaultGraph(), template, reverse);
    }

    public AccGraph(Graph graph, Template template, Node reverse) {
        super();
        this.graph = graph;
        this.template = template;
        this.reverse = reverse;
    }

    public static boolean isTrue(Object o) {
        boolean result = Boolean.TRUE.equals(o) || (o instanceof Number && ((Number)o).intValue() == 1);
        return result;
    }

    @Override
    public void accumulate(Binding binding, FunctionEnv env) {
        Map bNodeMap = new HashMap();
        Set triples = template.getTriples().stream()
                .map(t -> TemplateLib.subst(t, binding, bNodeMap))
                .collect(Collectors.toSet());

        //Node TRUE = NodeValue.TRUE.asNode();

        Node node = reverse.isVariable()
                ? binding.get((Var)reverse)
                : reverse
                ;

        boolean doReverse = node.isLiteral()
                ? isTrue(node.getLiteralValue())
                : false
                ;


        for(Triple triple : triples) {
            if(doReverse) {
                triple = TripleUtils.swap(triple);
            }

            graph.add(triple);
        }
    }

    @Override
    public Graph getValue() {
        return graph;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy