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

The following examples show how to use org.openrdf.repository.RepositoryResult#close() . 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: 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 2
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 3
Source File: DocumentFragmentTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public void testAddSingleElement() throws Exception {
	ObjectFactory of = con.getObjectFactory();
	Entity entity = con.addDesignation(of.createObject(), Entity.class);
	Document doc = parse("<element/>");
	DocumentFragment frag = doc.createDocumentFragment();
	frag.appendChild(doc.getDocumentElement());
	entity.setXML(frag);
	RepositoryResult<Statement> results = con.getStatements(entity.getResource(), pred, null);
	String xml = results.next().getObject().stringValue();
	results.close();
	assertEquals("<element/>", xml);
}
 
Example 4
Source File: DocumentFragmentTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public void testAddMultipleElements() throws Exception {
	ObjectFactory of = con.getObjectFactory();
	Entity entity = con.addDesignation(of.createObject(), Entity.class);
	Document doc = parse("<element><first/><second/></element>");
	DocumentFragment frag = doc.createDocumentFragment();
	frag.appendChild(doc.getDocumentElement().getFirstChild());
	frag.appendChild(doc.getDocumentElement().getLastChild());
	entity.setXML(frag);
	RepositoryResult<Statement> results = con.getStatements(entity.getResource(), pred, null);
	String xml = results.next().getObject().stringValue();
	results.close();
	assertEquals("<first/><second/>", xml);
}
 
Example 5
Source File: DocumentFragmentTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public void testAddNamespaceElement() throws Exception {
	String xml = "<a:Box xmlns:a=\"http://example.org/a#\" required=\"true\"><a:widget size=\"10\"> </a:widget><a:grommit id=\"23\"> text </a:grommit></a:Box>";
	Document doc = parse(xml);
	ObjectFactory of = con.getObjectFactory();
	Entity entity = con.addDesignation(of.createObject(), Entity.class);
	DocumentFragment frag = doc.createDocumentFragment();
	frag.appendChild(doc.getDocumentElement());
	entity.setXML(frag);
	RepositoryResult<Statement> resuts = con.getStatements(entity.getResource(), pred, null);
	String label = resuts.next().getObject().stringValue();
	resuts.close();
	assertEquals(xml, label);
}
 
Example 6
Source File: BigdataSailRemoteRepositoryConnectionTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testGetStatements() throws RepositoryException {
	final RepositoryResult<Statement> stmts = con.getStatements(s, p, o, includeInferred, c);
	try {
		assertEquals(EncodeDecodeValue.encodeValue(s), remote.data.opts.getRequestParam("s"));
		assertEquals(EncodeDecodeValue.encodeValue(p), remote.data.opts.getRequestParam("p"));
		assertEquals(EncodeDecodeValue.encodeValue(o), remote.data.opts.getRequestParam("o"));
		assertEquals(EncodeDecodeValue.encodeValue(c), remote.data.opts.getRequestParam("c"));
		assertEquals(Boolean.toString(includeInferred), remote.data.opts.getRequestParam(RemoteRepositoryDecls.INCLUDE_INFERRED));
	} finally {
		stmts.close();
	}
}
 
Example 7
Source File: TestTicket967.java    From database with GNU General Public License v2.0 5 votes vote down vote up
private void executeTest(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, RDFHandlerException,
		IOException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		try {
			conn.setAutoCommit(false);
			final ValueFactory vf = conn.getValueFactory();
	        final URI uri = vf.createURI("os:/elem/example");
	        // run a query which looks for a statement and then adds it if it is not found.
	        addDuringQueryExec(conn, uri, RDF.TYPE, vf.createURI("os:class/Clazz"));
	        // now try to export the statements.
        	final RepositoryResult<Statement> stats = conn.getStatements(null, null, null, false);
	        try {
	        	// materialize the newly added statement.
	        	stats.next();
	        } catch (RuntimeException e) {
	        	fail(e.getLocalizedMessage(), e); // With Bigdata this fails
	        } finally {
	        	stats.close();
	        }
	        conn.rollback(); // discard the result (or commit, but do something to avoid a logged warning from Sesame).
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 8
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 9
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 10
Source File: TestTicket348.java    From database with GNU General Public License v2.0 5 votes vote down vote up
private void executeTest(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, RDFHandlerException,
		IOException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		try {
			conn.setAutoCommit(false);
			final ValueFactory vf = conn.getValueFactory();
	        final URI uri = vf.createURI("os:/elem/example");
	        // run a query which looks for a statement and then adds it if it is not found.
	        addDuringQueryExec(conn, uri, RDF.TYPE, vf.createURI("os:class/Clazz"));
	        // now try to export the statements.
        	final RepositoryResult<Statement> stats = conn.getStatements(null, null, null, false);
	        try {
	        	// materialize the newly added statement.
	        	stats.next();
	        } catch (RuntimeException e) {
	        	fail(e.getLocalizedMessage(), e); // With Bigdata this fails
	        } finally {
	        	stats.close();
	        }
	        conn.rollback(); // discard the result (or commit, but do something to avoid a logged warning from Sesame).
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 11
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 12
Source File: RDFModelParser.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private void closeQuietly(RepositoryResult<?> results, String message) {
	if(results!=null) {
		try {
			results.close();
		} catch (OpenRDFException e) {
			if(LOGGER.isWarnEnabled()) {
				LOGGER.warn(message,e);
			}
		}
	}
}
 
Example 13
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 14
Source File: AST2BOpUpdate.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
     * Copy all statements from the sourceGraph to the targetGraph.
     * <p>
     * Note: The SILENT keyword for ADD, COPY, and MOVE indicates that the
     * implementation SHOULD/MAY report an error if the source graph does not
     * exist (the spec is not consistent here across those operations). Further,
     * there is no explicit create/drop of graphs in bigdata so it WOULD be Ok
     * if we just ignored the SILENT keyword.
     */
    private static void copyStatements(final AST2BOpUpdateContext context,
            final boolean silent, final BigdataURI sourceGraph,
            final BigdataURI targetGraph) throws RepositoryException {

        if (log.isDebugEnabled())
            log.debug("sourceGraph=" + sourceGraph + ", targetGraph="
                    + targetGraph);
        
        if (!silent) {

//            assertGraphNotEmpty(context, sourceGraph);

        }
        
        final RepositoryResult<Statement> result = context.conn.getStatements(
                null/* s */, null/* p */, null/* o */,
                context.isIncludeInferred(), new Resource[] { sourceGraph });
        
        try {

            context.conn.add(result, new Resource[] { targetGraph });

        } finally {

            result.close();

        }

    }
 
Example 15
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 2 votes vote down vote up
@Test
public void testInsertWhereWithBlankNode()
	throws Exception
{
	logger.debug("executing testInsertWhereWithBlankNode");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append(" INSERT { ?s ex:complexAge [ rdf:value ?age; rdfs:label \"old\" ] . } ");
	update.append(" WHERE { ?s ex:age ?age . ");
	update.append(" } ");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	URI age = f.createURI(EX_NS, "age");
	URI complexAge = f.createURI(EX_NS, "complexAge");

	assertTrue(con.hasStatement(bob, age, null, true));

	operation.execute();

	RepositoryResult<Statement> sts = con.getStatements(bob, complexAge, null, true);

	assertTrue(sts.hasNext());

	Value v1 = sts.next().getObject();

	sts.close();

	sts = con.getStatements(null, RDF.VALUE, null, true);

	assertTrue(sts.hasNext());

	Value v2 = sts.next().getSubject();

	assertEquals(v1, v2);

	sts.close();

	String query = getNamespaceDeclarations()
			+ " SELECT ?bn ?age ?l WHERE { ex:bob ex:complexAge ?bn. ?bn rdf:value ?age. ?bn rdfs:label ?l .} ";

	TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate();

	assertTrue(result.hasNext());

	BindingSet bs = result.next();

	assertFalse(result.hasNext());

}
 
Example 16
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();

      }

   }

}