org.apache.jena.sparql.function.FunctionEnv Java Examples

The following examples show how to use org.apache.jena.sparql.function.FunctionEnv. 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: IsValidForDatatypeFunction.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeValue exec(Node literalNode, Node datatypeNode, FunctionEnv env) {
	
	if(literalNode == null || !literalNode.isLiteral()) {
		throw new ExprEvalException();
	}
	String lex = literalNode.getLiteralLexicalForm();
	
	if(!datatypeNode.isURI()) {
		throw new ExprEvalException();
	}
	RDFDatatype datatype = TypeMapper.getInstance().getTypeByName(datatypeNode.getURI());
	
	if(datatype == null) {
		return NodeValue.TRUE;
	}
	else {
		boolean valid = datatype.isValid(lex);
		return NodeValue.makeBoolean(valid);
	}
}
 
Example #2
Source File: IteratorStreamFunctionBase.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public final void exec(
        final Binding binding,
        final ExprList args,
        final FunctionEnv env,
        final Consumer<List<List<NodeValue>>> collectionListNodeValue) {

    this.env = env;
    if (args == null) {
        throw new ARQInternalErrorException("IteratorFunctionBase:"
                + " Null args list");
    }

    List<NodeValue> evalArgs = new ArrayList<>();
    for (Expr e : args) {
        try {
            NodeValue x = e.eval(binding, env);
            evalArgs.add(x);
        } catch (ExprEvalException ex) {
            LOG.trace("Cannot evaluate node " + e + ": " + ex.getMessage());
            evalArgs.add(null);
        }
    }
    exec(evalArgs, collectionListNodeValue);
}
 
Example #3
Source File: JenaUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
private static Node invokeFunction(Resource function, ExprList args, Dataset dataset) {

		if (dataset == null) {
	        dataset = ARQFactory.get().getDataset(ModelFactory.createDefaultModel());
	    }
		
		E_Function expr = new E_Function(function.getURI(), args);
		DatasetGraph dsg = dataset.asDatasetGraph();
		Context cxt = ARQ.getContext().copy();
		cxt.set(ARQConstants.sysCurrentTime, NodeFactoryExtra.nowAsDateTime());
		FunctionEnv env = new ExecutionContext(cxt, dsg.getDefaultGraph(), dsg, null);
		try {
			NodeValue r = expr.eval(BindingRoot.create(), env);
			if(r != null) {
				return r.asNode();
			}
		}
		catch(ExprEvalException ex) {
		}
		return null;
	}
 
Example #4
Source File: EvalUtils.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
/**
 * The query name may be an expression, which evaluates differently
 * depending on the input bindings. This method groups the bindings for
 * which the query name evaluation is the same.
 *
 * @param expr the expression for the query name
 * @param bindings
 * @param env
 * @return
 */
public static Map<String, List<Binding>> splitBindingsForQuery(
        final Expr expr,
        final List<Binding> bindings,
        final FunctionEnv env) {
    final Map<String, List<Binding>> calls = new HashMap<>();
    for (Binding binding : bindings) {
        final Node n = eval(expr, binding, env);
        if (n == null) {
            continue;
        }
        if (!n.isURI()) {
            LOG.warn("Name of sub query resolved to something else than a"
                    + " URI: " + n);
            continue;
        }
        String queryName = n.getURI();
        List<Binding> call = calls.get(queryName);
        if (call == null) {
            call = new ArrayList<>();
            calls.put(queryName, call);
        }
        call.add(binding);
    }
    return calls;
}
 
Example #5
Source File: BindPlan.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
protected final Binding exec(Binding binding, Context context) {
    LOG.debug("Start " + this);
    context.set(ARQConstants.sysCurrentTime, NodeFactoryExtra.nowAsDateTime());
    final FunctionEnv env = new FunctionEnvBase(context);
    try {
        final NodeValue n = expr.eval(binding, env);
        if (LOG.isTraceEnabled()) {
            LOG.trace("New binding " + var + " = " + LogUtils.compress(n.asNode()));
        }
        return BindingFactory.binding(binding, var, n.asNode());
    } catch(ExprEvalException ex) {
        LOG.trace("No evaluation for " + this + " " + ex.getMessage());
        return binding;
    }
}
 
Example #6
Source File: TemplatePlan.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
public void exec(List<Var> variables, List<Binding> values, Context context) {
	final IndentedWriter writer = ContextUtils.getTemplateOutput(context);
	boolean first = true;
	final FunctionEnv env = new FunctionEnvBase(context);
	String result;
	for(Iterator<Binding> it=values.iterator(); it.hasNext();) {
		Binding binding = it.next();
		if (first && before != null) {
			result = getExprEval(before, binding, context, env);
			writer.print(result);
		}
		if (!first && separator != null) {
			result = getExprEval(separator, binding, context, env);
			writer.print(result);
		}
		result = getExprEval(expr, binding, context, env);
		writer.print(result);
		first = false;
		if (!it.hasNext() && after != null) {
			result = getExprEval(after, binding, context, env);
			writer.print(result);
		}
		writer.flush();
	}
}
 
Example #7
Source File: CheckRegexSyntaxFunction.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeValue exec(Node regexNode, FunctionEnv env) {
	if(regexNode == null || !regexNode.isLiteral()) {
		return NodeValue.makeString("Invalid argument to spif:checkRegexSyntax: " + regexNode);
	}
	else {
		String str = regexNode.getLiteralLexicalForm();
		try {
			Pattern.compile(str);
		}
		catch(Exception ex) {
			return NodeValue.makeString(ex.getMessage());
		}
		throw new ExprEvalException(); // OK
	}
}
 
Example #8
Source File: ST_Decr.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) {
    if (args == null) {
        throw new ARQInternalErrorException("FunctionBase: Null args list");
    }
    if (args.size() != 0) {
        throw new ExprEvalException("Expecting zero argument");
    }
    IndentedWriter writer = ContextUtils.getTemplateOutput(env.getContext());
    if(writer != null) {
    	writer.decIndent();
    } else {
    	LOG.warn("calling st:decr() outside TEMPLATE context.");
    }
    return EMPTY_NODE;
}
 
Example #9
Source File: ST_Format.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
public NodeValue exec(List<NodeValue> args, FunctionEnv env) {
    if (args.size() < 1) {
        LOG.debug("Expecting at least one arguments.");
        throw new ExprEvalException("Expecting at least one arguments.");
    }
    final NodeValue format = args.get(0);
    if (!format.isIRI() && !format.isString() && !format.asNode().isLiteral()) {
        LOG.debug("First argument must be a URI or a String.");
        throw new ExprEvalException("First argument must be a URI or a String.");
    }

    Object[] params = new String[args.size() - 1];
    for (int i = 0; i < args.size() - 1; i++) {
        params[i] = args.get(i + 1).asUnquotedString();
    }
    try {
        String output = String.format(getString(format, env), params);
        return new NodeValueString(output);
    } catch (IllegalFormatException ex) {
        throw new ExprEvalException("Exception while executing st:format(" + args + ")");
    }
}
 
Example #10
Source File: ST_Incr.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) {
    if (args == null) {
        throw new ARQInternalErrorException("FunctionBase: Null args list");
    }
    if (args.size() != 0) {
        throw new ExprEvalException("Expecting zero argument");
    }
    IndentedWriter writer = ContextUtils.getTemplateOutput(env.getContext());
    if(writer != null) {
    	writer.incIndent();
    } else {
    	LOG.warn("calling st:incr() outside TEMPLATE context.");
    }
    return EMPTY_NODE;
}
 
Example #11
Source File: FUN_Property.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) {
    if (args == null) {
        throw new ARQInternalErrorException("FunctionBase: Null args list");
    }
    if (args.size() != 2) {
        throw new ExprEvalException("Expecting two argument");
    }
    NodeValue file = args.get(0).eval(binding, env);
    NodeValue propertyNode = args.get(1).eval(binding, env);
    if (!propertyNode.isString()) {
        throw new ExprEvalException("Second argument must be a string. Got " + propertyNode);
    }
    Properties properties;
    try {
        properties = getProperties(file, env);
    } catch (IOException ex) {
        throw new ExprEvalException("IOException while extracting properties document " + file, ex);
    }
    String prop = properties.getProperty(propertyNode.getString());
    if (prop == null) {
        throw new ExprEvalException("Property " + prop + " not found in properties document " + file);
    }
    return new NodeValueString(prop);
}
 
Example #12
Source File: IsValidLangTagFunction.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeValue exec(Node arg, FunctionEnv env) {
	if(arg == null || !arg.isLiteral()) {
		throw new ExprEvalException("Argument must be a (string) literal");
	}
	return NodeValue.makeBoolean(LangTag.check(arg.getLiteralLexicalForm()));
}
 
Example #13
Source File: ExpandPrefixedNameFunction.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) {
	if (args == null) {
		throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list");
	}
	if (args.size() != 1) {
		throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size());
	}
       return exec(args.get(0).eval(binding, env), env.getContext());
}
 
Example #14
Source File: AbstractFunction4.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeValue exec(Node[] nodes, FunctionEnv env) {
	Node arg1 = nodes.length > 0 ? nodes[0] : null;
	Node arg2 = nodes.length > 1 ? nodes[1] : null;
	Node arg3 = nodes.length > 2 ? nodes[2] : null;
	Node arg4 = nodes.length > 3 ? nodes[3] : null;
	return exec(arg1, arg2, arg3, arg4, env);
}
 
Example #15
Source File: CustomAggregate.java    From xcurator with Apache License 2.0 5 votes vote down vote up
/** Function called on each row in a group */
@Override
public void accumulate(Binding binding, FunctionEnv functionEnv) {
    ExprList exprList = agg.getExprList() ;
    for(Expr expr: exprList) {
        try {
            NodeValue nv = expr.eval(binding, functionEnv) ;
            // Evaluation succeeded.
            if ( nv.isLiteral())
                count ++ ;
        } catch (ExprEvalException ex) {}
    }
}
 
Example #16
Source File: AbstractFunction5.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeValue exec(Node[] nodes, FunctionEnv env) {
	Node arg1 = nodes.length > 0 ? nodes[0] : null;
	Node arg2 = nodes.length > 1 ? nodes[1] : null;
	Node arg3 = nodes.length > 2 ? nodes[2] : null;
	Node arg4 = nodes.length > 3 ? nodes[3] : null;
	Node arg5 = nodes.length > 4 ? nodes[4] : null;
	return exec(arg1, arg2, arg3, arg4, arg5, env);
}
 
Example #17
Source File: AbstractFunction6.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeValue exec(Node[] nodes, FunctionEnv env) {
	Node arg1 = nodes.length > 0 ? nodes[0] : null;
	Node arg2 = nodes.length > 1 ? nodes[1] : null;
	Node arg3 = nodes.length > 2 ? nodes[2] : null;
	Node arg4 = nodes.length > 3 ? nodes[3] : null;
	Node arg5 = nodes.length > 4 ? nodes[4] : null;
	Node arg6 = nodes.length > 5 ? nodes[5] : null;
	return exec(arg1, arg2, arg3, arg4, arg5, arg6, env);
}
 
Example #18
Source File: ExpandPrefixFunction.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) {
	if (args == null) {
		throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list");
	}
	if (args.size() != 1) {
		throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size());
	}
       return exec(args.get(0).eval(binding, env), env.getContext());
}
 
Example #19
Source File: AbstractFunction3.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeValue exec(Node[] nodes, FunctionEnv env) {
	Node arg1 = nodes.length > 0 ? nodes[0] : null;
	Node arg2 = nodes.length > 1 ? nodes[1] : null;
	Node arg3 = nodes.length > 2 ? nodes[2] : null;
	return exec(arg1, arg2, arg3, env);
}
 
Example #20
Source File: EvalUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static Node eval(
        final Expr expr,
        final Binding binding,
        final FunctionEnv env) {
    Objects.requireNonNull(expr);
    try {
        NodeValue node = expr.eval(binding, env);
        if (node.asNode().isConcrete()) {
            return node.asNode();
        }
    } catch (ExprEvalException ex) {
        LOG.trace("Exception while evaluating the expression " + expr + ":", ex);
    }
    return null;
}
 
Example #21
Source File: EvalUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static List<Node> eval(
        final ExprList exprs,
        final Binding binding,
        final FunctionEnv env) {
    Objects.requireNonNull(binding);
    Objects.requireNonNull(env);
    if (exprs == null) {
        return null;
    }
    final List<Node> nodes = new ArrayList<>();
    exprs.forEach((expr) -> {
        nodes.add(eval(expr, binding, env));
    });
    return nodes;
}
 
Example #22
Source File: EvalUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static List<List<Node>> eval(
        final ExprList exprs,
        final List<Binding> bindings,
        final FunctionEnv env) {
    final List<List<Node>> nodesList = new ArrayList<>();
    for (Binding binding : bindings) {
        List<Node> nodes = eval(exprs, binding, env);
        if (nodes != null) {
            nodesList.add(nodes);
        }
    }
    return nodesList;
}
 
Example #23
Source File: ST_Format.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) {
    final boolean isDebugStConcat = ContextUtils.isDebugStConcat(env.getContext());
    if (args == null) // The contract on the function interface is that this should not happen.
    {
        throw new ARQInternalErrorException("FunctionBase: Null args list");
    }

    List<NodeValue> evalArgs = new ArrayList<>();
    for (Expr e : args) {
        try {
            NodeValue x = e.eval(binding, env);
            evalArgs.add(x);
        } catch (Exception ex) {
            StringWriter sw = new StringWriter();
            ex.printStackTrace(new PrintWriter(sw));
            String message = String.format("Error executing st:format with expression %s and binding %s: %s", ExprUtils.fmtSPARQL(args), LogUtils.compress(binding).toString(), sw.toString());
            if (LOG.isDebugEnabled()) {
                LOG.debug(message, ex);
            }
            if (isDebugStConcat) {
                evalArgs.add(new NodeValueString(String.format("\n<<<<<<<<<< %s >>>>>>>>>>\n", message)));
            }
        }
    }

    NodeValue nv = exec(evalArgs, env);
    return nv;
}
 
Example #24
Source File: DatasetDeclarationPlan.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private String evalSourceURI(Binding binding, Context context, Expr sourceExpr) {
	if (binding == null) {
		throw new NullPointerException("No binding to evaluate the source expression " + sourceExpr);
	}
	try {
		FunctionEnv env = new FunctionEnvBase(context);
		NodeValue nodeValue = sourceExpr.eval(binding, env);
		if (!nodeValue.isIRI()) {
			throw new IllegalArgumentException("FROM source expression did not eval to a URI " + sourceExpr);
		}
		return nodeValue.asNode().getURI();
	} catch (ExprEvalException ex) {
		throw new IllegalArgumentException("Exception when evaluating the source expression " + sourceExpr, ex);
	}
}
 
Example #25
Source File: TemplatePlan.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private String getExprEval(Expr expr, Binding binding, Context context, FunctionEnv env) {
	NodeValue nv = null;
	try {
		nv = expr.eval(binding, env);
	} catch (ExprEvalException ex) {
		LOG.debug("Could not evaluate expression " + expr, ex);
	}
	if (nv == null) {
		return "";
	}
	if (!nv.isLiteral()) {
		LOG.debug("Expression did not evaluate as a literal " + expr + ", got :" + nv);
	}
	return nv.asNode().getLiteralLexicalForm();
}
 
Example #26
Source File: SelectQueryPartialCopyVisitor.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private String evalSourceURI(Binding binding, Context context, Expr sourceExpr) {
	if (binding == null) {
		throw new NullPointerException("No binding to evaluate the source expression " + sourceExpr);
	}
	try {
		FunctionEnv env = new FunctionEnvBase(context);
		NodeValue nodeValue = sourceExpr.eval(binding, env);
		if (!nodeValue.isIRI()) {
			throw new IllegalArgumentException("FROM source expression did not eval to a URI " + sourceExpr);
		}
		return nodeValue.asNode().getURI();
	} catch (ExprEvalException ex) {
		throw new IllegalArgumentException("Exception when evaluating the source expression " + sourceExpr, ex);
	}
}
 
Example #27
Source File: GenerateNamedPlan.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void exec(
        final List<Var> variables,
        final List<Binding> values,
        final Context context) {
    final QueryExecutor queryExecutor = ContextUtils.getQueryExecutor(context);
    final FunctionEnv env = new FunctionEnvBase(context);
    final Map<String, List<Binding>> splitValues = EvalUtils.splitBindingsForQuery(name, values, env);
    for (String queryName : splitValues.keySet()) {
        final List<Binding> queryValues = splitValues.get(queryName);
        final List<List<Node>> queryCall = EvalUtils.eval(callParameters, queryValues, env);
        queryExecutor.execGenerateFromName(queryName, queryCall, context);
    }
}
 
Example #28
Source File: SPARQLExtFunction.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
public Key(Expr functionExpression, BindingMap binding, FunctionEnv env) {
    this.functionExpression = functionExpression;
    this.binding = binding;
    this.env = env;
}
 
Example #29
Source File: FUN_PrefixedIRI.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param binding
 * @param args
 * @param uri
 * @param env
 * @return
 */
@Override
public NodeValue exec(
        final Binding binding,
        final ExprList args,
        final String uri,
        final FunctionEnv env) {
    if (args == null) {
        throw new ARQInternalErrorException("FunctionBase: Null args list");
    }
    if (args.size() != 1) {
        throw new ExprEvalException("Expecting one argument");
    }
    NodeValue node = args.get(0).eval(binding, env);
    if (node == null) {
        throw new ExprEvalException("The input did not resolve to a IRI: " + args.get(0));
    }
    if (!node.isIRI()) {
        LOG.debug("The input should be a IRI. Got " + node);
        throw new ExprEvalException("The input should be a IRI. Got " + node);
    }

    String longIRI = node.asNode().getURI();
    Dataset dataset = ContextUtils.getDataset(env.getContext());
    
    final Map<String, String> prefixMap = dataset.getDefaultModel().getNsPrefixMap();
    final Set<String> prefixes = prefixMap.keySet();
    String prefix = null;
    String localName = uri;
    for (String p : prefixes) {
        String ns = prefixMap.get(p);
        if (longIRI.startsWith(ns)) {
            String ln = longIRI.substring(ns.length());
            if (ln.length() <= localName.length()) {
                prefix = p;
                localName = ln;
            }
        }
    }
    if(prefix != null) {
        return new NodeValueString(prefix + ":" + localName);
    } else {
        return new NodeValueString(longIRI);
    }
}
 
Example #30
Source File: IsDeactivatedFunction.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
protected NodeValue exec(Node arg1, FunctionEnv env) {
	return NodeValue.makeBoolean(env.getActiveGraph().contains(arg1, SH.deactivated.asNode(), JenaDatatypes.TRUE.asNode()));
}