org.eclipse.rdf4j.query.algebra.evaluation.function.Function Java Examples

The following examples show how to use org.eclipse.rdf4j.query.algebra.evaluation.function.Function. 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: HalyardValueExprEvaluation.java    From Halyard with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates a function.
 */
private Value evaluate(FunctionCall node, BindingSet bindings) throws ValueExprEvaluationException, QueryEvaluationException {
    Optional<Function> function = FunctionRegistry.getInstance().get(node.getURI());
    if (!function.isPresent()) {
        throw new QueryEvaluationException("Unknown function '" + node.getURI() + "'");
    }
    // the NOW function is a special case as it needs to keep a shared return
    // value for the duration of the query.
    if (function.get() instanceof Now) {
        return evaluate((Now) function.get(), bindings);
    }
    List<ValueExpr> args = node.getArgs();
    Value[] argValues = new Value[args.size()];
    for (int i = 0; i < args.size(); i++) {
        argValues[i] = evaluate(args.get(i), bindings);
    }
    return function.get().evaluate(valueFactory, argValues);
}
 
Example #2
Source File: StrictEvaluationStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Evaluates a function.
 */
public Value evaluate(FunctionCall node, BindingSet bindings)
		throws QueryEvaluationException {
	Function function = FunctionRegistry.getInstance()
			.get(node.getURI())
			.orElseThrow(() -> new QueryEvaluationException("Unknown function '" + node.getURI() + "'"));

	// the NOW function is a special case as it needs to keep a shared
	// return
	// value for the duration of the query.
	if (function instanceof Now) {
		return evaluate((Now) function, bindings);
	}

	List<ValueExpr> args = node.getArgs();

	Value[] argValues = new Value[args.size()];

	for (int i = 0; i < args.size(); i++) {
		argValues[i] = evaluate(args.get(i), bindings);
	}

	return function.evaluate(tripleSource.getValueFactory(), argValues);

}
 
Example #3
Source File: ConstantOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Determines if the provided zero-arg function is a function that should return a constant value for the entire
 * query execution (e.g NOW()), or if it should generate a new value for every call (e.g. RAND()).
 *
 * @param functionCall a zero-arg function call.
 * @return <code>true<code> iff the provided function returns a constant value for the query execution, <code>false</code>
 *         otherwise.
 */
private boolean isConstantZeroArgFunction(FunctionCall functionCall) {
	Function function = FunctionRegistry.getInstance()
			.get(functionCall.getURI())
			.orElseThrow(() -> new QueryEvaluationException(
					"Unable to find function with the URI: " + functionCall.getURI()));

	// we treat constant functions as the 'regular case' and make
	// exceptions for specific SPARQL built-in functions that require
	// different treatment.
	if (function instanceof Rand || function instanceof UUID || function instanceof STRUUID) {
		return false;
	}

	return true;
}
 
Example #4
Source File: Cast.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Value evaluate(ValueFactory valueFactory, Value arg1, Value arg2) throws ValueExprEvaluationException {
	if (!(arg1 instanceof Literal)) {
		throw new ValueExprEvaluationException("First argument must be a literal");
	}
	if (!(arg2 instanceof IRI)) {
		throw new ValueExprEvaluationException("Second argument must be a datatype");
	}
	Literal value = (Literal) arg1;
	IRI targetDatatype = (IRI) arg2;
	Function func = FunctionRegistry.getInstance().get(targetDatatype.stringValue()).orElse(null);
	return (func != null) ? func.evaluate(valueFactory, value)
			: valueFactory.createLiteral(value.getLabel(), targetDatatype);
}
 
Example #5
Source File: TemporalFilterIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void temporalFunctionsRegistered() {
    int count = 0;
    final Collection<Function> funcs = FunctionRegistry.getInstance().getAll();
    for (final Function fun : funcs) {
        if (fun.getURI().startsWith(TEMPORAL)) {
            count++;
        }
    }

    // There are 4 temporal functions registered, ensure that there are 4.
    assertEquals(4, count);
}
 
Example #6
Source File: GeoFilterIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void showGeoFunctionsRegistered() {
    int count = 0;
    final Collection<Function> funcs = FunctionRegistry.getInstance().getAll();
    for (final Function fun : funcs) {
        final String uri = fun.getURI();
        if (uri.startsWith(GEO)) {
            count++;
            System.out.println(String.format("Geo Registered Function #%02d: %s", count, uri));
        }
    }

    // There are 35 geo functions registered, ensure that there are 35.
    assertEquals(35, count);
}
 
Example #7
Source File: FunctionArguments.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the UoM IRI of the unit
 *
 * @param func function
 * @param v    value
 * @return UoM IRI
 * @throws ValueExprEvaluationException
 */
public static IRI getUnits(Function func, Value v) throws ValueExprEvaluationException {
	if (!(v instanceof IRI)) {
		throw new ValueExprEvaluationException("Invalid argument for " + func.getURI() + ": " + v);
	}
	IRI unitUri = (IRI) v;
	if (!unitUri.getNamespace().equals(GEOF.UOM_NAMESPACE)) {
		throw new ValueExprEvaluationException("Invalid unit of measurement URI for " + func.getURI() + ": " + v);
	}
	return unitUri;
}
 
Example #8
Source File: FunctionArguments.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the literal of a specific data type
 *
 * @param func             function
 * @param v                value
 * @param expectedDatatype
 * @return literal
 * @throws ValueExprEvaluationException
 */
public static Literal getLiteral(Function func, Value v, IRI expectedDatatype) throws ValueExprEvaluationException {
	if (!(v instanceof Literal)) {
		throw new ValueExprEvaluationException("Invalid argument for " + func.getURI() + ": " + v);
	}
	Literal lit = (Literal) v;
	if (!expectedDatatype.equals(lit.getDatatype())) {
		throw new ValueExprEvaluationException(
				"Invalid datatype " + lit.getDatatype() + " for " + func.getURI() + ": " + v);
	}
	return lit;
}
 
Example #9
Source File: FunctionArguments.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the geo shape
 *
 * @param func    function
 * @param v       value
 * @param context
 * @return shape
 * @throws ValueExprEvaluationException
 */
public static Shape getShape(Function func, Value v, SpatialContext context) throws ValueExprEvaluationException {
	Literal wktLiteral = getLiteral(func, v, GEO.WKT_LITERAL);
	try {
		ShapeReader reader = context.getFormats().getWktReader();
		return reader.read(wktLiteral.getLabel());
	} catch (IOException | InvalidShapeException | ParseException e) {
		throw new ValueExprEvaluationException("Invalid argument for " + func.getURI() + ": " + wktLiteral, e);
	}
}
 
Example #10
Source File: FunctionArguments.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the double value
 *
 * @param func function
 * @param v    value
 * @return double
 * @throws ValueExprEvaluationException
 */
public static double getDouble(Function func, Value v) throws ValueExprEvaluationException {
	if (!(v instanceof Literal)) {
		throw new ValueExprEvaluationException("Invalid argument for " + func.getURI() + ": " + v);
	}

	try {
		return ((Literal) v).doubleValue();
	} catch (NumberFormatException e) {
		throw new ValueExprEvaluationException(e);
	}

}
 
Example #11
Source File: SpinFunctionInterpreter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(FunctionCall node) throws RDF4JException {
	String name = node.getURI();
	if (!functionRegistry.has(name)) {
		IRI funcUri = vf.createIRI(name);
		Function f = parser.parseFunction(funcUri, tripleSource);
		functionRegistry.add(f);
	}
	super.meet(node);
}
 
Example #12
Source File: SpinSailConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void invalidate(Resource subj) {
	if (subj instanceof IRI) {
		parser.reset((IRI) subj);
		String key = subj.stringValue();
		Function func = functionRegistry.get(key).orElse(null);
		if (func instanceof TransientFunction) {
			functionRegistry.remove(func);
		}
		TupleFunction tupleFunc = tupleFunctionRegistry.get(key).orElse(null);
		if (tupleFunc instanceof TransientTupleFunction) {
			tupleFunctionRegistry.remove(tupleFunc);
		}
	}
}
 
Example #13
Source File: CanInvoke.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Function getFunction(String name, TripleSource tripleSource, FunctionRegistry functionRegistry)
		throws RDF4JException {
	Function func = functionRegistry.get(name).orElse(null);
	if (func == null) {
		IRI funcUri = tripleSource.getValueFactory().createIRI(name);
		func = parser.parseFunction(funcUri, tripleSource);
		functionRegistry.add(func);
	}
	return func;
}
 
Example #14
Source File: SpinTupleFunctionAsFunctionParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Function parse(IRI funcUri, TripleSource store) throws RDF4JException {
	Statement magicPropStmt = TripleSources.single(funcUri, RDF.TYPE, SPIN.MAGIC_PROPERTY_CLASS, store);
	if (magicPropStmt == null) {
		return null;
	}

	Value body = TripleSources.singleValue(funcUri, SPIN.BODY_PROPERTY, store);
	if (!(body instanceof Resource)) {
		return null;
	}
	final TupleFunction tupleFunc = parser.parseMagicProperty(funcUri, store);
	return new TransientFunction() {

		@Override
		public String getURI() {
			return tupleFunc.getURI();
		}

		@Override
		public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
			try {
				try (CloseableIteration<? extends List<? extends Value>, QueryEvaluationException> iter = tupleFunc
						.evaluate(valueFactory, args)) {
					if (iter.hasNext()) {
						return iter.next().get(0);
					} else {
						return null;
					}
				}
			} catch (QueryEvaluationException e) {
				throw new ValueExprEvaluationException(e);
			}
		}
	};
}
 
Example #15
Source File: Invoke.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length == 0) {
		throw new ValueExprEvaluationException("At least one argument is required");
	}
	if (!(args[0] instanceof URI)) {
		throw new ValueExprEvaluationException("The first argument must be a function URI");
	}
	URI func = (URI) args[0];
	Value[] funcArgs = new Value[args.length - 1];
	System.arraycopy(args, 1, funcArgs, 0, funcArgs.length);
	Function function = FunctionRegistry.getInstance().get(func.stringValue()).orElse(null);
	return function.evaluate(valueFactory, funcArgs);
}
 
Example #16
Source File: FunctionAdapter.java    From rya with Apache License 2.0 4 votes vote down vote up
FunctionAdapter(org.eclipse.rdf4j.query.algebra.evaluation.function.Function theRdf4JFunction) {
    this.theRdf4JFunction = theRdf4JFunction;
}
 
Example #17
Source File: GeoFunctionsIT.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void withGeoFilters() throws Exception {
    final String sparql =
            "PREFIX geo: <http://www.opengis.net/ont/geosparql#> " +
            "PREFIX ryageo: <tag:rya.apache.org,2017:function/geo#> " +
            "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> " +
            "SELECT ?feature ?point ?wkt {" +
                " ?feature a geo:Feature . " +
                " ?feature geo:hasGeometry ?point . " +
                " ?point a geo:Point . " +
                " ?point geo:asWKT ?wkt . " +
                " FILTER(ryageo:ehContains(?wkt, \"POLYGON((-77 39, -76 39, -76 38, -77 38, -77 39))\"^^geo:wktLiteral)) " +
            "}";

    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Set<Statement> statements = Sets.newHashSet(
            vf.createStatement(vf.createIRI("tag:rya.apache.org,2017:ex#feature"), vf.createIRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), vf.createIRI("http://www.opengis.net/ont/geosparql#Feature")),
            vf.createStatement(vf.createIRI("tag:rya.apache.org,2017:ex#feature"), vf.createIRI("http://www.opengis.net/ont/geosparql#hasGeometry"), vf.createIRI("tag:rya.apache.org,2017:ex#test_point")),
            vf.createStatement(vf.createIRI("tag:rya.apache.org,2017:ex#test_point"), vf.createIRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), vf.createIRI("http://www.opengis.net/ont/geosparql#Point")),
            vf.createStatement(vf.createIRI("tag:rya.apache.org,2017:ex#test_point"), vf.createIRI("http://www.opengis.net/ont/geosparql#asWKT"), vf.createLiteral("Point(-77.03524 38.889468)", vf.createIRI("http://www.opengis.net/ont/geosparql#wktLiteral"))));

    // Create a Geo function.
    final Function geoFunction = new Function() {
        @Override
        public String getURI() {
            return "tag:rya.apache.org,2017:function/geo#ehContains";
        }

        @Override
        public Value evaluate(final ValueFactory valueFactory, final Value... args) throws ValueExprEvaluationException {
            if (args.length != 2) {
                throw new ValueExprEvaluationException(getURI() + " requires exactly 3 arguments, got " + args.length);
            }
            return valueFactory.createLiteral(true);
        }
    };

    // Add our new function to the registry
    FunctionRegistry.getInstance().add(geoFunction);

    // The expected results of the SPARQL query once the PCJ has been computed.
    final Set<BindingSet> expectedResults = new HashSet<>();
    final MapBindingSet bs = new MapBindingSet();
    bs.addBinding("wkt", vf.createLiteral("Point(-77.03524 38.889468)", vf.createIRI("http://www.opengis.net/ont/geosparql#wktLiteral")));
    bs.addBinding("feature", vf.createIRI("tag:rya.apache.org,2017:ex#feature"));
    bs.addBinding("point", vf.createIRI("tag:rya.apache.org,2017:ex#test_point"));
    expectedResults.add(bs);

    runTest(sparql, statements, expectedResults);
}
 
Example #18
Source File: FunctionArguments.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Get the geo point
 *
 * @param func       function
 * @param v          value
 * @param geoContext
 * @return point
 * @throws ValueExprEvaluationException
 */
public static Point getPoint(Function func, Value v, SpatialContext geoContext)
		throws ValueExprEvaluationException {
	Shape p = FunctionArguments.getShape(func, v, geoContext);
	if (!(p instanceof Point)) {
		throw new ValueExprEvaluationException("Invalid argument for " + func.getURI() + " (not a point): " + v);
	}
	return (Point) p;
}
 
Example #19
Source File: FunctionArguments.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Get the string value
 *
 * @param func function
 * @param v    value
 * @return string
 * @throws ValueExprEvaluationException
 */
public static String getString(Function func, Value v) throws ValueExprEvaluationException {
	Literal l = getLiteral(func, v, XMLSchema.STRING);
	return l.stringValue();
}
 
Example #20
Source File: FunctionParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License votes vote down vote up
Function parse(IRI uri, TripleSource store) throws RDF4JException;