Java Code Examples for org.eclipse.rdf4j.model.ValueFactory#createBNode()

The following examples show how to use org.eclipse.rdf4j.model.ValueFactory#createBNode() . 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: AbstractSailImplConfig.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Resource export(Model m) {
	ValueFactory vf = SimpleValueFactory.getInstance();
	BNode implNode = vf.createBNode();

	m.setNamespace("sail", SailConfigSchema.NAMESPACE);
	if (type != null) {
		m.add(implNode, SAILTYPE, vf.createLiteral(type));
	}

	if (iterationCacheSyncThreshold > 0) {
		m.add(implNode, SailConfigSchema.ITERATION_CACHE_SYNC_THRESHOLD,
				vf.createLiteral(iterationCacheSyncThreshold));
	}

	if (connectionTimeOut > 0) {
		m.add(implNode, SailConfigSchema.CONNECTION_TIME_OUT, vf.createLiteral(connectionTimeOut));
	}
	return implNode;
}
 
Example 2
Source File: MemInferencingTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testBlankNodePredicateInference() {
	Repository sailRepository = new SailRepository(createSail());

	ValueFactory vf = sailRepository.getValueFactory();

	try (RepositoryConnection connection = sailRepository.getConnection()) {
		BNode bNode = vf.createBNode();
		connection.add(vf.createStatement(vf.createIRI("http://a"), RDFS.SUBPROPERTYOF, bNode)); // 1
		connection.add(vf.createStatement(bNode, RDFS.DOMAIN, vf.createIRI("http://c"))); // 2
		connection.add(
				vf.createStatement(vf.createIRI("http://d"), vf.createIRI("http://a"), vf.createIRI("http://e"))); // 3
	}

	try (RepositoryConnection connection = sailRepository.getConnection()) {
		boolean correctInference = connection.hasStatement(vf.createIRI("http://d"), RDF.TYPE,
				vf.createIRI("http://c"), true);
		assertTrue("d should be type c, because 3 and 1 entail 'd _:bNode e' with 2 entail 'd type c'",
				correctInference);
	}

}
 
Example 3
Source File: RepositoryConfigUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Update the specified RepositoryConnection with the specified set of RepositoryConfigs. This will overwrite all
 * existing configurations in the Repository that have a Repository ID occurring in these RepositoryConfigs. Note:
 * this method does NOT commit the updates on the connection.
 *
 * @param con     the repository connection to perform the update on
 * @param configs The RepositoryConfigs that should be added to or updated in the Repository. The RepositoryConfig's
 *                ID may already occur in the Repository, in which case all previous configuration data for that
 *                Repository will be cleared before the RepositoryConfig is added.
 * @throws RepositoryException
 * @throws RepositoryConfigException
 */
@Deprecated
public static void updateRepositoryConfigs(RepositoryConnection con, RepositoryConfig... configs)
		throws RepositoryException, RepositoryConfigException {
	ValueFactory vf = con.getRepository().getValueFactory();

	con.begin();

	for (RepositoryConfig config : configs) {
		Resource context = getContext(con, config.getID());

		if (context != null) {
			con.clear(context);
		} else {
			context = vf.createBNode();
		}

		con.add(context, RDF.TYPE, REPOSITORY_CONTEXT);

		Model graph = new LinkedHashModel();
		config.export(graph);
		con.add(graph, context);
	}

	con.commit();
}
 
Example 4
Source File: ProtocolTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testEncodeValueRoundtrip() {
	final ValueFactory vf = SimpleValueFactory.getInstance();
	IRI uri = vf.createIRI("http://example.org/foo-bar");

	String encodedUri = Protocol.encodeValue(uri);
	IRI decodedUri = (IRI) Protocol.decodeValue(encodedUri, vf);

	assertEquals(uri, decodedUri);

	BNode bnode = vf.createBNode("foo-bar-1");
	String encodedBnode = Protocol.encodeValue(bnode);

	BNode decodedNode = (BNode) Protocol.decodeValue(encodedBnode, vf);
	assertEquals(bnode, decodedNode);

	Triple triple1 = vf.createTriple(bnode, uri, vf.createLiteral(16));
	String encodedTriple1 = Protocol.encodeValue(triple1);
	Triple decodedTriple1 = (Triple) Protocol.decodeValue(encodedTriple1, vf);
	assertEquals(triple1, decodedTriple1);

	Triple triple2 = vf.createTriple(bnode, uri, triple1);
	String encodedTriple2 = Protocol.encodeValue(triple2);
	Triple decodedTriple2 = (Triple) Protocol.decodeValue(encodedTriple2, vf);
	assertEquals(triple2, decodedTriple2);
}
 
Example 5
Source File: WikiDataReification.java    From inception with Apache License 2.0 5 votes vote down vote up
private List<Statement> getQualifiersById(RepositoryConnection aConnection, KnowledgeBase kb,
        String aStatementId)
{
    ValueFactory vf = aConnection.getValueFactory();
    
    String QUERY = String.join("\n",
            "SELECT DISTINCT ?p ?o WHERE {",
            "  ?id ?p ?o .",
            "}",
            "LIMIT " + kb.getMaxResults());
    Resource id = vf.createBNode(aStatementId);
    TupleQuery tupleQuery = aConnection.prepareTupleQuery(QueryLanguage.SPARQL, QUERY);
    tupleQuery.setBinding("id", id);

    tupleQuery.setIncludeInferred(false);
    TupleQueryResult result;

    try {
        result = tupleQuery.evaluate();
    }
    catch (QueryEvaluationException e) {
        log.warn("No such statementId in knowledge base", e);
        return null;
    }

    List<Statement> statements = new ArrayList<>();
    while (result.hasNext()) {
        BindingSet bindings = result.next();
        Binding p = bindings.getBinding("p");
        Binding o = bindings.getBinding("o");

        if (!p.getValue().stringValue().contains(PREDICATE_NAMESPACE)) {
            IRI predicate = vf.createIRI(p.getValue().stringValue());
            Value object = o.getValue();
            Statement qualifierStatement = vf.createStatement(id, predicate, object);
            statements.add(qualifierStatement);
        }
    }
    return statements;
}
 
Example 6
Source File: UtilTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public final void testContextsTwo() {
	String ONE = "http://one.rdf4j.org";
	String TWO = "_:two";

	ValueFactory f = repo.getValueFactory();
	Resource[] check = new Resource[] { f.createIRI(ONE), f.createBNode(TWO.substring(2)) };

	String[] tokens = { "command", ONE, TWO };
	Resource[] ctxs = Util.getContexts(tokens, 1, repo);

	assertTrue("Not equal", Arrays.equals(check, ctxs));
}
 
Example 7
Source File: CustomGraphQueryInferencerConfig.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void addQueryNode(Model m, Resource implNode, IRI predicate, String queryText) {
	if (null != queryText) {
		ValueFactory factory = SimpleValueFactory.getInstance();
		BNode queryNode = factory.createBNode();
		m.add(implNode, predicate, queryNode);
		m.add(queryNode, RDF.TYPE, SP.CONSTRUCT_CLASS);
		m.add(queryNode, SP.TEXT_PROPERTY, factory.createLiteral(queryText));
	}
}
 
Example 8
Source File: WikiDataReification.java    From inception with Apache License 2.0 4 votes vote down vote up
private List<Statement> getStatementsById(RepositoryConnection aConnection, KnowledgeBase kb,
        String aStatementId)
{
    ValueFactory vf = aConnection.getValueFactory();
    
    String QUERY = String
        .join("\n",
            "SELECT DISTINCT ?s ?p ?ps ?o WHERE {",
            "  ?s  ?p  ?id .",
            "  ?id ?ps ?o .",
            "  FILTER(STRSTARTS(STR(?ps), STR(?ps_ns)))",
            "}",
            "LIMIT 10");
    Resource id = vf.createBNode(aStatementId);
    TupleQuery tupleQuery = aConnection.prepareTupleQuery(QueryLanguage.SPARQL, QUERY);
    tupleQuery.setBinding("id", id);
    tupleQuery.setBinding("ps_ns", vf.createIRI(PREDICATE_NAMESPACE));

    tupleQuery.setIncludeInferred(false);
    TupleQueryResult result;

    try {
        result = tupleQuery.evaluate();
    }
    catch (QueryEvaluationException e) {
        log.warn("No such statementId in knowledge base", e);
        return null;
    }

    List<Statement> statements = new ArrayList<>();
    while (result.hasNext()) {
        BindingSet bindings = result.next();
        Binding s = bindings.getBinding("s");
        Binding p = bindings.getBinding("p");
        Binding o = bindings.getBinding("o");
        Binding ps = bindings.getBinding("ps");

        IRI instance = vf.createIRI(s.getValue().stringValue());
        IRI predicate = vf.createIRI(p.getValue().stringValue());
        Statement root = vf.createStatement(instance, predicate, id);

        IRI valuePredicate = vf.createIRI(ps.getValue().stringValue());
        Value object = o.getValue();
        Statement valueStatement = vf.createStatement(id, valuePredicate, object);
        statements.add(root);
        statements.add(valueStatement);
    }
    return statements;
}
 
Example 9
Source File: CustomFederationConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testAssertionErrorReproduction() {

	for (int i = 0; i < 1000; i++) {

		ValueFactory vf = SimpleValueFactory.getInstance();
		BNode address = vf.createBNode();
		BNode anotherAddress = vf.createBNode();

		ModelBuilder builder = new ModelBuilder();
		builder
				.setNamespace("ex", "http://example.org/")
				.subject("ex:Picasso")
				.add(RDF.TYPE, "ex:Artist")
				.add(FOAF.FIRST_NAME, "Pablo")
				.add("ex:homeAddress", address)
				.subject("ex:AnotherArtist")
				.add(RDF.TYPE, "ex:Artist")
				.add(FOAF.FIRST_NAME, "AnotherArtist")
				.add("ex:homeAddress", anotherAddress)
				.subject(address)
				.add("ex:street", "31 Art Gallery")
				.add("ex:city", "Madrid")
				.add("ex:country", "Spain")
				.subject(anotherAddress)
				.add("ex:street", "32 Art Gallery")
				.add("ex:city", "London")
				.add("ex:country", "UK");

		Model model = builder.build();
		Repository repo1 = new SailRepository(new MemoryStore());
		repo1.init();
		try (RepositoryConnection connection = repo1.getConnection()) {
			connection.add(model);
		}

		Repository repo2 = new SailRepository(new MemoryStore());
		repo2.init();

		Federation fed = new Federation();
		fed.addMember(repo1);
		fed.addMember(repo2);

		String ex = "http://example.org/";
		String queryString = "PREFIX rdf: <" + RDF.NAMESPACE + ">\n" +
				"PREFIX foaf: <" + FOAF.NAMESPACE + ">\n" +
				"PREFIX ex: <" + ex + ">\n" +
				"select (count(?persons) as ?count) {\n" +
				"   ?persons rdf:type ex:Artist ;\n"
				+ "          ex:homeAddress ?country .\n"
				+ " ?country ex:country \"Spain\" . }";

		SailRepository fedRepo = new SailRepository(fed);
		fedRepo.init();

		IntStream.range(0, 100).parallel().forEach(j -> {

			try (SailRepositoryConnection fedRepoConn = fedRepo.getConnection()) {

				fedRepoConn.begin();
				TupleQuery query = fedRepoConn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
				try (TupleQueryResult eval = query.evaluate()) {
					if (eval.hasNext()) {
						Value next = eval.next().getValue("count");
						assertEquals(1, ((Literal) next).intValue());
					} else {
						fail("No result");
					}
				}

				fedRepoConn.commit();
			}

		});

		fedRepo.shutDown();
	}
}
 
Example 10
Source File: JSONLDInternalTripleCallback.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public JSONLDInternalTripleCallback(RDFHandler nextHandler, ValueFactory vf) {
	this(nextHandler, vf, new ParserConfig(), new ParseErrorLogger(), nodeID -> vf.createBNode(nodeID),
			() -> vf.createBNode());
}
 
Example 11
Source File: Fact.java    From rya with Apache License 2.0 4 votes vote down vote up
@Override
public void readFields(final DataInput in) throws IOException {
    derivation = null;
    final int tripleLength = in.readInt();
    if (tripleLength == 0) {
        triple = null;
    }
    else {
        final byte[] tripleBytes = new byte[tripleLength];
        in.readFully(tripleBytes);
        final String tripleString = new String(tripleBytes, StandardCharsets.UTF_8);
        final String[] parts = tripleString.split(SEP);
        final ValueFactory factory = SimpleValueFactory.getInstance();
        final String context = parts[0];
        Resource s = null;
        final IRI p = factory.createIRI(parts[2]);
        Value o = null;
        // Subject: either bnode or URI
        if (parts[1].startsWith("_")) {
            s = factory.createBNode(parts[1].substring(2));
        }
        else {
            s = factory.createIRI(parts[1]);
        }
        // Object: literal, bnode, or URI
        if (parts[3].startsWith("_")) {
            o = factory.createBNode(parts[3].substring(2));
        }
        else if (parts[3].startsWith("\"")) {
            //literal: may have language or datatype
            final int close = parts[3].lastIndexOf("\"");
            final int length = parts[3].length();
            final String label = parts[3].substring(1, close);
            if (close == length - 1) {
                // Just a string enclosed in quotes
                o = factory.createLiteral(label);
            }
            else {
                final String data = parts[3].substring(close + 1);
                if (data.startsWith(LiteralLanguageUtils.LANGUAGE_DELIMITER)) {
                    final String lang = data.substring(1);
                    o = factory.createLiteral(label, lang);
                }
                else if (data.startsWith("^^<")) {
                    o = factory.createLiteral(label, factory.createIRI(
                        data.substring(3, data.length() - 1)));
                }
            }
        }
        else {
            o = factory.createIRI(parts[3]);
        }
        // Create a statement with or without context
        if (context.isEmpty()) {
            triple = VF.createStatement(s, p, o);
        }
        else {
            triple = VF.createStatement(s, p, o, factory.createIRI(context));
        }
    }
    useful = in.readBoolean();
    if (in.readBoolean()) {
        derivation = new Derivation();
        derivation.readFields(in);
    }
}
 
Example 12
Source File: MultiProjectionProcessorIT.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void showProcessorWorks() 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);

    // Create a topology for the Query that will be tested.
    final String sparql =
            "CONSTRUCT {" +
                "_:b a <urn:movementObservation> ; " +
                "<urn:location> ?location ; " +
                "<urn:direction> ?direction ; " +
            "}" +
            "WHERE {" +
                "?thing <urn:corner> ?location ." +
                "?thing <urn:compass> ?direction." +
            "}";

    final String bNodeId = UUID.randomUUID().toString();
    final TopologyBuilder builder = new TopologyFactory().build(sparql, statementsTopic, resultsTopic, () -> bNodeId);

    // Create the statements that will be input into the query.
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final List<VisibilityStatement> statements = new ArrayList<>();
    statements.add( new VisibilityStatement(
            vf.createStatement(vf.createIRI("urn:car1"), vf.createIRI("urn:compass"), vf.createIRI("urn:NW")), "a") );
    statements.add( new VisibilityStatement(
            vf.createStatement(vf.createIRI("urn:car1"), vf.createIRI("urn:corner"), vf.createIRI("urn:corner1")), "a") );

    // Make the expected results.
    final Set<VisibilityStatement> expected = new HashSet<>();
    final BNode blankNode = vf.createBNode(bNodeId);

    expected.add(new VisibilityStatement(vf.createStatement(blankNode, RDF.TYPE, vf.createIRI("urn:movementObservation")), "a"));
    expected.add(new VisibilityStatement(vf.createStatement(blankNode, vf.createIRI("urn:direction"), vf.createIRI("urn:NW")), "a"));
    expected.add(new VisibilityStatement(vf.createStatement(blankNode, vf.createIRI("urn:location"), vf.createIRI("urn:corner1")), "a"));

    // Run the test.
    RyaStreamsTestUtil.runStreamProcessingTest(kafka, statementsTopic, resultsTopic, builder, statements, expected, VisibilityStatementDeserializer.class);
}
 
Example 13
Source File: SourceSelectorImplConfigBase.java    From semagrow with Apache License 2.0 4 votes vote down vote up
public Resource export(Model graph) {
    ValueFactory vf = SimpleValueFactory.getInstance();
    BNode implNode = vf.createBNode();
    graph.add(implNode, SemagrowSchema.SOURCESELECTOR, vf.createLiteral(getType()));
    return implNode;
}
 
Example 14
Source File: NTriplesUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Parses an N-Triples bNode, creates an object for it using the supplied ValueFactory and returns this object.
 *
 * @param nTriplesBNode The N-Triples bNode to parse.
 * @param valueFactory  The ValueFactory to use for creating the object.
 * @return An object representing the parsed bNode.
 * @throws IllegalArgumentException If the supplied bNode could not be parsed correctly.
 */
public static BNode parseBNode(String nTriplesBNode, ValueFactory valueFactory) throws IllegalArgumentException {
	if (nTriplesBNode.startsWith("_:")) {
		return valueFactory.createBNode(nTriplesBNode.substring(2));
	} else {
		throw new IllegalArgumentException("Not a legal N-Triples Blank Node: " + nTriplesBNode);
	}
}