org.eclipse.rdf4j.model.Value Java Examples

The following examples show how to use org.eclipse.rdf4j.model.Value. 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: SparqlToPigTransformVisitor.java    From rya with Apache License 2.0 6 votes vote down vote up
protected String getVarValue(Var var) {
    if (var == null) {
        return "";
    } else {
        Value value = var.getValue();
        if (value == null) {
            return "";
        }
        if (value instanceof IRI) {
            return "<" + value.stringValue() + ">";
        }
        if (value instanceof Literal) {
            Literal lit = (Literal) value;
            if (lit.getDatatype() == null) {
                //string
                return "\\'" + value.stringValue() + "\\'";
            }
        }
        return value.stringValue();
    }

}
 
Example #2
Source File: RepositoryModel.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterator<org.ontoware.rdf2go.model.Statement> findStatements(
		ResourceOrVariable subject, UriOrVariable predicate, NodeOrVariable object)
		throws ModelRuntimeException {
	assertModel();
	// convert parameters to RDF4J data types
	org.eclipse.rdf4j.model.Resource targetSubject = (org.eclipse.rdf4j.model.Resource) ConversionUtil
			.toRDF4J(subject, this.valueFactory);
	org.eclipse.rdf4j.model.IRI targetPredicate = (org.eclipse.rdf4j.model.IRI) ConversionUtil.toRDF4J(
			predicate, this.valueFactory);
	Value targetObject = ConversionUtil.toRDF4J(object, this.valueFactory);

	try {
		// find the matching statements
		CloseableIteration<? extends org.eclipse.rdf4j.model.Statement, ? extends RDF4JException> statements = this.connection
				.getStatements(targetSubject, targetPredicate, targetObject, true,
						this.rdf4jContext);
		// wrap them in a StatementIterable
		return new StatementIterator(statements, this);
	} catch (RepositoryException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example #3
Source File: ProjectionIterator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static BindingSet project(ProjectionElemList projElemList, BindingSet sourceBindings,
		BindingSet parentBindings, boolean includeAllParentBindings) {
	final QueryBindingSet resultBindings = new QueryBindingSet();
	if (includeAllParentBindings) {
		resultBindings.addAll(parentBindings);
	}

	for (ProjectionElem pe : projElemList.getElements()) {
		Value targetValue = sourceBindings.getValue(pe.getSourceName());
		if (!includeAllParentBindings && targetValue == null) {
			targetValue = parentBindings.getValue(pe.getSourceName());
		}
		if (targetValue != null) {
			resultBindings.setBinding(pe.getTargetName(), targetValue);
		}
	}

	return resultBindings;
}
 
Example #4
Source File: FunctionAdapter.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Convert from OpenRDF to rdf4j value used by Geo Functions.
 * 
 * @param value
 *            Must be a URIImpl, Literal or a BooleanLiteralImpl, or throws error. Ignores language.
 * @param rdf4jValueFactory
 * @return an rdf4j Literal copied from the input
 */
public org.eclipse.rdf4j.model.Value adaptValue(Value value, org.eclipse.rdf4j.model.ValueFactory rdf4jValueFactory) {
    if (value instanceof URIImpl) {
        URIImpl uri = (URIImpl) value;
        return rdf4jValueFactory.createIRI(uri.stringValue());
    } else if (!(value instanceof Literal)) {
        throw new UnsupportedOperationException("Not supported, value must be literal type, it was: " + value.getClass() + " value=" + value);
    }
    if (value instanceof BooleanLiteralImpl) {
        BooleanLiteralImpl bl = (BooleanLiteralImpl) value;
        if (bl.booleanValue())
            return org.eclipse.rdf4j.model.impl.BooleanLiteral.TRUE;
        else
            return org.eclipse.rdf4j.model.impl.BooleanLiteral.FALSE;
    }
    final Literal literalValue = (Literal) value;
    org.eclipse.rdf4j.model.ValueFactory vf = org.eclipse.rdf4j.model.impl.SimpleValueFactory.getInstance();
    final String label = literalValue.getLabel();
    final IRI datatype = vf.createIRI(literalValue.getDatatype().stringValue());
    return vf.createLiteral(label, datatype);
}
 
Example #5
Source File: TreeModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public boolean contains(Resource subj, IRI pred, Value obj, Resource... contexts) {
	if (contexts == null || contexts.length == 1 && contexts[0] == null) {
		Iterator<Statement> iter = matchPattern(subj, pred, obj, null);
		while (iter.hasNext()) {
			if (iter.next().getContext() == null) {
				return true;
			}
		}
		return false;
	} else if (contexts.length == 0) {
		return matchPattern(subj, pred, obj, null).hasNext();
	} else {
		for (Resource ctx : contexts) {
			if (ctx == null) {
				if (contains(subj, pred, obj, (Resource[]) null)) {
					return true;
				}
			} else if (matchPattern(subj, pred, obj, ctx).hasNext()) {
				return true;
			}
		}
		return false;
	}
}
 
Example #6
Source File: FederationEvalStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public FederationEvalStrategy(FederationContext federationContext) {
	super(new org.eclipse.rdf4j.query.algebra.evaluation.TripleSource() {

		@Override
		public CloseableIteration<? extends Statement, QueryEvaluationException> getStatements(
				Resource subj, IRI pred, Value obj, Resource... contexts)
				throws QueryEvaluationException {
			throw new FedXRuntimeException(
					"Federation Strategy does not support org.openrdf.query.algebra.evaluation.TripleSource#getStatements."
							+
							" If you encounter this exception, please report it.");
		}

		@Override
		public ValueFactory getValueFactory() {
			return SimpleValueFactory.getInstance();
		}
	}, federationContext.getFederatedServiceResolver());
	this.federationContext = federationContext;
	this.executor = federationContext.getManager().getExecutor();
	this.cache = createSourceSelectionCache();
}
 
Example #7
Source File: SparqlTripleSource.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public boolean hasStatements(Resource subj,
		IRI pred, Value obj, QueryInfo queryInfo, Resource... contexts)
		throws RepositoryException {

	if (!useASKQueries) {
		StatementPattern st = new StatementPattern(new Var("s", subj), new Var("p", pred), new Var("o", obj));
		Dataset dataset = FedXUtil.toDataset(contexts);
		try {
			return hasStatements(st, EmptyBindingSet.getInstance(), queryInfo, dataset);
		} catch (Exception e) {
			throw new RepositoryException(e);
		}
	}
	return super.hasStatements(subj, pred, obj, queryInfo, contexts);
}
 
Example #8
Source File: StrictEvaluationStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Value evaluate(Str node, BindingSet bindings) throws QueryEvaluationException {
	Value argValue = evaluate(node.getArg(), bindings);

	if (argValue instanceof IRI) {
		return tripleSource.getValueFactory().createLiteral(argValue.toString());
	} else if (argValue instanceof Literal) {
		Literal literal = (Literal) argValue;

		if (QueryEvaluationUtil.isSimpleLiteral(literal)) {
			return literal;
		} else {
			return tripleSource.getValueFactory().createLiteral(literal.getLabel());
		}
	} else if (argValue instanceof Triple) {
		return tripleSource.getValueFactory().createLiteral(argValue.toString());
	} else {
		throw new ValueExprEvaluationException();
	}
}
 
Example #9
Source File: LinkedHashModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public boolean add(Resource subj, IRI pred, Value obj, Resource... contexts) {
	if (subj == null || pred == null || obj == null) {
		throw new UnsupportedOperationException("Incomplete statement");
	}
	Value[] ctxs = notNull(contexts);
	if (ctxs.length == 0) {
		ctxs = NULL_CTX;
	}
	boolean changed = false;
	for (Value ctx : ctxs) {
		ModelNode<Resource> s = asNode(subj);
		ModelNode<IRI> p = asNode(pred);
		ModelNode<Value> o = asNode(obj);
		ModelNode<Resource> c = asNode((Resource) ctx);
		ModelStatement st = new ModelStatement(s, p, o, c);
		changed |= addModelStatement(st);
	}
	return changed;
}
 
Example #10
Source File: GeoTemporalProviderTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void twoSubjectMultiFilter_test() throws Exception {
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Value geo = vf.createLiteral("Point(0 0)", GeoConstants.XMLSCHEMA_OGC_WKT);
    final Value temp = vf.createLiteral(new TemporalInstantRfc3339(2015, 12, 30, 12, 00, 0).toString());
    final IRI tempPred = vf.createIRI(URI_PROPERTY_AT_TIME);
    final String query =
        "PREFIX geo: <http://www.opengis.net/ont/geosparql#>" +
        "PREFIX geos: <http://www.opengis.net/def/function/geosparql/>" +
        "PREFIX time: <tag:rya-rdf.org,2015:temporal#>" +
        "SELECT * WHERE { " +
            "?subj <" + tempPred + "> ?time ."+
            "?subj <" + GeoConstants.GEO_AS_WKT + "> ?loc . " +
            " FILTER(geos:sfContains(?loc, " + geo + ")) . " +
            " FILTER(time:equals(?time, " + temp + ")) . " +
            " FILTER(geos:sfWithin(?loc, " + geo + ")) . " +
            " FILTER(time:before(?time, " + temp + ")) . " +
        "}";
    final QuerySegment<EventQueryNode> node = getQueryNode(query);
    final List<EventQueryNode> nodes = provider.getExternalSets(node);
    assertEquals(1, nodes.size());
}
 
Example #11
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String getVarName(Resource r) throws RDF4JException {
	// have we already seen it
	String varName = vars.get(r);
	// is it well-known
	if (varName == null && r instanceof IRI) {
		varName = wellKnownVars.apply((IRI) r);
		if (varName != null) {
			vars.put(r, varName);
		}
	}
	if (varName == null) {
		// check for a varName statement
		Value nameValue = TripleSources.singleValue(r, SP.VAR_NAME_PROPERTY, store);
		if (nameValue instanceof Literal) {
			varName = ((Literal) nameValue).getLabel();
			if (varName != null) {
				vars.put(r, varName);
			}
		} else if (nameValue != null) {
			throw new MalformedSpinException(
					String.format("Value of %s is not a literal", SP.VAR_NAME_PROPERTY));
		}
	}
	return varName;
}
 
Example #12
Source File: SRID.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length != 1) {
		throw new ValueExprEvaluationException(getURI() + " requires exactly 1 argument, got " + args.length);
	}

	Literal geom = FunctionArguments.getLiteral(this, args[0], GEO.WKT_LITERAL);
	String wkt = geom.getLabel();
	String srid;
	int sep = wkt.indexOf(' ');
	if (sep != -1 && wkt.charAt(0) == '<' && wkt.charAt(sep - 1) == '>') {
		srid = wkt.substring(1, sep - 1);
	} else {
		srid = GEO.DEFAULT_SRID;
	}

	return valueFactory.createLiteral(srid, XMLSchema.ANYURI);
}
 
Example #13
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Var getVar(Value v) throws RDF4JException {
	Var var = null;
	if (v instanceof Resource) {
		String varName = getVarName((Resource) v);
		if (varName != null) {
			var = createVar(varName);
		}
	}

	if (var == null) {
		// it must be a constant then
		var = TupleExprs.createConstVar(v);
	}

	return var;
}
 
Example #14
Source File: HBaseSail.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Override
public void removeStatement(UpdateContext op, Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException {
	    //should we be defensive about nulls for subj, pre and obj? removeStatements is where you would use nulls, not here.

    if (!isWritable()) throw new SailException(tableName + " is read only");
    long timestamp = getDefaultTimeStamp();
    try {
        for (Resource ctx : normalizeContexts(contexts)) {
            for (KeyValue kv : HalyardTableUtils.toKeyValues(subj, pred, obj, ctx, true, timestamp)) { //calculate the kv's corresponding to the quad (or triple)
                delete(kv);
            }
        }
    } catch (IOException e) {
        throw new SailException(e);
    }
}
 
Example #15
Source File: SelectTupleFunction.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public List<Value> next() throws QueryEvaluationException {
	if (isClosed()) {
		throw new NoSuchElementException("The iteration has been closed.");
	}
	try {
		BindingSet bs = queryResult.next();
		List<Value> values = new ArrayList<>(bindingNames.size());
		for (String bindingName : bindingNames) {
			values.add(bs.getValue(bindingName));
		}
		return values;
	} catch (NoSuchElementException e) {
		close();
		throw e;
	}
}
 
Example #16
Source File: InferenceIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllValuesFromQuery() throws Exception {
    final String ontology = "INSERT DATA { GRAPH <http://updated/test> {\n"
            + "  <urn:Cairn_Terrier> rdfs:subClassOf <urn:Terrier> .\n"
            + "  <urn:Terrier> rdfs:subClassOf <urn:Dog> ;\n"
            + "    owl:onProperty <urn:relative> ;\n"
            + "    owl:allValuesFrom <urn:Terrier> .\n"
            + "  <urn:Dog> rdfs:subClassOf [\n"
            + "    owl:onProperty <urn:portrays> ; owl:allValuesFrom <urn:FictionalDog>\n"
            + "  ] .\n"
            + "  <urn:parent> rdfs:subPropertyOf <urn:relative> .\n"
            + "}}";
    conn.prepareUpdate(QueryLanguage.SPARQL, ontology).execute();
    inferenceEngine.refreshGraph();
    final String instances = "INSERT DATA { GRAPH <http://updated/test> {\n"
            + "  <urn:Rommy> a <urn:Cairn_Terrier> .\n"
            + "  <urn:Rommy> <urn:parent> <urn:Terry> .\n"
            + "  <urn:Terry> <urn:portrays> <urn:Toto> .\n"
            + "}}";
    conn.prepareUpdate(QueryLanguage.SPARQL, instances).execute();
    conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT ?x { ?x a <urn:Dog> }").evaluate(resultHandler);
    Assert.assertEquals(2, solutions.size());
    final Set<Value> answers = new HashSet<>();
    for (final BindingSet solution : solutions) {
        answers.add(solution.getBinding("x").getValue());
    }
    Assert.assertTrue(answers.contains(VF.createIRI("urn:Terry")));
    Assert.assertTrue(answers.contains(VF.createIRI("urn:Rommy")));
    // If allValuesFrom inference were applied recursively, this triple wouldn't be needed:
    conn.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA { GRAPH <http://updated/test> {\n"
            + "  <urn:Terry> a <urn:Cairn_Terrier> .\n"
            + "}}").execute();
    conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT ?x { ?x a <urn:FictionalDog> }").evaluate(resultHandler);
    Assert.assertEquals(1, solutions.size());
    Assert.assertEquals(VF.createIRI("urn:Toto"), solutions.get(0).getBinding("x").getValue());
}
 
Example #17
Source File: MongoGeoIndexerIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testDcSearchWithContext() throws Exception {
    // test a ring around dc
    try (final MongoGeoIndexer f = new MongoGeoIndexer()) {
        f.setConf(conf);
        f.init();

        final ValueFactory vf = SimpleValueFactory.getInstance();
        final Resource subject = vf.createIRI("foo:subj");
        final IRI predicate = GeoConstants.GEO_AS_WKT;
        final Value object = vf.createLiteral("Point(-77.03524 38.889468)", GeoConstants.XMLSCHEMA_OGC_WKT);
        final Resource context = vf.createIRI("foo:context");

        final Statement statement = vf.createStatement(subject, predicate, object, context);
        f.storeStatement(convertStatement(statement));
        f.flush();

        final double[] IN = { -78, 39, -77, 39, -77, 38, -78, 38, -78, 39 };
        final LinearRing r1 = gf.createLinearRing(new PackedCoordinateSequence.Double(IN, 2));
        final Polygon p1 = gf.createPolygon(r1, new LinearRing[] {});

        // query with correct context
        assertEquals(Sets.newHashSet(statement), getSet(f.queryWithin(p1, new StatementConstraints().setContext(context))));

        // query with wrong context
        assertEquals(Sets.newHashSet(),
                getSet(f.queryWithin(p1, new StatementConstraints().setContext(vf.createIRI("foo:context2")))));
    }
}
 
Example #18
Source File: GeoWaveIndexerTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestrictPredicatesSearch() throws Exception {
    conf.setStrings(ConfigUtils.GEO_PREDICATES_LIST, "pred:1,pred:2");
    try (final GeoWaveGeoIndexer f = new GeoWaveGeoIndexer()) {
        f.setConf(conf);
        f.purge(conf);

        final ValueFactory vf = SimpleValueFactory.getInstance();

        final Point point = gf.createPoint(new Coordinate(10, 10));
        final Value pointValue = vf.createLiteral("Point(10 10)", GeoConstants.XMLSCHEMA_OGC_WKT);
        final IRI invalidPredicate = GeoConstants.GEO_AS_WKT;

        // These should not be stored because they are not in the predicate list
        f.storeStatement(convertStatement(vf.createStatement(vf.createIRI("foo:subj1"), invalidPredicate, pointValue)));
        f.storeStatement(convertStatement(vf.createStatement(vf.createIRI("foo:subj2"), invalidPredicate, pointValue)));

        final IRI pred1 = vf.createIRI("pred:1");
        final IRI pred2 = vf.createIRI("pred:2");

        // These should be stored because they are in the predicate list
        final Statement s3 = vf.createStatement(vf.createIRI("foo:subj3"), pred1, pointValue);
        final Statement s4 = vf.createStatement(vf.createIRI("foo:subj4"), pred2, pointValue);
        f.storeStatement(convertStatement(s3));
        f.storeStatement(convertStatement(s4));

        // This should not be stored because the object is not valid wkt
        f.storeStatement(convertStatement(vf.createStatement(vf.createIRI("foo:subj5"), pred1, vf.createLiteral("soint(10 10)"))));

        // This should not be stored because the object is not a literal
        f.storeStatement(convertStatement(vf.createStatement(vf.createIRI("foo:subj6"), pred1, vf.createIRI("p:Point(10 10)"))));

        f.flush();

        final Set<Statement> actual = getSet(f.queryEquals(point, EMPTY_CONSTRAINTS));
        Assert.assertEquals(2, actual.size());
        Assert.assertTrue(actual.contains(s3));
        Assert.assertTrue(actual.contains(s4));
    }
}
 
Example #19
Source File: TurtleParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void reportStatement(Resource subj, IRI pred, Value obj) throws RDFParseException, RDFHandlerException {
	if (subj != null && pred != null && obj != null) {
		Statement st = createStatement(subj, pred, obj);
		if (rdfHandler != null) {
			rdfHandler.handleStatement(st);
		}
	}
}
 
Example #20
Source File: InferenceEngine.java    From rya with Apache License 2.0 5 votes vote down vote up
private void refreshHasValueRestrictions(final Map<Resource, IRI> restrictions) throws QueryEvaluationException {
    hasValueByType.clear();
    hasValueByProperty.clear();
    final CloseableIteration<Statement, QueryEvaluationException> iter = RyaDAOHelper.query(ryaDAO, null, OWL.HASVALUE, null, conf);
    try {
        while (iter.hasNext()) {
            final Statement st = iter.next();
            final Resource restrictionClass = st.getSubject();
            if (restrictions.containsKey(restrictionClass)) {
                final IRI property = restrictions.get(restrictionClass);
                final Value value = st.getObject();
                if (!hasValueByType.containsKey(restrictionClass)) {
                    hasValueByType.put(restrictionClass, new HashMap<>());
                }
                if (!hasValueByProperty.containsKey(property)) {
                    hasValueByProperty.put(property, new HashMap<>());
                }
                hasValueByType.get(restrictionClass).put(property, value);
                hasValueByProperty.get(property).put(restrictionClass, value);
            }
        }
    } finally {
        if (iter != null) {
            iter.close();
        }
    }
}
 
Example #21
Source File: OrderComparator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Value evaluate(ValueExpr valueExpr, BindingSet o) throws QueryEvaluationException {
	try {
		return strategy.evaluate(valueExpr, o);
	} catch (ValueExprEvaluationException exc) {
		return null;
	}
}
 
Example #22
Source File: ContextAwareConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void add(Resource subject, IRI predicate, Value object, Resource... contexts) throws RepositoryException {
	if (isNilContext(contexts)) {
		super.add(subject, predicate, object, getAddContexts());
	} else {
		super.add(subject, predicate, object, contexts);
	}
}
 
Example #23
Source File: LinkedHashModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void writeObject(ObjectOutputStream s) throws IOException {
	// Write out any hidden serialization magic
	s.defaultWriteObject();
	// Write in size
	s.writeInt(statements.size());
	// Write in all elements
	for (ModelStatement st : statements) {
		Resource subj = st.getSubject();
		IRI pred = st.getPredicate();
		Value obj = st.getObject();
		Resource ctx = st.getContext();
		s.writeObject(new ContextStatement(subj, pred, obj, ctx));
	}
}
 
Example #24
Source File: KryoVisibilityBindingSetSerializer.java    From rya with Apache License 2.0 5 votes vote down vote up
private static Value makeValue(final String valueString, final IRI typeURI) {
    // Convert the String Value into a Value.
    if (typeURI.equals(XMLSchema.ANYURI)) {
        return VF.createIRI(valueString);
    } else {
        return VF.createLiteral(valueString, typeURI);
    }
}
 
Example #25
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSES1081SameTermWithValues() throws Exception {
	loadTestData("/testdata-query/dataset-ses1081.trig");
	StringBuilder query = new StringBuilder();
	query.append("PREFIX ex: <http://example.org/>\n");
	query.append(" SELECT * \n");
	query.append(" WHERE { \n ");
	query.append("          ?s ex:p ?a . \n");
	query.append("          FILTER sameTerm(?a, ?e) \n ");
	query.append("          VALUES ?e { ex:b } \n ");
	query.append(" } ");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());

	try (TupleQueryResult result = tq.evaluate();) {
		assertNotNull(result);

		int count = 0;
		while (result.hasNext()) {
			BindingSet bs = result.next();
			count++;
			assertNotNull(bs);

			Value s = bs.getValue("s");
			Value a = bs.getValue("a");

			assertNotNull(s);
			assertNotNull(a);
			assertEquals(f.createIRI("http://example.org/a"), s);
			assertEquals(f.createIRI("http://example.org/b"), a);
		}
		assertEquals(1, count);
	} catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example #26
Source File: TripleObjectFunctionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testEvaluateWithTriple() {
	IRI subj = f.createIRI("urn:a");
	IRI pred = f.createIRI("urn:b");
	IRI obj = f.createIRI("urn:c");
	Triple testValue = f.createTriple(subj, pred, obj);

	Value value = function.evaluate(f, testValue);
	assertNotNull(value);
	assertTrue("expect IRI", value instanceof IRI);
	assertEquals("expect same value", obj, value);
}
 
Example #27
Source File: IsTripleFunction.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Value evaluate(ValueFactory vf, Value... args) throws ValueExprEvaluationException {
	if (args.length != 1) {
		throw new ValueExprEvaluationException("expect exactly 1 argument");
	}
	return vf.createLiteral((args[0] instanceof Triple));
}
 
Example #28
Source File: ExtensionIterator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public BindingSet convert(BindingSet sourceBindings) throws QueryEvaluationException {
	QueryBindingSet targetBindings = new QueryBindingSet(sourceBindings);

	for (ExtensionElem extElem : extension.getElements()) {
		ValueExpr expr = extElem.getExpr();
		if (!(expr instanceof AggregateOperator)) {
			try {
				// we evaluate each extension element over the targetbindings, so that bindings from
				// a previous extension element in this same extension can be used by other extension elements.
				// e.g. if a projection contains (?a + ?b as ?c) (?c * 2 as ?d)
				Value targetValue = strategy.evaluate(extElem.getExpr(), targetBindings);

				if (targetValue != null) {
					// Potentially overwrites bindings from super
					targetBindings.setBinding(extElem.getName(), targetValue);
				}
			} catch (ValueExprEvaluationException e) {
				// silently ignore type errors in extension arguments. They should not cause the
				// query to fail but result in no bindings for this solution
				// see https://www.w3.org/TR/sparql11-query/#assignment
				// use null as place holder for unbound variables that must remain so
				targetBindings.setBinding(extElem.getName(), null);
			}
		}
	}

	return targetBindings;
}
 
Example #29
Source File: RepositoryConnectionWrapper.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean hasStatement(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts)
		throws RepositoryException {
	if (isDelegatingRead()) {
		return getDelegate().hasStatement(subj, pred, obj, includeInferred, contexts);
	}
	return super.hasStatement(subj, pred, obj, includeInferred, contexts);
}
 
Example #30
Source File: StatementOutputFormatterSupplier.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final Object key, final ProcessorResult value) {
    VisibilityBindingSet result = null;
    switch(value.getType()) {
        case UNARY:
            result = value.getUnary().getResult();
            break;

        case BINARY:
            result = value.getBinary().getResult();
            break;
    }

    if(result != null && result.getBindingNames().containsAll(REQURIED_BINDINGS)) {
        // Make sure the Subject is the correct type.
        final Value subjVal = result.getValue("subject");
        if(!(subjVal instanceof Resource)) {
            return;
        }

        // Make sure the Predicate is the correct type.
        final Value predVal = result.getValue("predicate");
        if(!(predVal instanceof IRI)) {
            return;
        }

        // Forward the visibility statement.
        final Statement statement = VF.createStatement(
                (Resource) subjVal,
                (IRI) predVal,
                result.getValue("object"));
        processorContext.forward(key, new VisibilityStatement(statement, result.getVisibility()));
    }
}