Java Code Examples for info.aduna.iteration.CloseableIteration#hasNext()

The following examples show how to use info.aduna.iteration.CloseableIteration#hasNext() . 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: RDFList.java    From anno4j with Apache License 2.0 6 votes vote down vote up
Value getFirst(Resource list) {
	if (list == null)
		return null;
	try {
		CloseableIteration<Value, RepositoryException> stmts;
		stmts = getValues(list, RDF.FIRST, null);
		try {
			if (stmts.hasNext())
				return stmts.next();
			return null;
		} finally {
			stmts.close();
		}
	} catch (RepositoryException e) {
		throw new ObjectStoreException(e);
	}
}
 
Example 2
Source File: RDFList.java    From anno4j with Apache License 2.0 6 votes vote down vote up
Resource getRest(Resource list) {
	if (list == null)
		return null;
	try {
		CloseableIteration<Value, RepositoryException> stmts;
		stmts = getValues(list, RDF.REST, null);
		try {
			if (stmts.hasNext())
				return (Resource) stmts.next();
			return null;
		} finally {
			stmts.close();
		}
	} catch (RepositoryException e) {
		throw new ObjectStoreException(e);
	}
}
 
Example 3
Source File: RDFSContainer.java    From anno4j with Apache License 2.0 6 votes vote down vote up
private int findSize() throws RepositoryException {
	CloseableIteration<? extends Statement, RepositoryException> iter;
	HashSet<URI> set = new HashSet<URI>();
	ObjectConnection conn = getObjectConnection();
	iter = conn.getStatements(getResource(), null, null);
	try {
		while (iter.hasNext()) {
			set.add(iter.next().getPredicate());
		}
	} finally {
		iter.close();
	}
	int index = 0;
	while (set.contains(getMemberPredicate(index)))
		index++;
	return index;
}
 
Example 4
Source File: RDFStoreTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
protected int verifyQueryResult(
		CloseableIteration<? extends BindingSet, QueryEvaluationException> resultIter,
		int expectedBindingCount)
	throws QueryEvaluationException
{
	int resultCount = 0;

	while (resultIter.hasNext()) {
		BindingSet resultBindings = resultIter.next();
		resultCount++;

		assertEquals("Wrong number of binding names for binding set", expectedBindingCount,
				resultBindings.getBindingNames().size());

		int bindingCount = 0;
		Iterator<Binding> bindingIter = resultBindings.iterator();
		while (bindingIter.hasNext()) {
			bindingIter.next();
			bindingCount++;
		}

		assertEquals("Wrong number of bindings in binding set", expectedBindingCount, bindingCount);
	}

	return resultCount;
}
 
Example 5
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private int getTotalStatementCount(RepositoryConnection connection)
	throws RepositoryException
{
	CloseableIteration<? extends Statement, RepositoryException> iter = connection.getStatements(null,
			null, null, true);

	try {
		int size = 0;

		while (iter.hasNext()) {
			iter.next();
			++size;
		}

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

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

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

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

		if (yyy instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements(null, RDF.TYPE, xxx, true);

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

				Resource aaa = t1.getSubject();

				boolean added = addInferredStatement(aaa, RDF.TYPE, yyy);
				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 applyRuleRdfs3_2()
	throws SailException
{
	int nofInferred = 0;

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

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

		Resource aaa = nt.getSubject();
		Value zzz = nt.getObject();

		if (aaa instanceof URI && zzz instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements(null, (URI)aaa, null, true);

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

				Value uuu = t1.getObject();
				if (uuu instanceof Resource) {
					boolean added = addInferredStatement((Resource)uuu, RDF.TYPE, zzz);
					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
/**
 * rrr rdfs:subPropertyOf  ppp 
 * rrr nrl:inverseProperty sss 
 * ppp nrl:inverseProperty qqq 
 * -->
 * sss rdfs:subPropertyOf  qqq
 * @return
 * @throws SailException
 */
private int applyRuleN2b()
throws SailException
{
	int nofInferred = 0;
	Iterator<Statement> it1 = this.newThisIteration.match(null, RDFS.SUBPROPERTYOF, null);
	while (it1.hasNext()) {
		Statement stmt1 = it1.next();
		Resource rrr = stmt1.getSubject();
		Value ppp = stmt1.getObject();
		if(ppp instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> it2;
			it2 = getWrappedConnection().getStatements(rrr,NRL_InverseProperty, null, true);
			while (it2.hasNext()) {
				Statement stmt2 = it2.next();
				Value sss = stmt2.getObject();
				if(sss instanceof Resource) {
					CloseableIteration<? extends Statement, SailException> it3;
					it3 = getWrappedConnection().getStatements( (Resource) ppp,NRL_InverseProperty, null, true);
					while (it3.hasNext()) {
						Statement stmt3 = it3.next();
						Value qqq = stmt3.getObject();
						if( qqq instanceof Resource) {
							boolean added = addInferredStatement((Resource)sss, RDFS.SUBPROPERTYOF, qqq);
							if (added) {
								nofInferred++;
							}
						}
					}
					it3.close();
				}
			}
			it2.close();
		}
	}
	return nofInferred;
}
 
Example 10
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 11
Source File: ContextsHandler.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
@Override
public ModelAndView serve(final Repository repository, final HttpServletRequest request, final HttpServletResponse response)
		throws Exception {
	Map<String, Object> model = new HashMap<String, Object>();
	TupleQueryResultWriterFactory factory = ProtocolUtil.getAcceptableService(request, response,
			TupleQueryResultWriterRegistry.getInstance());

	if (METHOD_GET.equals(request.getMethod())) {
		List<String> columnNames = Arrays.asList("contextID");
		List<BindingSet> contexts = new ArrayList<BindingSet>();
		RepositoryConnection repositoryCon = repository.getConnection();
		synchronized (repositoryCon) {
			try {
				CloseableIteration<? extends Resource, RepositoryException> contextIter = repositoryCon.getContextIDs();

				try {
					while (contextIter.hasNext()) {
						BindingSet bindingSet = new ListBindingSet(columnNames, contextIter.next());
						contexts.add(bindingSet);
					}
				} finally {
					contextIter.close();
				}
			} catch (RepositoryException e) {
				throw new ServerHTTPException("Repository error: " + e.getMessage(), e);
			}
		}
		model.put(QueryResultView.QUERY_RESULT_KEY, new TupleQueryResultImpl(columnNames, contexts));
	}

	model.put(QueryResultView.FILENAME_HINT_KEY, "contexts");
	model.put(QueryResultView.FACTORY_KEY, factory);
	model.put(QueryResultView.HEADERS_ONLY, METHOD_HEAD.equals(request.getMethod()));
	return new ModelAndView(TupleQueryResultView.getInstance(), model);
}
 
Example 12
Source File: ForwardChainingRDFSInferencerConnection.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int applyRuleRdfs11_1()
	throws SailException
{
	int nofInferred = 0;

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

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

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

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

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

				Value zzz = t1.getObject();

				if (zzz instanceof Resource) {
					boolean added = addInferredStatement(xxx, RDFS.SUBCLASSOF, zzz);
					if (added) {
						nofInferred++;
					}
				}
			}
			t1Iter.close();
		}
	}

	return nofInferred;
}
 
Example 13
Source File: ForwardChainingRDFSInferencerConnection.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
	 * xxx nrl:inverseProperty yyy
	 * aaa xxx bbb 
	 * -->
	 * bbb yyy aaa
	 * @return
	 * @throws SailException
	 */
	private int applyRuleN1a()
	throws SailException
{
	int nofInferred = 0;
	
	Iterator<Statement> ntIter = this.newThisIteration.match(null, NRL_InverseProperty, null);

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

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

		if (xxx instanceof URI && yyy instanceof URI) {
			// apply to triples using the property
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements(null, (URI)xxx, null, true);

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

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

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

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

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

		Resource yyy = nt.getSubject();
		Value zzz = nt.getObject();

		if (zzz instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements(null, RDFS.SUBCLASSOF, yyy, true);

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

				Resource xxx = t1.getSubject();

				boolean added = addInferredStatement(xxx, RDFS.SUBCLASSOF, zzz);
				if (added) {
					nofInferred++;
				}
			}
			t1Iter.close();
		}
	}

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

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

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

		Resource bbb = nt.getSubject();
		Value ccc = nt.getObject();

		if (ccc instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements(null, RDFS.SUBPROPERTYOF, bbb, true);

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

				Resource aaa = t1.getSubject();
				boolean added = addInferredStatement(aaa, RDFS.SUBPROPERTYOF, ccc);
				if (added) {
					nofInferred++;
				}
			}
			t1Iter.close();
		}
	}

	return nofInferred;
}
 
Example 16
Source File: CBD.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
     * Consume statements from the source iterator, adding new statements into a
     * collection and adding new blank node {@link IV}s into another collection.
     * 
     * @param src
     *            The statements to be consumed.
     * @param stmts
     *            The set of statements in the description of the resources from
     *            the previous round(s) (if any).
     * @param bnodes_tm1
     *            The blank node {@link IV}s already known on entry to the
     *            current round. This is empty for on entry to the first
     *            expansion round.
     * 
     * @return The set of blank node {@link IV}s not previous encountered in the
     *         CBD expansion.
     * 
     * @throws QueryEvaluationException
     */
    private static Set<IV<?, ?>> consumeStatements(
            final CloseableIteration<BigdataStatement, QueryEvaluationException> src,
            final Set<BigdataStatement> stmts, final Set<IV<?, ?>> bnodes_tm1)
            throws QueryEvaluationException {

        final Set<IV<?, ?>> newBnodes = new LinkedHashSet<IV<?, ?>>();
        try {

            while (src.hasNext()) {

                final BigdataStatement stmt = src.next();

//                /*
//                 * A statement of the form
//                 * 
//                 * ?stmtN rdf:subject <term>
//                 * 
//                 * where <term> is a blank node.
//                 */
//                final boolean foo = stmt.getPredicate().equals(RDF.SUBJECT)
//                        && bnodes_tm1.contains(stmt.getObject());
                
                if (stmts.add(stmt)) {

                    /*
                     * New blank node IVs can only be encountered for new
                     * statements.
                     * 
                     * TODO Consider using an ISPO => BigdataStatement map for
                     * the statements so we can avoid duplicate entries for
                     * BigdataStatements having different blank nodes but the
                     * same IVs for those blank nodes.
                     */
                    
                    collectBNodeIVs(bnodes_tm1, newBnodes,
                            getBNodeIV(stmt.getSubject()));

                    collectBNodeIVs(bnodes_tm1, newBnodes,
                            getBNodeIV(stmt.getObject()));

                    collectBNodeIVs(bnodes_tm1, newBnodes,
                            getBNodeIV(stmt.getContext()));

                }

            }
            
            return newBnodes;

        } finally {

            src.close();

        }

    }
 
Example 17
Source File: ASTEvalHelper.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Evaluate a boolean query.
 * 
 * @param store
 *            The {@link AbstractTripleStore} having the data.
 * @param astContainer
 *            The {@link ASTContainer}.
 * @param globallyScopedBS
 *            The initial solution to kick things off.
 *            
 * @return <code>true</code> if there are any solutions to the query.
 * 
 * @throws QueryEvaluationException
 */
static public boolean evaluateBooleanQuery(
        final AbstractTripleStore store,
        final ASTContainer astContainer,
        final BindingSet globallyScopedBS,
        final Dataset dataset)
        throws QueryEvaluationException {

    final AST2BOpContext context = new AST2BOpContext(astContainer, store);

    final DeferredResolutionResult resolved;
    try {
    	// @see https://jira.blazegraph.com/browse/BLZG-1176
        resolved = ASTDeferredIVResolution.resolveQuery(
            store, astContainer, globallyScopedBS, dataset, context);
    } catch (MalformedQueryException e) {
        throw new QueryEvaluationException(e.getMessage(), e);
    }

    if (resolved.dataset != null) {
        astContainer.getOriginalAST().setDataset(
            new DatasetNode(resolved.dataset, false/* update */));
    }


    // Clear the optimized AST.
    astContainer.clearOptimizedAST();

    // Batch resolve Values to IVs and convert to bigdata binding set.
    final IBindingSet[] globallyScopedBSAsList = toBindingSet(resolved.bindingSet) ;

    // Convert the query (generates an optimized AST as a side-effect).
    AST2BOpUtility.convert(context, globallyScopedBSAsList);

    // The optimized AST.
    final QueryRoot optimizedQuery = astContainer.getOptimizedAST();

    // Note: We do not need to materialize anything for ASK.
    final boolean materializeProjectionInQuery = context.materializeProjectionInQuery
            && !optimizedQuery.hasSlice();

    CloseableIteration<BindingSet, QueryEvaluationException> itr = null;
    try {
        itr = ASTEvalHelper.evaluateQuery(
                astContainer,
                context,
                materializeProjectionInQuery,
                new IVariable[0]// required
                );
        return itr.hasNext();
    } finally {
        if (itr != null) {
            /**
             * Ensure query is terminated. An interrupt during hasNext()
             * should cause the query to terminate through itr.close().
             * 
             * @see <a
             *      href="https://sourceforge.net/apps/trac/bigdata/ticket/707">
             *      BlockingBuffer.close() does not unblock threads </a>
             */
            itr.close();
        }
    }
}
 
Example 18
Source File: ExportKB.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
     * Exports all told statements associated with the last commit point for the
     * KB.
     * 
     * @throws IOException
     * @throws SailException
     * @throws RDFHandlerException
     */
    public void exportData() throws IOException, SailException,
            RDFHandlerException {
        prepare();
//        final BigdataSail sail = new BigdataSail(kb);
//        try {
//            sail.initialize();
//            final SailConnection conn = sail.getReadOnlyConnection();
//            try {
                final CloseableIteration<? extends Statement, SailException> itr = conn
                        .getStatements(null/* s */, null/* p */, null/* o */,
                                includeInferred, new Resource[] {}/* contexts */);
                try {
                    final File file = new File(kbdir, "data."
                            + format.getDefaultFileExtension()+".gz");
                    System.out.println("Writing " + file);
                    final OutputStream os = new GZIPOutputStream(
                            new FileOutputStream(file));
                    try {
                        final RDFWriter writer = RDFWriterRegistry
                                .getInstance().get(format).getWriter(os);
                        writer.startRDF();
                        while (itr.hasNext()) {
                            final Statement stmt = itr.next();
                            writer.handleStatement(stmt);
                        }
                        writer.endRDF();
                    } finally {
                        os.close();
                    }
                } finally {
                    itr.close();
                }
//            } finally {
//                conn.close();
//            }
//        } finally {
//            sail.shutDown();
//        }

    }
 
Example 19
Source File: ProxyBigdataSailTestCase.java    From database with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Verifies that the iterator visits the specified objects in some arbitrary
 * ordering and that the iterator is exhausted once all expected objects
 * have been visited. The implementation uses a selection without
 * replacement "pattern".
 */
@SuppressWarnings("unchecked")
static public void assertSameIterationAnyOrder(String msg,
        final Resource[] expected,
        final CloseableIteration<?, ? extends Exception> actual)
        throws Exception {

    // Populate a map that we will use to realize the match and
    // selection without replacement logic.

    final int nrange = expected.length;

    final java.util.Map range = new java.util.HashMap();

    for (int j = 0; j < nrange; j++) {

        range.put(expected[j], expected[j]);

    }

    // Do selection without replacement for the objects visited by
    // iterator.

    for (int j = 0; j < nrange; j++) {

        if (!actual.hasNext()) {

            fail(msg + ": Index exhausted while expecting more object(s)"
                    + ": index=" + j);

        }

        final Object actualObject = actual.next();

        if (range.remove(actualObject) == null) {

            fail("Object not expected" + ": index=" + j + ", object="
                    + actualObject);

        }

    }

    if (actual.hasNext()) {

        fail("Iterator will deliver too many objects.");

    }

}
 
Example 20
Source File: SAILGASEngine.java    From database with GNU General Public License v2.0 2 votes vote down vote up
@Override
public VertexDistribution getDistribution(final Random r) {

    try {

        final VertexDistribution sample = new VertexDistribution(r);

        final CloseableIteration<? extends Statement, SailException> citr = cxn
                .getStatements(null/* s */, null/* p */, null /* o */,
                        includeInferred, defaultContext);

        try {

            while (citr.hasNext()) {

                final Statement st = citr.next();

                if (!(st.getObject() instanceof Resource)) {
                    
                    // This is a property value, not an edge.
                    continue;
                }

                if (st.getSubject().equals(st.getObject())) {

                    // ignore self-loops.
                    continue;

                }

                sample.addOutEdgeSample(st.getSubject());

                sample.addInEdgeSample((Resource) st.getObject());

            }

        } finally {

            citr.close();

        }

        return sample;

    } catch (SailException ex) {

        throw new RuntimeException(ex);
        
    }
    
}