Java Code Examples for org.openrdf.repository.RepositoryResult#hasNext()

The following examples show how to use org.openrdf.repository.RepositoryResult#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: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void write(DataSource ds, String contextName) {
    RepositoryConnection conn = null;
    try {
        conn = repo.getConnection();
        RepositoryResult<Resource> contexts = conn.getContextIDs();
        while (contexts.hasNext()) {
            Resource context = contexts.next();
            if (context.stringValue().equals(contextName)) {
                write(ds, conn, context);
            }
        }
    } catch (RepositoryException x) {
        throw new TripleStoreException(String.format("Writing on %s", ds), x);
    } finally {
        closeConnection(conn, "Writing on " + ds);
    }
}
 
Example 2
Source File: CustomSesameDataset.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
/**
 * Tuple pattern query - find all statements with the pattern, where null is
 * a wildcard
 * 
 * @param s
 *            subject (null for wildcard)
 * @param p
 *            predicate (null for wildcard)
 * @param o
 *            object (null for wildcard)
 * @param contexts
 *            varArgs contexts (use default graph if null)
 * @return serialized graph of results
 */
public List<Statement> tuplePattern(Resource s, URI p, Value o,
		Resource... contexts) {
	try {
		RepositoryConnection con = currentRepository.getConnection();
		try {
			RepositoryResult<Statement> repres = con.getStatements(s, p, o,
					true, contexts);
			ArrayList<Statement> reslist = new ArrayList<Statement>();
			while (repres.hasNext()) {
				reslist.add(repres.next());
			}
			return reslist;
		} finally {
			con.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 3
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public Set<String> contextNames() {
    HashSet<String> names = new HashSet<>();
    RepositoryConnection conn = null;
    try {
        conn = repo.getConnection();
        RepositoryResult<Resource> rs = conn.getContextIDs();
        while (rs.hasNext()) {
            names.add(rs.next().stringValue());
        }
        return names;
    } catch (RepositoryException x) {
        LOG.error("getting context names : {}", x.getMessage());
    } finally {
        closeConnection(conn, "Getting context names");
    }
    return names;
}
 
Example 4
Source File: TestBigdataSailRemoteRepository.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test the CONTEXTS method.
 */
public void test_CONTEXTS() throws Exception {

	if (getTestMode() != TestMode.quads)
		return;

    doInsertbyURL("POST", packagePath
            + "test_estcard.trig");
    
    final RepositoryResult<Resource> contexts = cxn.getContextIDs();
    
    int size = 0;
    while (contexts.hasNext()) {
    	contexts.next();
    	size++;
    }
    
    assertEquals(3, size);
    
}
 
Example 5
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public List<PrefixNamespace> getNamespaces() {
    List<PrefixNamespace> namespaces = new ArrayList<>();
    RepositoryConnection cnx = null;
    try {
        cnx = repo.getConnection();
        RepositoryResult<Namespace> ns = cnx.getNamespaces();
        while (ns.hasNext()) {
            Namespace namespace = ns.next();
            namespaces.add(new PrefixNamespace(namespace.getPrefix(), namespace.getName()));
        }
    } catch (RepositoryException x) {
        throw new TripleStoreException("Getting namespaces", x);
    } finally {
        closeConnection(cnx, "Getting namespaces");
    }
    return namespaces;
}
 
Example 6
Source File: SesameTransformationRepairSwitchSet.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void activate(final Collection<SesameSwitchSetMatch> matches) throws RepositoryException {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI currentPositionProperty = vf.createURI(BASE_PREFIX + CURRENTPOSITION);

	for (final SesameSwitchSetMatch match : matches) {
		final Resource sw = match.getSw();
		final Value position = match.getPosition();
		final Value currentPosition = match.getCurrentPosition();

		final RepositoryResult<Statement> statementsToRemove = con.getStatements(sw, currentPositionProperty, currentPosition, false);
		while (statementsToRemove.hasNext()) {
			con.remove(statementsToRemove.next());
		}

		con.add(sw, currentPositionProperty, position);
	}
}
 
Example 7
Source File: Util.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
public static <T> Iterator<T> toResultIterator (final RepositoryResult<T> result) {
	
	return new AbstractIterator<T>() {

		@Override
		protected T computeNext() {
			
			try {
				
				if(result.hasNext()) {
					return result.next();
				}
				
			} catch (RepositoryException e) {
				LOGGER.error(MessageCatalog._00025_CUMULUS_SYSTEM_INTERNAL_FAILURE_MSG + " Could not compute next result.", e);
			}
			return endOfData();
		}
	};
}
 
Example 8
Source File: AugurTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
public void test_naive() throws Exception {
	ValueFactory vf = con.getValueFactory();
	final URI Bean = vf.createURI(NS, "Bean");
	final URI name = vf.createURI(NS, "name");
	final URI parent = vf.createURI(NS, "parent");
	final URI friend = vf.createURI(NS, "friend");
	long start = System.currentTimeMillis();
	RepositoryResult<Statement> beans = con.getStatements(null, RDF.TYPE, Bean);
	while (beans.hasNext()) {
		Statement st = beans.next();
		Resource bean = st.getSubject();
		QueryResults.asList(con.getStatements(bean, name, null));
		RepositoryResult<Statement> match;
		match = con.getStatements(bean, parent, null);
		while (match.hasNext()) {
			QueryResults.asList(con.getStatements((Resource)match.next().getObject(), name, null));
		}
		match = con.getStatements(bean, friend, null);
		while (match.hasNext()) {
			QueryResults.asList(con.getStatements((Resource)match.next().getObject(), name, null));
		}
	}
	long end = System.currentTimeMillis();
	System.out.println((end - start) / 1000.0);
}
 
Example 9
Source File: ListTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
private int getSize(Repository repository) throws RepositoryException {
	int size = 0;
	RepositoryConnection connection = null;
	RepositoryResult<Statement> iter = null;
	try {
		connection = repository.getConnection();
		iter = connection.getStatements(null, null, null, false);
		while (iter.hasNext()) {
			iter.next();
			++size;
		}
	} finally {
		if (iter != null)
			iter.close();
		if (connection != null)
			connection.close();
	}
	return size;
}
 
Example 10
Source File: TypeManager.java    From anno4j with Apache License 2.0 6 votes vote down vote up
public Set<URI> getTypes(Resource res) throws RepositoryException {
	if (!readTypes)
		return Collections.emptySet();
	RepositoryResult<Statement> match = conn.getStatements(res, RDF.TYPE, null);
	try {
		if (!match.hasNext())
			return Collections.emptySet();
		Value obj = match.next().getObject();
		if (obj instanceof URI && !match.hasNext())
			return Collections.singleton((URI) obj);
		Set<URI> types = new HashSet<URI>(4);
		if (obj instanceof URI) {
			types.add((URI) obj);
		}
		while (match.hasNext()) {
			obj = match.next().getObject();
			if (obj instanceof URI) {
				types.add((URI) obj);
			}
		}
		return types;
	} finally {
		match.close();
	}
}
 
Example 11
Source File: StressTest_ClosedByInterrupt_RW.java    From database with GNU General Public License v2.0 5 votes vote down vote up
private Collection<Statement> getStatementsForContext(final RepositoryConnection conn,
        final URI context) throws RepositoryException {
    RepositoryResult<Statement> res = null;
    final Collection<Statement> statements = new ArrayList<Statement>();
    try {
        res = conn.getStatements(null, null, null, false, context);
        while (res.hasNext()) {
            statements.add(res.next());
        }
    } finally {
        res.close();
    }
    return statements;
}
 
Example 12
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the #of solutions in a result set.
 * 
 * @param result
 *           The result set.
 * 
 * @return The #of solutions.
 */
static protected long countResults(final RepositoryResult<Statement> result)
      throws Exception {

   try {
      long i;
      for (i = 0; result.hasNext(); i++) {
         result.next();
      }
      return i;
   } finally {
      result.close();
   }

}
 
Example 13
Source File: RDFModelParser.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private void importRepository(RepositoryConnection connection, TripleSink sink) throws RepositoryException {
	RepositoryResult<Statement> statements = null;
	try {
		statements=connection.getStatements(null, null, null, false);
		SesameModelParser tripleParser=new SesameModelParser(getNamespaces(connection));
		while(statements.hasNext()) {
			sink.addTriple(tripleParser.parseStatement(statements.next()));
		}
	} finally {
		closeQuietly(statements, "Could not close results after parsing statements");
	}
}
 
Example 14
Source File: RDFSingleDataSet.java    From mustard with MIT License 5 votes vote down vote up
@Override
public List<Statement> getStatements(Resource subject, URI predicate, Value object, boolean allowInference) {
	List<Statement> resGraph = new ArrayList<Statement>();

	try {
		RepositoryConnection repCon = rdfRep.getConnection();

		try {
			
			
			RepositoryResult<Statement> statements = repCon.getStatements(subject, predicate, object, allowInference);

			try {
				while (statements.hasNext()) {
					resGraph.add(statements.next());
				}
			}
			finally {
				statements.close();
			}
		} finally {
			repCon.close();
		}

	} catch (Exception e) {
		e.printStackTrace();
	}

	return resGraph;		
}
 
Example 15
Source File: SesameTransformationInjectSwitchSet.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<SesameSwitchSetInjectMatch> matches) throws RepositoryException {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI currentPositionProperty = vf.createURI(BASE_PREFIX + CURRENTPOSITION);

	for (final SesameSwitchSetInjectMatch match : matches) {
		final URI sw = match.getSw();
		final RepositoryResult<Statement> statements = con.getStatements(sw, currentPositionProperty, null, true);
		if (!statements.hasNext()) {
			continue;
		}

		final Statement oldStatement = statements.next();

		// delete old statement
		con.remove(oldStatement);

		// get next enum value
		final URI currentPositionURI = (URI) oldStatement.getObject();
		final String currentPositionRDFString = currentPositionURI.getLocalName();
		final String currentPositionString = RdfHelper.removePrefix(Position.class, currentPositionRDFString);
		final Position currentPosition = Position.valueOf(currentPositionString);
		final Position newCurrentPosition = Position.values()[(currentPosition.ordinal() + 1) % Position.values().length];
		final String newCurrentPositionString = RdfHelper.addEnumPrefix(newCurrentPosition);
		final URI newCurrentPositionUri = vf.createURI(BASE_PREFIX + newCurrentPositionString);

		// set new value
		con.add(sw, currentPositionProperty, newCurrentPositionUri);
	}
}
 
Example 16
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private static int statementsCount(RepositoryConnection conn, Resource ctx) {
    int counter = 0;
    try {
        RepositoryResult<Statement> statements = conn.getStatements(null, null, null, true, ctx);
        while (statements.hasNext()) {
            counter++;
            statements.next();
        }
    } catch (RepositoryException e) {
        LOG.error(e.getMessage());
    }
    return counter;
}
 
Example 17
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void print(PrintStream out) {
    out.println("TripleStore based on Blazegraph");
    RepositoryConnection conn;
    try {
        conn = repo.getConnection();
        try {
            RepositoryResult<Resource> ctxs = conn.getContextIDs();
            while (ctxs.hasNext()) {
                Resource ctx = ctxs.next();
                int size = statementsCount(conn, ctx);
                out.println("    " + ctx + " : " + size);
                if (PRINT_ALL_STATEMENTS) {
                    RepositoryResult<Statement> statements = conn.getStatements(null, null, null, true, ctx);
                    while (statements.hasNext()) {
                        Statement statement = statements.next();
                        out.println("        " + statement.getSubject() + " " + statement.getPredicate() + " "
                            + statement.getObject());
                    }
                }
            }
        } finally {
            closeConnection(conn, "Printing");
        }
    } catch (RepositoryException e) {
        LOG.error(e.getMessage());
    }
}
 
Example 18
Source File: QueryServlet.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Void call() throws Exception {

  BigdataSailRepositoryConnection conn = null;
  
  try {

      conn = getQueryConnection();

      String mimeType = null;
      RDFFormat format = null;
      if (mimeTypes!=null) {
          mimeTypesLoop:
      	while(mimeTypes.hasMoreElements()) {
          	for (String mt:mimeTypes.nextElement().split(",")) {
          		mt = mt.trim();
               RDFFormat fmt = RDFWriterRegistry.getInstance()
                   .getFileFormatForMIMEType(mt);
               if (conn.getTripleStore().isQuads() && (mt.equals(RDFFormat.NQUADS.getDefaultMIMEType()) || mt.equals(RDFFormat.TURTLE.getDefaultMIMEType())) || !conn.getTripleStore().isQuads() && fmt != null) {
                   mimeType = mt;
                   format = fmt;
                   break mimeTypesLoop;
               }
          	}
          }
      }
      if (format==null) {
          if(conn.getTripleStore().isQuads()){
              mimeType = RDFFormat.NQUADS.getDefaultMIMEType();
          } else {
              mimeType = RDFFormat.NTRIPLES.getDefaultMIMEType();
          }
          format = RDFWriterRegistry.getInstance()
              .getFileFormatForMIMEType(mimeType);
      }
      resp.setContentType(mimeType);

      final OutputStream os = resp.getOutputStream();

      final RDFWriter w = RDFWriterRegistry.getInstance().get(format)
          .getWriter(os);

      RepositoryResult<Statement> stmts = null;

      try {
          w.startRDF();
          stmts = conn.getStatements(s, p, o, includeInferred, c);
          while(stmts.hasNext()){
              w.handleStatement(stmts.next());
          }
          w.endRDF();
      } finally {
          if (stmts != null) {
              stmts.close();
          }
          os.flush();
          os.close();
      }

      return null;
  } finally {
      if (conn != null) {
          conn.close();
      }
  }
}
 
Example 19
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
private static void copyNamespacesToModel(RepositoryConnection conn, Model m) throws RepositoryException {
    RepositoryResult<Namespace> ns = conn.getNamespaces();
    while (ns.hasNext()) {
        m.setNamespace(ns.next());
    }
}
 
Example 20
Source File: RestApiGetContextsTask.java    From database with GNU General Public License v2.0 2 votes vote down vote up
@Override
public Void call() throws Exception {

   BigdataSailRepositoryConnection conn = null;
   try {

      conn = getQueryConnection();

      final StringWriter w = new StringWriter();

      final RepositoryResult<Resource> it = conn.getContextIDs();

      try {

         final XMLBuilder t = new XMLBuilder(w);

         final Node root = t.root("contexts");

         while (it.hasNext()) {

            root.node("context").attr("uri", it.next()).close();

         }

         root.close();

      } finally {

         it.close();

      }

      buildResponse(QueryServlet.HTTP_OK, QueryServlet.MIME_APPLICATION_XML,
            w.toString());

      return null;

   } finally {

      if (conn != null) {

         conn.close();

      }

   }

}