Java Code Examples for org.eclipse.rdf4j.repository.RepositoryConnection#getValueFactory()

The following examples show how to use org.eclipse.rdf4j.repository.RepositoryConnection#getValueFactory() . 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: RyaAccumuloSailFactoryTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
public void testAddStatement() throws Exception {
    SailRepositoryFactory f = new SailRepositoryFactory();
    Repository r = f.getRepository(getConfig());
    r.initialize();
    RepositoryConnection rc = r.getConnection();

    ValueFactory vf = rc.getValueFactory();
    Statement s = vf.createStatement(vf.createIRI("u:a"), vf.createIRI("u:b"), vf.createIRI("u:c"));

    assertFalse(rc.hasStatement(s, false));

    rc.add(s);

    Assert.assertTrue(rc.hasStatement(s, false));
    rc.close();
}
 
Example 2
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 3
Source File: WikiDataReification.java    From inception with Apache License 2.0 6 votes vote down vote up
@Override
public void upsertQualifier(RepositoryConnection aConnection, KnowledgeBase kb,
        KBQualifier aQualifier)
{
    // According to the Wikidata reification scheme, the predicate of the property prefix is
    // replaced when the property is used as a qualifier, e.g.
    // p:P186 -> pq:P186
    String propStatementIri = aQualifier.getProperty().getIdentifier().replace(PREFIX_PROP,
            PREFIX_PROP_QUALIFIER);
    
    ValueFactory vf = aConnection.getValueFactory();
    Set<Statement> newTriples = singleton(
            vf.createStatement(vf.createIRI(aQualifier.getStatement().getStatementId()),
                    vf.createIRI(propStatementIri),
                    valueMapper.mapQualifierValue(aQualifier, vf)));

    upsert(aConnection, aQualifier.getOriginalTriples(), newTriples);

    aQualifier.getStatement().addQualifier(aQualifier);
    aQualifier.setOriginalTriples(newTriples);
}
 
Example 4
Source File: NoReification.java    From inception with Apache License 2.0 5 votes vote down vote up
@Override
public void upsertStatement(RepositoryConnection aConnection, KnowledgeBase kb,
        KBStatement aStatement)
{
    ValueFactory vf = aConnection.getValueFactory();
    Set<Statement> newTriples = singleton(vf.createStatement(
            vf.createIRI(aStatement.getInstance().getIdentifier()), 
            vf.createIRI(aStatement.getProperty().getIdentifier()), 
            valueMapper.mapStatementValue(aStatement, vf)));
    
    upsert(aConnection, aStatement.getOriginalTriples(), newTriples);
   
    aStatement.setOriginalTriples(newTriples);
}
 
Example 5
Source File: WikiDataReification.java    From inception with Apache License 2.0 5 votes vote down vote up
@Override
public void upsertStatement(RepositoryConnection aConnection, KnowledgeBase aKB,
        KBStatement aStatement)
{
    if (!aStatement.getProperty().getIdentifier().startsWith(PREFIX_PROP)) {
        throw new IllegalArgumentException(
                "With WikiDataReification, properties must start " + "with [" + PREFIX_PROP
                        + "] but found [" + aStatement.getProperty().getIdentifier() + "]");
    }
    
    ValueFactory vf = aConnection.getValueFactory();
    
    // According to the Wikidata reification scheme, the predicate of the secondary triple
    // corresponds to the predicate of the primary triple with the prefix replaced, e.g.
    // p:P186 -> ps:P186
    String propStatementIri = aStatement.getProperty().getIdentifier().replace(PREFIX_PROP,
            PREFIX_PROP_STATEMENT);
    
    IRI subject = vf.createIRI(aStatement.getInstance().getIdentifier());
    IRI pred1 =  vf.createIRI(aStatement.getProperty().getIdentifier());
    Resource stmt = aStatement.getStatementId() != null
            ? vf.createIRI(aStatement.getStatementId())
            : vf.createIRI(generateStatementIdentifier(aConnection, aKB));
            //: vf.createBNode();
    IRI pred2 =  vf.createIRI(propStatementIri);
    Value value = valueMapper.mapStatementValue(aStatement, vf);
    
    // Generate all the triples that are to be stored by this statement
    // Add primary and secondary triple
    Set<Statement> statements = new HashSet<>();
    statements.add(vf.createStatement(subject, pred1, stmt));
    statements.add(vf.createStatement(stmt, pred2, value));
    
    // Delete all original triples except the ones which we would re-create anyway
    upsert(aConnection, aStatement.getOriginalTriples(), statements);
    
    // Update the original triples and the statement ID in the statement
    aStatement.setStatementId(stmt.stringValue());
    aStatement.setOriginalTriples(statements);
}
 
Example 6
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 7
Source File: NoReification.java    From inception with Apache License 2.0 5 votes vote down vote up
private void delete(RepositoryConnection aConnection, KnowledgeBase kb, String aIdentifier)
{
    ValueFactory vf = aConnection.getValueFactory();
    IRI iri = vf.createIRI(aIdentifier);
    try (RepositoryResult<Statement> subStmts = aConnection.getStatements(iri, null, null);
            RepositoryResult<Statement> predStmts = aConnection.getStatements(null, iri, null);
            RepositoryResult<Statement> objStmts = aConnection.getStatements(null, null, iri)) {
        aConnection.remove(subStmts);
        aConnection.remove(predStmts);
        aConnection.remove(objStmts);
    }
}
 
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: NoReification.java    From inception with Apache License 2.0 4 votes vote down vote up
private String generateIdentifier(RepositoryConnection aConn, KnowledgeBase aKB)
{
    ValueFactory vf = aConn.getValueFactory();
    // default value of basePrefix is IriConstants.INCEPTION_NAMESPACE
    return aKB.getBasePrefix() + vf.createBNode().getID();
}
 
Example 10
Source File: WikiDataReification.java    From inception with Apache License 2.0 4 votes vote down vote up
@Override
public String generatePropertyIdentifier(RepositoryConnection aConn, KnowledgeBase aKB)
{
    ValueFactory vf = aConn.getValueFactory();
    return PREFIX_PROP + vf.createBNode().getID();
}
 
Example 11
Source File: WikiDataReification.java    From inception with Apache License 2.0 4 votes vote down vote up
private String generateIdentifier(RepositoryConnection aConn, KnowledgeBase aKB)
{
    ValueFactory vf = aConn.getValueFactory();
    // default value of basePrefix is IriConstants.INCEPTION_NAMESPACE
    return aKB.getBasePrefix() + vf.createBNode().getID();
}
 
Example 12
Source File: KBConcept.java    From inception with Apache License 2.0 4 votes vote down vote up
public void write(RepositoryConnection aConn, KnowledgeBase kb)
{
    ValueFactory vf = aConn.getValueFactory();
    IRI subject = vf.createIRI(identifier);

    originalStatements.clear();

    Statement typeStmt = vf.createStatement(subject, kb.getTypeIri(), kb.getClassIri());
    originalStatements.add(typeStmt);
    aConn.add(typeStmt);

    if (isNotBlank(name)) {
        Literal nameLiteral;
        if (language != null) {
            nameLiteral = vf.createLiteral(name, language);
        }
        else if (kb.getDefaultLanguage() != null) {
            nameLiteral = vf.createLiteral(name, kb.getDefaultLanguage());
        }
        else {
            nameLiteral = vf.createLiteral(name);
        }
        Statement nameStmt = vf.createStatement(subject, kb.getLabelIri(), nameLiteral);
        originalStatements.add(nameStmt);
        aConn.add(nameStmt);
    }
    if (isNotBlank(description)) {
        Literal descriptionLiteral;
        if (language == null) {
            descriptionLiteral = vf.createLiteral(description);
        }
        else {
            descriptionLiteral = vf.createLiteral(description, language);
        }
        Statement descStmt = vf
            .createStatement(subject, kb.getDescriptionIri(), descriptionLiteral);
        originalStatements.add(descStmt);
        aConn.add(descStmt);
    }

    /* Commented out until the functionality which uses them is actually implemented
    Statement closedStmt = vf.createStatement(subject, CLOSED, vf.createLiteral(closed));
    originalStatements.add(closedStmt);
    aConn.add(closedStmt);

    Statement abstractStmt = vf
        .createStatement(subject, ABSTRACT, vf.createLiteral(abstractClass));
    originalStatements.add(abstractStmt);
    aConn.add(abstractStmt);
    */
}
 
Example 13
Source File: KBInstance.java    From inception with Apache License 2.0 4 votes vote down vote up
public void write(RepositoryConnection aConn, KnowledgeBase kb)
{
    ValueFactory vf = aConn.getValueFactory();
    IRI subject = vf.createIRI(identifier);

    originalStatements.clear();

    Statement typeStmt = vf.createStatement(subject, kb.getTypeIri(),
            vf.createIRI(type.toString()));
    originalStatements.add(typeStmt);
    aConn.add(typeStmt);

    if (isNotBlank(name)) {
        Literal nameLiteral;
        if (language != null) {
            nameLiteral = vf.createLiteral(name, language);
        }
        else if (kb.getDefaultLanguage() != null) {
            nameLiteral = vf.createLiteral(name, kb.getDefaultLanguage());
        }
        else {
            nameLiteral = vf.createLiteral(name);
        }
        Statement nameStmt = vf.createStatement(subject, kb.getLabelIri(), nameLiteral);
        originalStatements.add(nameStmt);
        aConn.add(nameStmt);
    }

    if (isNotBlank(description)) {
        Literal descriptionLiteral;
        if (language == null) {
            descriptionLiteral = vf.createLiteral(description);
        }
        else {
            descriptionLiteral = vf.createLiteral(description, language);
        }
        Statement descStmt = vf
            .createStatement(subject, kb.getDescriptionIri(), descriptionLiteral);
        originalStatements.add(descStmt);
        aConn.add(descStmt);
    }
}
 
Example 14
Source File: KBProperty.java    From inception with Apache License 2.0 4 votes vote down vote up
public void write(RepositoryConnection aConn, KnowledgeBase kb)
{
    ValueFactory vf = aConn.getValueFactory();
    IRI subject = vf.createIRI(identifier);

    originalStatements.clear();

    Statement typeStmt = vf.createStatement(subject, kb.getTypeIri(), kb.getPropertyTypeIri());
    originalStatements.add(typeStmt);
    aConn.add(typeStmt);

    if (isNotBlank(name)) {
        Literal nameLiteral;
        if (language != null) {
            nameLiteral = vf.createLiteral(name, language);
        }
        else if (kb.getDefaultLanguage() != null) {
            nameLiteral = vf.createLiteral(name, kb.getDefaultLanguage());
        }
        else {
            nameLiteral = vf.createLiteral(name);
        }
        Statement nameStmt = vf.createStatement(subject, kb.getPropertyLabelIri(), nameLiteral);
        originalStatements.add(nameStmt);
        aConn.add(nameStmt);
    }

    if (isNotBlank(description)) {
        Literal descriptionLiteral;
        if (language == null) {
            descriptionLiteral = vf.createLiteral(description);
        }
        else {
            descriptionLiteral = vf.createLiteral(description, language);
        }
        Statement descStmt = vf.createStatement(subject, kb.getPropertyDescriptionIri(),
                descriptionLiteral);
        originalStatements.add(descStmt);
        aConn.add(descStmt);
    }

    if (domain != null) {
        Statement domainStmt = vf
            .createStatement(subject, RDFS.DOMAIN, vf.createLiteral(domain.toString()));
        originalStatements.add(domainStmt);
        aConn.add(domainStmt);
    }

    if (range != null) {
        Statement rangeStmt = vf
            .createStatement(subject, RDFS.RANGE, vf.createLiteral(range.toString()));
        originalStatements.add(rangeStmt);
        aConn.add(rangeStmt);
    }
}
 
Example 15
Source File: IsolationLevelTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void insertTestStatement(RepositoryConnection connection, int i) throws RepositoryException {
	ValueFactory vf = connection.getValueFactory();
	Literal lit = vf.createLiteral(Integer.toString(i), XMLSchema.INTEGER);
	connection.add(vf.createIRI("http://test#s" + i), vf.createIRI("http://test#p"), lit,
			vf.createIRI("http://test#context_" + i));
}
 
Example 16
Source File: CustomGraphQueryInferencerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void runTest(final CustomGraphQueryInferencer inferencer) throws RepositoryException, RDFParseException,
		IOException, MalformedQueryException, UpdateExecutionException {
	// Initialize
	Repository sail = new SailRepository(inferencer);
	sail.initialize();
	RepositoryConnection connection = sail.getConnection();
	try {
		connection.begin();
		connection.clear();
		connection.add(new StringReader(initial), BASE, RDFFormat.TURTLE);

		// Test initial inferencer state
		Collection<Value> watchPredicates = inferencer.getWatchPredicates();
		assertThat(watchPredicates).hasSize(testData.predCount);
		Collection<Value> watchObjects = inferencer.getWatchObjects();
		assertThat(watchObjects).hasSize(testData.objCount);
		Collection<Value> watchSubjects = inferencer.getWatchSubjects();
		assertThat(watchSubjects).hasSize(testData.subjCount);
		ValueFactory factory = connection.getValueFactory();
		if (resourceFolder.startsWith(PREDICATE)) {
			assertThat(watchPredicates.contains(factory.createIRI(BASE, "brotherOf"))).isTrue();
			assertThat(watchPredicates.contains(factory.createIRI(BASE, "parentOf"))).isTrue();
		} else {
			IRI bob = factory.createIRI(BASE, "Bob");
			IRI alice = factory.createIRI(BASE, "Alice");
			assertThat(watchSubjects).contains(bob, alice);
			assertThat(watchObjects).contains(bob, alice);
		}

		// Test initial inferencing results
		assertThat(Iterations.asSet(connection.getStatements(null, null, null, true)))
				.hasSize(testData.initialCount);

		// Test results after removing some statements
		connection.prepareUpdate(QueryLanguage.SPARQL, delete).execute();
		assertThat(Iterations.asSet(connection.getStatements(null, null, null, true)))
				.hasSize(testData.countAfterRemove);

		// Tidy up. Storage gets re-used for subsequent tests, so must clear here,
		// in order to properly clear out any inferred statements.
		connection.clear();
		connection.commit();
	} finally {
		connection.close();
	}
	sail.shutDown();
}
 
Example 17
Source File: RDFInserter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Creates a new RDFInserter object that preserves bnode IDs and that does not enforce any context upon statements
 * that are reported to it.
 *
 * @param con The connection to use for the add operations.
 */
public RDFInserter(RepositoryConnection con) {
	super(con.getValueFactory());
	this.con = con;
}