org.eclipse.rdf4j.model.ValueFactory Java Examples

The following examples show how to use org.eclipse.rdf4j.model.ValueFactory. 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: KafkaExportIT.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void sum() throws Exception {
    // A query that sums the counts of all of the items that are in the inventory.
    final String sparql =
            "SELECT (sum(?count) as ?itemSum) { " +
                "?item <urn:count> ?count . " +
            "}";

    // Create the Statements that will be loaded into Rya.
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Collection<Statement> statements = Sets.newHashSet(
            vf.createStatement(vf.createIRI("urn:apple"), vf.createIRI("urn:count"), vf.createLiteral(5)),
            vf.createStatement(vf.createIRI("urn:gum"), vf.createIRI("urn:count"), vf.createLiteral(7)),
            vf.createStatement(vf.createIRI("urn:sandwich"), vf.createIRI("urn:count"), vf.createLiteral(2)));

    // Create the PCJ in Fluo and load the statements into Rya.
    final String pcjId = loadDataAndCreateQuery(sparql, statements);

    // Create the expected results of the SPARQL query once the PCJ has been computed.
    final MapBindingSet expectedResult = new MapBindingSet();
    expectedResult.addBinding("itemSum", vf.createLiteral("14", XMLSchema.INTEGER));

    // Ensure the last result matches the expected result.
    final VisibilityBindingSet result = readLastResult(pcjId);
    assertEquals(expectedResult, result);
}
 
Example #2
Source File: GeoTemporalProviderTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void twoNode_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 . " +
            "?subj2 <" + tempPred + "> ?time2 ."+
            "?subj2 <" + GeoConstants.GEO_AS_WKT + "> ?loc2 . " +
            " FILTER(geos:sfContains(?loc, " + geo + ")) . " +
            " FILTER(time:equals(?time, " + temp + ")) . " +
            " FILTER(geos:sfContains(?loc2, " + geo + ")) . " +
            " FILTER(time:equals(?time2, " + temp + ")) . " +
        "}";
    final QuerySegment<EventQueryNode> node = getQueryNode(query);
    final List<EventQueryNode> nodes = provider.getExternalSets(node);
    assertEquals(2, nodes.size());
}
 
Example #3
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 #4
Source File: Index.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public CloseableIteration<? extends List<? extends Value>, QueryEvaluationException> evaluate(
		final ValueFactory valueFactory, final Value... args) throws QueryEvaluationException {
	return new CloseableIteratorIteration<List<? extends Value>, QueryEvaluationException>(
			new Iterator<List<Value>>() {

				int pos = 0;

				@Override
				public boolean hasNext() {
					return (pos < args.length);
				}

				@Override
				public List<Value> next() {
					return Arrays.asList(valueFactory.createLiteral(pos), args[pos++]);
				}

				@Override
				public void remove() {
					throw new UnsupportedOperationException();
				}
			});
}
 
Example #5
Source File: HBaseSailTest.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Test
public void testEvaluateWithContext() throws Exception {
    ValueFactory vf = SimpleValueFactory.getInstance();
    Resource subj = vf.createIRI("http://whatever/subj/");
    IRI pred = vf.createIRI("http://whatever/pred/");
    Value obj = vf.createLiteral("whatever");
    IRI context = vf.createIRI("http://whatever/context/");
    CloseableIteration<? extends Statement, SailException> iter;
    HBaseSail sail = new HBaseSail(HBaseServerTestInstance.getInstanceConfig(), "whatevertable", true, 0, true, 0, null, null);
    SailRepository rep = new SailRepository(sail);
    rep.initialize();
    sail.addStatement(subj, pred, obj, context);
    sail.commit();
    TupleQuery q = rep.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, "select ?s ?p ?o from named <http://whatever/context/> where {<http://whatever/subj/> <http://whatever/pred/> \"whatever\"}");
    TupleQueryResult res = q.evaluate();
    assertFalse(res.hasNext());
    rep.shutDown();
}
 
Example #6
Source File: NoReification.java    From inception with Apache License 2.0 6 votes vote down vote up
@Override
public boolean exists(RepositoryConnection aConnection, KnowledgeBase akb,
        KBStatement mockStatement)
{
    ValueFactory vf = aConnection.getValueFactory();
    String QUERY = "SELECT * WHERE { ?s ?p ?o . }";
    TupleQuery tupleQuery = aConnection.prepareTupleQuery(QueryLanguage.SPARQL, QUERY);
    tupleQuery.setBinding("s", vf.createIRI(mockStatement.getInstance().getIdentifier()));
    tupleQuery.setBinding("p", vf.createIRI(mockStatement.getProperty().getIdentifier()));

    InceptionValueMapper mapper = new InceptionValueMapper();
    tupleQuery.setBinding("o", mapper.mapStatementValue(mockStatement, vf));

    try (TupleQueryResult result = tupleQuery.evaluate()) {
        return result.hasNext();
    }
}
 
Example #7
Source File: GeoTemporalProviderTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void twoSubjOneFilter_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 . " +
            "?subj2 <" + tempPred + "> ?time2 ."+
            "?subj2 <" + GeoConstants.GEO_AS_WKT + "> ?loc2 . " +
            " FILTER(geos:sfContains(?loc, " + geo + ")) . " +
            " FILTER(time:equals(?time, " + temp + ")) . " +
        "}";
    final QuerySegment<EventQueryNode> node = getQueryNode(query);
    final List<EventQueryNode> nodes = provider.getExternalSets(node);
    assertEquals(1, nodes.size());
}
 
Example #8
Source File: LinearTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	repo = OptimisticIsolationTest.getEmptyInitializedRepository(LinearTest.class);
	lf = repo.getValueFactory();
	ValueFactory uf = repo.getValueFactory();
	PAINTER = uf.createIRI(NS, "Painter");
	PAINTS = uf.createIRI(NS, "paints");
	PAINTING = uf.createIRI(NS, "Painting");
	YEAR = uf.createIRI(NS, "year");
	PERIOD = uf.createIRI(NS, "period");
	PICASSO = uf.createIRI(NS, "picasso");
	REMBRANDT = uf.createIRI(NS, "rembrandt");
	GUERNICA = uf.createIRI(NS, "guernica");
	JACQUELINE = uf.createIRI(NS, "jacqueline");
	NIGHTWATCH = uf.createIRI(NS, "nightwatch");
	ARTEMISIA = uf.createIRI(NS, "artemisia");
	DANAE = uf.createIRI(NS, "danaƫ");
	JACOB = uf.createIRI(NS, "jacob");
	ANATOMY = uf.createIRI(NS, "anatomy");
	BELSHAZZAR = uf.createIRI(NS, "belshazzar");
	a = repo.getConnection();
	b = repo.getConnection();
}
 
Example #9
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSES1979MinMaxInf() throws Exception {
	loadTestData("/testdata-query/dataset-ses1979.trig");
	String query = "prefix : <http://example.org/> select (min(?o) as ?min) (max(?o) as ?max) where { ?s :float ?o }";

	ValueFactory vf = conn.getValueFactory();
	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);

	try (TupleQueryResult evaluate = tq.evaluate();) {
		List<BindingSet> result = QueryResults.asList(evaluate);
		assertNotNull(result);
		assertEquals(1, result.size());

		assertEquals(vf.createLiteral(Float.NEGATIVE_INFINITY), result.get(0).getValue("min"));
		assertEquals(vf.createLiteral(Float.POSITIVE_INFINITY), result.get(0).getValue("max"));
	} catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example #10
Source File: BulkedBenchmark.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public BulkedBenchmark() {

		repository.init();

		List<Resource> subjects = new ArrayList<>();

		try (SailRepositoryConnection connection = repository.getConnection()) {
			connection.begin();
			ValueFactory vf = connection.getValueFactory();
			for (int i = 0; i < SIZE; i++) {
				IRI iri = vf.createIRI("http://example.com/" + i);
				connection.add(iri, RDF.TYPE, RDFS.RESOURCE);
				connection.add(iri, RDFS.LABEL, vf.createLiteral("label_" + i));
				subjects.add(iri);
			}

			connection.commit();
		}

		ValueComparator valueComparator = new ValueComparator();
		subjects.sort(valueComparator);

		this.subjects = subjects.stream().map(Tuple::new).collect(Collectors.toList());

	}
 
Example #11
Source File: DateTimeWithinPeriod.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Determines whether two datetimes occur within a specified period of time of one another. This method expects four
 * values, where the first two values are the datetimes, the third value is an integer indicating the period, and
 * the fourth value is an IRI indicating the time unit of the period. The IRI must be of Type DurationDescription in
 * the OWL-Time ontology (see <a href ="https://www.w3.org/TR/owl-time/">https://www.w3.org/TR/owl-time/</a>).
 * Examples of valid time unit IRIs can be found in the class {@link OWLTime} and below
 * <ul>
 * <li>http://www.w3.org/2006/time#days</li>
 * <li>http://www.w3.org/2006/time#hours</li>
 * <li>http://www.w3.org/2006/time#minutes</li>
 * <li>http://www.w3.org/2006/time#seconds</li>
 * </ul>
 *
 * @param valueFactory - factory for creating values (not null)
 * @param values - array of Value arguments for this Function (not null).
 */
@Override
public Value evaluate(ValueFactory valueFactory, Value... values) throws ValueExprEvaluationException {
    checkNotNull(valueFactory);
    checkNotNull(values);
    try {
        // general validation of input
        checkArgument(values.length == 4);
        checkArgument(values[0] instanceof Literal);
        checkArgument(values[1] instanceof Literal);
        checkArgument(values[2] instanceof Literal);
        checkArgument(values[3] instanceof IRI);

        Instant dateTime1 = convertToInstant((Literal) values[0]);
        Instant dateTime2 = convertToInstant((Literal) values[1]);
        long periodMillis = convertPeriodToMillis((Literal) values[2], (IRI) values[3]);
        long timeBetween = Math.abs(Duration.between(dateTime1, dateTime2).toMillis());

        return valueFactory.createLiteral(timeBetween < periodMillis);
    } catch (Exception e) {
        throw new ValueExprEvaluationException(e);
    }
}
 
Example #12
Source File: StatementPatternMatcherTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void matchesSubject() throws Exception {
    // Create the matcher against a pattern that matches a specific subject.
    final StatementPatternMatcher matcher = new StatementPatternMatcher(getSp(
            "SELECT * WHERE {" +
                "<urn:Alice> ?p ?o ." +
            "}"));

    // Create a statement that matches the pattern.
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Statement statement = vf.createStatement(vf.createIRI("urn:Alice"), vf.createIRI("urn:talksTo"), vf.createIRI("urn:Bob"), vf.createIRI("urn:testGraph"));

    // Create the expected resulting Binding Set.
    final QueryBindingSet expected = new QueryBindingSet();
    expected.addBinding("p", vf.createIRI("urn:talksTo"));
    expected.addBinding("o", vf.createIRI("urn:Bob"));

    // Show the expected Binding Set matches the resulting Binding Set.
    final Optional<BindingSet> bs = matcher.match(statement);
    assertEquals(expected, bs.get());
}
 
Example #13
Source File: DirectTypeHierarchyInferencer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void evaluateIntoStatements(ParsedGraphQuery query, Collection<Statement> statements)
		throws SailException, RDFHandlerException, QueryEvaluationException {
	try (CloseableIteration<? extends BindingSet, QueryEvaluationException> bindingsIter = getWrappedConnection()
			.evaluate(query.getTupleExpr(), null, EmptyBindingSet.getInstance(), true)) {
		ValueFactory vf = getValueFactory();

		while (bindingsIter.hasNext()) {
			BindingSet bindings = bindingsIter.next();

			Value subj = bindings.getValue("subject");
			Value pred = bindings.getValue("predicate");
			Value obj = bindings.getValue("object");

			if (subj instanceof Resource && pred instanceof IRI && obj != null) {
				statements.add(vf.createStatement((Resource) subj, (IRI) pred, obj));
			}
		}
	}
}
 
Example #14
Source File: BuildURI.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("Incorrect number of arguments");
	}
	if (!(args[0] instanceof Literal)) {
		throw new ValueExprEvaluationException("First argument must be a string");
	}
	Literal s = (Literal) args[0];
	String tmpl = s.getLabel();
	Map<String, String> mappings = new HashMap<>(args.length);
	for (int i = 1; i < args.length; i++) {
		mappings.put(Integer.toString(i), args[i].stringValue());
	}
	String newValue = StringSubstitutor.replace(tmpl, mappings, "{?", "}");
	if (tmpl.charAt(0) == '<' && tmpl.charAt(tmpl.length() - 1) == '>') {
		return valueFactory.createURI(newValue.substring(1, newValue.length() - 1));
	}
	throw new ValueExprEvaluationException("Invalid URI template: " + tmpl);
}
 
Example #15
Source File: HalyardUpdateTest.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
    File rf = File.createTempFile("HalyardUpdateTest", "");
    rf.delete();
    rf.mkdirs();
    ROOT = rf.toURI().toURL().toString();
    if (!ROOT.endsWith("/")) {
        ROOT = ROOT + "/";
    }
    ValueFactory vf = SimpleValueFactory.getInstance();
    HBaseSail sail = new HBaseSail(HBaseServerTestInstance.getInstanceConfig(), TABLE, true, 0, true, 0, null, null);
    sail.initialize();
    for (int i=0; i<5; i++) {
        for (int j=0; j<5; j++) {
            sail.addStatement(vf.createIRI("http://whatever/subj" + i), vf.createIRI("http://whatever/pred"), vf.createIRI("http://whatever/obj" + j));
        }
    }
    sail.commit();
    sail.shutDown();
}
 
Example #16
Source File: ConvertSpinRDFToString.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 || args.length > 2) {
		throw new ValueExprEvaluationException("Incorrect number of arguments");
	}
	if (!(args[0] instanceof Resource)) {
		throw new ValueExprEvaluationException("First argument must be the root of a SPIN RDF query");
	}
	if (args.length == 2 && !(args[1] instanceof Literal)) {
		throw new ValueExprEvaluationException("Second argument must be a string");
	}
	Resource q = (Resource) args[0];
	boolean useHtml = (args.length == 2) ? ((Literal) args[1]).booleanValue() : false;
	String sparqlString;
	try {
		ParsedOperation op = parser.parse(q, getCurrentQueryPreparer().getTripleSource());
		sparqlString = new SPARQLQueryRenderer().render((ParsedQuery) op);
	} catch (Exception e) {
		throw new ValueExprEvaluationException(e);
	}
	return valueFactory.createLiteral(sparqlString);
}
 
Example #17
Source File: HalyardExportTest.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
    File rf = File.createTempFile("HalyardExportTest", "");
    rf.delete();
    rf.mkdirs();
    ROOT = rf.toURI().toURL().toString();
    if (!ROOT.endsWith("/")) {
        ROOT = ROOT + "/";
    }
    ValueFactory vf = SimpleValueFactory.getInstance();
    HBaseSail sail = new HBaseSail(HBaseServerTestInstance.getInstanceConfig(), TABLE, true, 0, true, 0, null, null);
    sail.initialize();
    for (int i=0; i<10; i++) {
        for (int j=0; j<10; j++) {
            for (int k=0; k<10; k++) {
                sail.addStatement(vf.createIRI("http://whatever/subj" + i), vf.createIRI("http://whatever/pred" + j), vf.createLiteral("whatever\n\"\\" + k));
            }
        }
    }
    sail.commit();
    sail.shutDown();
}
 
Example #18
Source File: Distance.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 != 3) {
		throw new ValueExprEvaluationException(getURI() + " requires exactly 3 arguments, got " + args.length);
	}

	SpatialContext geoContext = SpatialSupport.getSpatialContext();
	Point p1 = FunctionArguments.getPoint(this, args[0], geoContext);
	Point p2 = FunctionArguments.getPoint(this, args[1], geoContext);
	IRI units = FunctionArguments.getUnits(this, args[2]);

	double distDegs = geoContext.calcDistance(p1, p2);
	double distUom = FunctionArguments.convertFromDegrees(distDegs, units);

	return valueFactory.createLiteral(distUom);
}
 
Example #19
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testDescribeWhere() throws Exception {
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ?x WHERE {?x rdfs:label ?y . } ");

	GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());

	ValueFactory vf = conn.getValueFactory();
	IRI a = vf.createIRI("http://example.org/a");
	IRI b = vf.createIRI("http://example.org/b");
	IRI c = vf.createIRI("http://example.org/c");
	IRI e = vf.createIRI("http://example.org/e");
	IRI f = vf.createIRI("http://example.org/f");
	IRI p = vf.createIRI("http://example.org/p");

	try (GraphQueryResult evaluate = gq.evaluate();) {
		Model result = QueryResults.asModel(evaluate);
		assertTrue(result.contains(a, p, null));
		assertTrue(result.contains(b, RDFS.LABEL, null));
		assertTrue(result.contains(c, RDFS.LABEL, null));
		assertTrue(result.contains(null, p, b));
		assertTrue(result.contains(e, RDFS.LABEL, null));
		assertTrue(result.contains(null, p, e));
		assertFalse(result.contains(f, null, null));
		Set<Value> objects = result.filter(a, p, null).objects();
		assertNotNull(objects);
		for (Value object : objects) {
			if (object instanceof BNode) {
				assertTrue(result.contains((Resource) object, null, null));
				assertEquals(2, result.filter((Resource) object, null, null).size());
			}
		}
	}
}
 
Example #20
Source File: JoinProcessorIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void manyJoins() throws Exception {
    // Enumerate some topics that will be re-used
    final String ryaInstance = UUID.randomUUID().toString();
    final UUID queryId = UUID.randomUUID();
    final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
    final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);

    // Setup a topology.
    final String query =
            "SELECT * WHERE { " +
                "?person <urn:talksTo> ?employee ." +
                "?employee <urn:worksAt> ?business ." +
                "?employee <urn:hourlyWage> ?wage ." +
            " }";
    final TopologyFactory factory = new TopologyFactory();
    final TopologyBuilder builder = factory.build(query, statementsTopic, resultsTopic, new RandomUUIDFactory());

    // Create some statements that generate a bunch of right SP results.
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final List<VisibilityStatement> statements = new ArrayList<>();
    statements.add( new VisibilityStatement(
            vf.createStatement(vf.createIRI("urn:Alice"), vf.createIRI("urn:talksTo"), vf.createIRI("urn:Bob")), "a") );
    statements.add( new VisibilityStatement(
            vf.createStatement(vf.createIRI("urn:Bob"), vf.createIRI("urn:worksAt"), vf.createIRI("urn:BurgerJoint")), "a") );
    statements.add( new VisibilityStatement(
            vf.createStatement(vf.createIRI("urn:Bob"), vf.createIRI("urn:hourlyWage"), vf.createLiteral(7.25)), "a") );

    // Make the expected results.
    final Set<VisibilityBindingSet> expected = new HashSet<>();
    final MapBindingSet bs = new MapBindingSet();
    bs.addBinding("person", vf.createIRI("urn:Alice"));
    bs.addBinding("employee", vf.createIRI("urn:Bob"));
    bs.addBinding("business", vf.createIRI("urn:BurgerJoint"));
    bs.addBinding("wage", vf.createLiteral(7.25));
    expected.add( new VisibilityBindingSet(bs, "a") );

    // Run the test.
    RyaStreamsTestUtil.runStreamProcessingTest(kafka, statementsTopic, resultsTopic, builder, statements, expected, VisibilityBindingSetDeserializer.class);
}
 
Example #21
Source File: QueryIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void dateTimeWithinNow() throws Exception {

    final ValueFactory vf = SimpleValueFactory.getInstance();
    final DatatypeFactory dtf = DatatypeFactory.newInstance();
    FunctionRegistry.getInstance().add(new DateTimeWithinPeriod());

    final String sparql = "PREFIX fn: <" + FN.NAMESPACE +">"
            + "SELECT ?event ?startTime WHERE { ?event <uri:startTime> ?startTime. "
            + "FILTER(fn:dateTimeWithin(?startTime, NOW(), 30, <" + OWLTime.SECONDS_URI + "> ))}";

    final ZonedDateTime zTime = ZonedDateTime.now();
    final String time = zTime.format(DateTimeFormatter.ISO_INSTANT);

    final ZonedDateTime zTime1 = zTime.minusSeconds(30);
    final String time1 = zTime1.format(DateTimeFormatter.ISO_INSTANT);

    final Literal lit = vf.createLiteral(dtf.newXMLGregorianCalendar(time));
    final Literal lit1 = vf.createLiteral(dtf.newXMLGregorianCalendar(time1));

    // Create the Statements that will be loaded into Rya.
    final Collection<Statement> statements = Sets.newHashSet(
            vf.createStatement(vf.createIRI("uri:event1"), vf.createIRI("uri:startTime"), lit),
            vf.createStatement(vf.createIRI("uri:event2"), vf.createIRI("uri:startTime"), lit1)
           );

    // Create 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("event", vf.createIRI("uri:event1"));
    bs.addBinding("startTime", lit);
    expectedResults.add(bs);

    // Verify the end results of the query match the expected results.
    runTest(sparql, statements, expectedResults, ExportStrategy.RYA);
}
 
Example #22
Source File: NTriplesUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Parses an N-Triples resource, creates an object for it using the supplied ValueFactory and returns this object.
 *
 * @param nTriplesResource The N-Triples resource to parse.
 * @param valueFactory     The ValueFactory to use for creating the object.
 * @return An object representing the parsed resource.
 * @throws IllegalArgumentException If the supplied resource could not be parsed correctly.
 */
public static Resource parseResource(String nTriplesResource, ValueFactory valueFactory)
		throws IllegalArgumentException {
	if (nTriplesResource.startsWith("<<")) {
		return parseTriple(nTriplesResource, valueFactory);
	} else if (nTriplesResource.startsWith("<")) {
		return parseURI(nTriplesResource, valueFactory);
	} else if (nTriplesResource.startsWith("_:")) {
		return parseBNode(nTriplesResource, valueFactory);
	} else {
		throw new IllegalArgumentException("Not a legal N-Triples resource: " + nTriplesResource);
	}
}
 
Example #23
Source File: HBaseSailTest.java    From Halyard with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void testStatementsIteratorRemove2() throws Exception {
    HBaseSail sail = new HBaseSail(HBaseServerTestInstance.getInstanceConfig(), "whatevertable", true, 0, true, 0, null, null);
    try {
        sail.initialize();
        ValueFactory vf = SimpleValueFactory.getInstance();
        sail.getStatements(vf.createIRI("http://whatever/subj/"), vf.createIRI("http://whatever/pred/"), vf.createIRI("http://whatever/obj/"), true).remove();
    } finally {
        sail.shutDown();
    }
}
 
Example #24
Source File: ArbitraryLengthPathTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSimilarPatterns() throws Exception {
	ValueFactory vf = con.getValueFactory();
	con.add(vf.createIRI("urn:test:a"), RDF.TYPE, vf.createIRI("urn:test:c"));
	con.add(vf.createIRI("urn:test:b"), RDF.TYPE, vf.createIRI("urn:test:d"));
	con.add(vf.createIRI("urn:test:c"), RDFS.SUBCLASSOF, vf.createIRI("urn:test:e"));
	con.add(vf.createIRI("urn:test:d"), RDFS.SUBCLASSOF, vf.createIRI("urn:test:f"));
	String sparql = "ASK { \n"
			+ "   values (?expectedTargetClass55555 ?expectedTargetClass5544T) {(<urn:test:e> <urn:test:f>)}.\n"
			+ "   <urn:test:a> a ?linkTargetClass55555 .\n"
			+ "   ?linkTargetClass55555 rdfs:subClassOf* ?expectedTargetClass55555 .\n"
			+ "   <urn:test:b> a ?linkTargetClass55556 .\n"
			+ "   ?linkTargetClass55556 rdfs:subClassOf* ?expectedTargetClass5544T . }";
	assertTrue(con.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate());
}
 
Example #25
Source File: NeptuneSparqlClient.java    From amazon-neptune-tools with Apache License 2.0 5 votes vote down vote up
private IRI getNonDefaultNamedGraph(Value g, ValueFactory factory) {
    String s = g.stringValue();

    if (StringUtils.isEmpty(s) || s.equalsIgnoreCase("http://aws.amazon.com/neptune/vocab/v01/DefaultNamedGraph")){
        return null;
    }

    return factory.createIRI(s);
}
 
Example #26
Source File: ProtocolUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Resource parseResourceParam(HttpServletRequest request, String paramName, ValueFactory vf)
		throws ClientHTTPException {
	String paramValue = request.getParameter(paramName);
	try {
		return Protocol.decodeResource(paramValue, vf);
	} catch (IllegalArgumentException e) {
		throw new ClientHTTPException(SC_BAD_REQUEST,
				"Invalid value for parameter '" + paramName + "': " + paramValue);
	}
}
 
Example #27
Source File: HalyardTableUtils.java    From Halyard with Apache License 2.0 5 votes vote down vote up
/**
 * Parser method returning all Statements from a single HBase Scan Result
 * @param res HBase Scan Result
 * @param vf ValueFactory to construct Statement and its Values
 * @return List of Statements
 */
public static List<Statement> parseStatements(Result res, ValueFactory vf) {
	// multiple triples may have the same hash (i.e. row key)
    ArrayList<Statement> st = new ArrayList<>();
    if (res.rawCells() != null) for (Cell c : res.rawCells()) {
        st.add(parseStatement(c, vf));
    }
    return st;
}
 
Example #28
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 #29
Source File: MongoGeoIndexerSfIT.java    From rya with Apache License 2.0 5 votes vote down vote up
private static RyaStatement statement(final Geometry geo) {
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Resource subject = vf.createIRI("uri:" + names.get(geo));
    final IRI predicate = GeoConstants.GEO_AS_WKT;
    final Value object = vf.createLiteral(geo.toString(), GeoConstants.XMLSCHEMA_OGC_WKT);
    return RdfToRyaConversions.convertStatement(vf.createStatement(subject, predicate, object));

}
 
Example #30
Source File: TupleQueryResultTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testNotClosingResult() {
	ValueFactory vf = con.getValueFactory();
	int subjectIndex = 0;
	int predicateIndex = 100;
	int objectIndex = 1000;
	int testStatementCount = 1000;
	int count = 0;
	con.begin();
	while (count < testStatementCount) {
		con.add(vf.createIRI("urn:test:" + subjectIndex), vf.createIRI("urn:test:" + predicateIndex),
				vf.createIRI("urn:test:" + objectIndex));
		if (Math.round(Math.random()) > 0) {
			subjectIndex++;
		}
		if (Math.round(Math.random()) > 0) {
			predicateIndex++;
		}
		if (Math.round(Math.random()) > 0) {
			objectIndex++;
		}
		count++;
	}
	con.commit();

	logger.info("Open lots of TupleQueryResults without closing them");
	for (int i = 0; i < 100; i++) {
		try (RepositoryConnection repCon = rep.getConnection()) {
			String queryString = "select * where {?s ?p ?o}";
			TupleQuery tupleQuery = repCon.prepareTupleQuery(QueryLanguage.SPARQL, queryString);

			// see if open results hangs test
			try (TupleQueryResult result = tupleQuery.evaluate()) {
			}
		}
	}
}