Java Code Examples for org.openrdf.model.Statement#getPredicate()

The following examples show how to use org.openrdf.model.Statement#getPredicate() . 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: AbstractDataAndSPARQLTestCase.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Override
            public void handleStatement(final Statement stmt)
                    throws RDFHandlerException {

                final Resource s = stmt.getSubject();
                final URI p = stmt.getPredicate();
                final Value o = stmt.getObject();
                final Resource c = stmt.getContext() == null ? this.context
                        : stmt.getContext();

//                if (log.isDebugEnabled())
//                    log.debug("<" + s + "," + p + "," + o + "," + c + ">");

                buffer.add(s, p, o, c, StatementEnum.Explicit);

                n++;

            }
 
Example 2
Source File: ForwardChainingRDFSInferencerConnection.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private int applyRuleX1()
	throws SailException
{
	int nofInferred = 0;

	String prefix = RDF.NAMESPACE + "_";
	Iterator<Statement> iter = this.newThisIteration.match(null, null, null);

	while (iter.hasNext()) {
		Statement st = iter.next();

		URI predNode = st.getPredicate();
		String predURI = predNode.toString();

		if (predURI.startsWith(prefix) && isValidPredicateNumber(predURI.substring(prefix.length()))) {
			boolean added = addInferredStatement(predNode, RDF.TYPE, RDFS.CONTAINERMEMBERSHIPPROPERTY);
			if (added) {
				nofInferred++;
			}
		}
	}

	return nofInferred;
}
 
Example 3
Source File: Util.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a statement to an array of its RDF values.
 * 
 * @param stmt - statement to be converted
 * @return array containing the RDF values comprised in the statement.
 */
public static Value[] toValueArray(Statement stmt) {

	Value[] out = new Value[stmt.getContext() == null ? 3 : 4];
	out[0] = stmt.getSubject();
	out[1] = stmt.getPredicate();
	out[2] = stmt.getObject();

	if (stmt.getContext() != null) {
		out[3] = stmt.getContext();
	}

	return out;
}
 
Example 4
Source File: TurtlePrettyPrinter.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleStatement(Statement st) throws RDFHandlerException {
	Resource subject = st.getSubject();
	URI predicate = st.getPredicate();
	Value object = st.getObject();
	trace("Added triple (%s,%s,%s).",subject,predicate,object);
	graph.add(subject, predicate, object);
}
 
Example 5
Source File: RESCALLinkPredictor.java    From mustard with MIT License 5 votes vote down vote up
public double predict(Statement stmt) {
	// Relation
	if (!(stmt.getObject() instanceof Literal)) {
		return dotProduct(computeRow(entityEmb.get(stmt.getSubject()), latentFac.get(stmt.getPredicate())), entityEmb.get((Resource) stmt.getObject()));
	} else { // Literal
		Pair<URI, Literal> p = new Pair<URI,Literal>(stmt.getPredicate(), (Literal) stmt.getObject());
		return dotProduct(entityEmb.get(stmt.getSubject()), attributeEmb.get(p));	
	}
}
 
Example 6
Source File: ForwardChainingRDFSInferencerConnection.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
	 * aaa xxx bbb 
	 * xxx nrl:inverseProperty yyy
	 * -->
	 * bbb yyy aaa
	 * @return
	 * @throws SailException
	 */
	private int applyRuleN1b()
	throws SailException
{
	int nofInferred = 0;
	
	Iterator<Statement> ntIter = this.newThisIteration.match(null, null, null);

	while (ntIter.hasNext()) {
		Statement nt = ntIter.next();

		Resource xxx = nt.getPredicate();

		CloseableIteration<? extends Statement, SailException> t1Iter;
		t1Iter = getWrappedConnection().getStatements(xxx,NRL_InverseProperty, null, true);

		while (t1Iter.hasNext()) {
			Statement t1 = t1Iter.next();

			Value yyy = t1.getObject();
			if (yyy instanceof URI) {
				Resource aaa = 	nt.getSubject();
				Value bbb = nt.getObject();
				boolean added = addInferredStatement((Resource)bbb, (URI) yyy, aaa);
				if (added) {
					nofInferred++;
				}
			}
		}
		t1Iter.close();
	}

	return nofInferred;
}
 
Example 7
Source File: ForwardChainingRDFSInferencerConnection.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int applyRuleRdfs7_1()
	throws SailException
{
	int nofInferred = 0;

	Iterator<Statement> ntIter = this.newThisIteration.match(null, null, null);

	while (ntIter.hasNext()) {
		Statement nt = ntIter.next();

		Resource xxx = nt.getSubject();
		URI aaa = nt.getPredicate();
		Value yyy = nt.getObject();

		CloseableIteration<? extends Statement, SailException> t1Iter;
		t1Iter = getWrappedConnection().getStatements(aaa, RDFS.SUBPROPERTYOF, null, true);

		while (t1Iter.hasNext()) {
			Statement t1 = t1Iter.next();

			Value bbb = t1.getObject();
			if (bbb instanceof URI) {
				boolean added = addInferredStatement(xxx, (URI)bbb, yyy);
				if (added) {
					nofInferred++;
				}
			}
		}
		t1Iter.close();
	}

	return nofInferred;
}
 
Example 8
Source File: ForwardChainingRDFSInferencerConnection.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int applyRuleRdfs3_1()
	throws SailException
{
	int nofInferred = 0;

	Iterator<Statement> ntIter = this.newThisIteration.match(null, null, null);

	while (ntIter.hasNext()) {
		Statement nt = ntIter.next();

		URI aaa = nt.getPredicate();
		Value uuu = nt.getObject();

		if (uuu instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements(aaa, RDFS.RANGE, null, true);

			while (t1Iter.hasNext()) {
				Statement t1 = t1Iter.next();

				Value zzz = t1.getObject();
				if (zzz instanceof Resource) {
					boolean added = addInferredStatement((Resource)uuu, RDF.TYPE, zzz);
					if (added) {
						nofInferred++;
					}
				}
			}
			t1Iter.close();
		}
	}
	return nofInferred;
}
 
Example 9
Source File: ForwardChainingRDFSInferencerConnection.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int applyRuleRdfs2_1()
	throws SailException
{
	int nofInferred = 0;

	Iterator<Statement> ntIter = this.newThisIteration.match(null, null, null);

	while (ntIter.hasNext()) {
		Statement nt = ntIter.next();

		Resource xxx = nt.getSubject();
		URI aaa = nt.getPredicate();

		CloseableIteration<? extends Statement, SailException> t1Iter;
		t1Iter = getWrappedConnection().getStatements(aaa, RDFS.DOMAIN, null, true);

		while (t1Iter.hasNext()) {
			Statement t1 = t1Iter.next();

			Value zzz = t1.getObject();
			if (zzz instanceof Resource) {
				boolean added = addInferredStatement(xxx, RDF.TYPE, zzz);
				if (added) {
					nofInferred++;
				}
			}
		}
		t1Iter.close();
	}

	return nofInferred;
}
 
Example 10
Source File: SesameHTTPRepositoryTest.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * test statements related operations.
 * @throws Exception Exception the test would fails if exception occurs
 */
@Test
public void testStatements() throws Exception {
	//test add Statements
	for (final String tripleAsString : _data) {

		final Statement triple = parseNX(tripleAsString).iterator().next();
		final Value[] query = new Value[] { triple.getSubject(), triple.getPredicate(), triple.getObject() };
		TRIPLE_STORE.removeData(query);

		//ensure the repository contains not statements to be added
		int howManyTriplesForPattern = numOfRes(TRIPLE_STORE.query(query));
		assertEquals("This triple " + tripleAsString + " mustn't exist on store", 0, howManyTriplesForPattern);

		String uri = BASE_URI + Protocol.REPOSITORIES + "/" + REPO_ID + "/" + Protocol.STATEMENTS;
		final ServletInputStream stream = new ServletInputStream() {
			final InputStream _inputStream = new ByteArrayInputStream(tripleAsString.getBytes(Environment.CHARSET_UTF8));

			@Override
			public int read() throws IOException {
				return _inputStream.read();
			}
		};
		final HttpServletRequest request = mockHttpRequest(uri, METHOD_PUT);
		when(request.getInputStream()).thenReturn(stream);
		when(request.getContentType()).thenReturn(MIMETYPE_TXT_N3);
		when(request.getCharacterEncoding()).thenReturn(UTF_8);
		File tmp = WebTestUtils.tmpFile();
		final ServletOutputStream servletOutputStream = new StubServletOutputStream(tmp);
		final HttpServletResponse response = mock(HttpServletResponse.class);
		when(response.getOutputStream()).thenReturn(servletOutputStream);

		_classUnderTest.service(request, response);

		verify(response).setStatus(HttpServletResponse.SC_NO_CONTENT);

		int howManyTriplesOnTheStore = numOfRes(TRIPLE_STORE.query(query));
		assertEquals(1, howManyTriplesOnTheStore);
	}
}
 
Example 11
Source File: LoadPdb.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public static void readSomeData(Repository repo) throws Exception {

		RepositoryConnection cxn = repo.getConnection();
		int counter = 0;
		try {

			RepositoryResult<Statement> stmts = cxn.getStatements(null, null, null, true /*
																						* include
																						* inferred
																						*/);
			while (stmts.hasNext()) {
				Statement stmt = stmts.next();
				Resource s = stmt.getSubject();
				URI p = stmt.getPredicate();
				Value o = stmt.getObject();
				// do something with the statement
				LOG.info(stmt);

				// cast to BigdataStatement to get at additional information
				BigdataStatement bdStmt = (BigdataStatement) stmt;
				if (bdStmt.isExplicit()) {
					// do one thing
				} else if (bdStmt.isInferred()) {
					// do another thing
				} else { // bdStmt.isAxiom()
					// do something else
				}
				LOG.info(bdStmt.getStatementType());
				counter++;
			}

		} finally {
			// close the repository connection
			cxn.close();

			LOG.info("Number of Triples: " + counter);
		}

	}
 
Example 12
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testURISerialization()
	throws Exception
{
	testCon.add(bob, name, nameBob);

	Statement st;
	RepositoryResult<Statement> statements = testCon.getStatements(null, null, null, false);
	try {
		st = statements.next();
	}
	finally {
		statements.close();
	}

	URI uri = st.getPredicate();

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ObjectOutputStream out = new ObjectOutputStream(baos);
	out.writeObject(uri);
	out.close();

	ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
	ObjectInputStream in = new ObjectInputStream(bais);
	URI deserializedURI = (URI)in.readObject();
	in.close();

	assertThat(deserializedURI, is(equalTo(uri)));

	assertThat(testCon.hasStatement(bob, uri, nameBob, true), is(equalTo(true)));
	assertThat(testCon.hasStatement(bob, deserializedURI, nameBob, true), is(equalTo(true)));
}
 
Example 13
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPreparedGraphQuery()
	throws Exception
{
	testCon.add(alice, name, nameAlice, context2);
	testCon.add(alice, mbox, mboxAlice, context2);
	testCon.add(context2, publisher, nameAlice);
	testCon.add(bob, name, nameBob, context1);
	testCon.add(bob, mbox, mboxBob, context1);
	testCon.add(context1, publisher, nameBob);
	StringBuilder queryBuilder = new StringBuilder(128);
       queryBuilder.append(" prefix foaf: <" + FOAF_NS + ">");
	queryBuilder.append(" construct ");
	queryBuilder.append(" where { ?s foaf:name ?name . ?s foaf:mbox ?mbox . }");
	GraphQuery query = testCon.prepareGraphQuery(QueryLanguage.SPARQL, queryBuilder.toString());
	query.setBinding(NAME, nameBob);
	GraphQueryResult result = query.evaluate();
	try {
		assertThat(result, is(notNullValue()));
		assertThat(result.hasNext(), is(equalTo(true)));
		while (result.hasNext()) {
			Statement st = result.next();
			URI predicate = st.getPredicate();
			assertThat(predicate, anyOf(is(equalTo(name)), is(equalTo(mbox))));
			Value object = st.getObject();
			if (name.equals(predicate)) {
				assertEquals("unexpected value for name: " + object, nameBob, object);
			}
			else {
				assertThat(predicate, is(equalTo(mbox)));
				assertEquals("unexpected value for mbox: " + object, mboxBob, object);
			}
		}
	}
	finally {
		result.close();
	}
}
 
Example 14
Source File: SampleCode.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Read some statements from a repository.
 * 
 * @param repo
 * @param uri
 * @throws Exception
 */
public void readSomeData(Repository repo, URI uri) throws Exception {
    
    /*
     * With MVCC, you read from a historical state to avoid blocking and
     * being blocked by writers.  BigdataSailRepository.getQueryConnection
     * gives you a view of the repository at the last commit point.
     */
    RepositoryConnection cxn;
    if (repo instanceof BigdataSailRepository) { 
        cxn = ((BigdataSailRepository) repo).getReadOnlyConnection();
    } else {
        cxn = repo.getConnection();
    }
    
    try {
        
        RepositoryResult<Statement> stmts = 
            cxn.getStatements(uri, null, null, true /* include inferred */);
        while (stmts.hasNext()) {
            Statement stmt = stmts.next();
            Resource s = stmt.getSubject();
            URI p = stmt.getPredicate();
            Value o = stmt.getObject();
            // do something with the statement
            log.info(stmt);
            
            // cast to BigdataStatement to get at additional information
            BigdataStatement bdStmt = (BigdataStatement) stmt;
            if (bdStmt.isExplicit()) {
                // do one thing
            } else if (bdStmt.isInferred()) {
                // do another thing
            } else { // bdStmt.isAxiom()
                // do something else
            }
            log.info(bdStmt.getStatementType());
        }
        
    } finally {
        // close the repository connection
        cxn.close();
    }
    
}
 
Example 15
Source File: Schema.java    From cumulusrdf with Apache License 2.0 4 votes vote down vote up
public void index(final Store store, final ITopLevelDictionary dictionary) throws DataAccessLayerException {

		PersistentSet<byte[]> clazzes_cassandra = new PersistentSet<byte[]>(byte[].class, COL_CLAZZES);
		PersistentSet<byte[]> d_props_cassandra = new PersistentSet<byte[]>(byte[].class, COL_D_PROPS);
		PersistentSet<byte[]> o_props_cassandra = new PersistentSet<byte[]>(byte[].class, COL_O_PROPS);

		try {

			long counter = 0;

			LOG.info(MessageCatalog._00063_CREATING_NEW_SCHEMA);

			for (final Iterator<Statement> iterator = store.query(new Value[] {null, RDF.TYPE, null}); iterator.hasNext();) {

				// TODO it should be sufficient to just "getID" here
				clazzes_cassandra.add(dictionary.getID(iterator.next().getObject(), false));

				if (++counter % 1000 == 0) {
					LOG.info(MessageCatalog._00064_HOW_MANY_TYPE_TRIPLES, counter);
				}
			}

			LOG.info(MessageCatalog._00065_HOW_MANY_CLASSES_FOUND, clazzes_cassandra.size());
			counter = 0;

			/*
			 * probe each class for instances ...
			 */
			for (byte[] clazz_id : clazzes_cassandra) {

				final Value clazz = dictionary.getValue(clazz_id, false);
				LOG.info(MessageCatalog._00066_SAMPLING_OVER, clazz);

				for (Iterator<Statement> clazz_iter = store.query(new Value[] {null, RDF.TYPE, clazz}); clazz_iter.hasNext();) {

					for (final Iterator<Statement> instance_iter = store.query(
							new Value[] {clazz_iter.next().getSubject(), null, null}, 100); instance_iter.hasNext();) {

						final Statement triple = instance_iter.next();
						final Value object = triple.getObject();
						final URI predicate = triple.getPredicate();
						
						if (object instanceof Literal) {
							// TODO it should be sufficient to just "getID" here
							d_props_cassandra.add(dictionary.getID(predicate, true));
						} else {
							// TODO it should be sufficient to just "getID" here
							o_props_cassandra.add(dictionary.getID(predicate, true));
						}

						if (++counter % 1000 == 0) {
							LOG.info(MessageCatalog._00067_HOW_MANY_INSTANCE_TRIPLES, counter);
						}
					}
				}
			}

			LOG.info(MessageCatalog._00068_SAMPLING_COMPLETED, counter);
		} catch (final CumulusStoreException exception) {
			LOG.error(MessageCatalog._00025_CUMULUS_SYSTEM_INTERNAL_FAILURE, exception);
		}
	}
 
Example 16
Source File: BigdataEdge.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public BigdataEdge(final Statement stmt, final BigdataGraph graph) {
	super(stmt.getPredicate(), graph);
	
	this.stmt = stmt;
}
 
Example 17
Source File: BigdataGraph.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Convert a unit of RDF data to an atomic unit of PG data.
 */
protected BigdataGraphAtom toGraphAtom(final Statement stmt) {

    final URI s = (URI) stmt.getSubject();
    final URI p = (URI) stmt.getPredicate();
    final Value o = stmt.getObject();
    
    return toGraphAtom(s, p, o);
    
}
 
Example 18
Source File: VocabBuilder.java    From database with GNU General Public License v2.0 2 votes vote down vote up
public void handleStatement(final Statement stmt)
		throws RDFHandlerException {

	final URI p = stmt.getPredicate();

	// A. Count number of occurrences for predicate at hand
	UriFrequency predFrequency = preds.get(p);

	if (predFrequency == null) {

		preds.put(p, predFrequency = new UriFrequency(p));

		if (log.isDebugEnabled())
			log.debug("New " + p + " : total=" + preds.size());

	}

	predFrequency.cnt++;

	
	// B. For typing statements, also count occurrence of the type
	if (stmt.getPredicate().equals(RDF.TYPE)) {
		
		final Value o = stmt.getObject();

		if (o instanceof URI) {
		
			UriFrequency typeFrequency = types.get((URI)o);
	
			if (typeFrequency == null) {
	
				types.put((URI)o, typeFrequency = new UriFrequency((URI)o));
	
				if (log.isDebugEnabled())
					log.debug("New " + (URI)o + " : total=" + types.size());
	
			}
			
			typeFrequency.cnt++;
		}
	}
}