Java Code Examples for org.openrdf.repository.Repository

The following examples show how to use org.openrdf.repository.Repository. These examples are extracted from open source projects. 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
@Override
public void add(TripleStore source) {
    Objects.requireNonNull(source);
    Repository sourceRepository;
    if (source instanceof TripleStoreBlazegraph) {
        sourceRepository = ((TripleStoreBlazegraph) source).repo;
        RepositoryConnection sourceConn = null;
        try {
            sourceConn = sourceRepository.getConnection();
            copyFrom(sourceConn);
        } catch (RepositoryException e) {
            LOG.error("Connecting to the source repository : {}", e.getMessage());
        } finally {
            if (sourceConn != null) {
                closeConnection(sourceConn, "Copying from source");
            }
        }
    } else {
        throw new TripleStoreException(String.format("Add to %s from source %s is not supported",
            getImplementationName(), source.getImplementationName()));
    }
}
 
Example 2
public static TupleQueryResult executeSelectQuery(final Repository repo, final String query,
		final QueryLanguage ql) throws OpenRDFException  {

	RepositoryConnection cxn;
	if (repo instanceof BigdataSailRepository) {
		cxn = ((BigdataSailRepository) repo).getReadOnlyConnection();
	} else {
		cxn = repo.getConnection();
	}

	try {

		final TupleQuery tupleQuery = cxn.prepareTupleQuery(ql, query);
		tupleQuery.setIncludeInferred(true /* includeInferred */);
		return tupleQuery.evaluate();
		
	} finally {
		// close the repository connection
		cxn.close();
	}
}
 
Example 3
Source Project: cumulusrdf   Source File: GraphHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get all statements and export them as RDF.
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param response the HttpServletResponse object
 * @return a model and view for exporting the statements.
 * @throws ClientHTTPException throws when errors in parameters 
 */
private ModelAndView getExportStatementsResult(final Repository repository, final HttpServletRequest request,
		final HttpServletResponse response)
		throws ClientHTTPException {
	ProtocolUtil.logRequestParameters(request);

	ValueFactory vf = repository.getValueFactory();

	URI graph = getGraphName(request, vf);

	RDFWriterFactory rdfWriterFactory = ProtocolUtil.getAcceptableService(request, response,
			RDFWriterRegistry.getInstance());

	Map<String, Object> model = new HashMap<String, Object>();

	model.put(ExportStatementsView.CONTEXTS_KEY, new Resource[] { graph });
	model.put(ExportStatementsView.FACTORY_KEY, rdfWriterFactory);
	model.put(ExportStatementsView.USE_INFERENCING_KEY, true);
	model.put(ExportStatementsView.HEADERS_ONLY, METHOD_HEAD.equals(request.getMethod()));
	return new ModelAndView(ExportStatementsView.getInstance(), model);
}
 
Example 4
Source Project: cumulusrdf   Source File: NamespaceHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param prefix the prefix
 * @return the SimpleResponseView which will return the namesapce
 * @throws ServerHTTPException throws when there is error about the repository
 * @throws ClientHTTPException throws when there is undefined prefix
 */
private ModelAndView getExportNamespaceResult(final Repository repository, final HttpServletRequest request, final String prefix)
		throws ServerHTTPException, ClientHTTPException {
	try {
		String namespace = null;

		RepositoryConnection repositoryCon = repository.getConnection();
		synchronized (repositoryCon) {
			namespace = repositoryCon.getNamespace(prefix);
		}

		if (namespace == null) {
			throw new ClientHTTPException(SC_NOT_FOUND, "Undefined prefix: " + prefix);
		}

		Map<String, Object> model = new HashMap<String, Object>();
		model.put(SimpleResponseView.CONTENT_KEY, namespace);
		repositoryCon.close();
		return new ModelAndView(SimpleResponseView.getInstance(), model);
	} catch (RepositoryException e) {
		throw new ServerHTTPException("Repository error: " + e.getMessage(), e);
	}
}
 
Example 5
Source Project: cumulusrdf   Source File: GraphHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delete data from the graph.
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param response the HttpServletResponse object
 * @return the EmptySuccessView if successes
 * @throws ClientHTTPException throws when there are errors in getting the name of the Graph
 * @throws ServerHTTPException throws when errors happens update the data
 */
private ModelAndView getDeleteDataResult(final Repository repository,
		final HttpServletRequest request, final HttpServletResponse response)
		throws ClientHTTPException, ServerHTTPException {
	ProtocolUtil.logRequestParameters(request);

	ValueFactory vf = repository.getValueFactory();

	URI graph = getGraphName(request, vf);

	try {
		RepositoryConnection repositoryCon = repository.getConnection();
		synchronized (repositoryCon) {
			repositoryCon.clear(graph);
		}
		repositoryCon.close();
		return new ModelAndView(EmptySuccessView.getInstance());
	} catch (RepositoryException e) {
		throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
	}
}
 
Example 6
Source Project: anno4j   Source File: ListTest.java    License: 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 7
Source Project: database   Source File: SPARQLQueryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static String getManifestName(Repository manifestRep, RepositoryConnection con,
		String manifestFileURL)
	throws QueryEvaluationException, RepositoryException, MalformedQueryException
{
	// Try to extract suite name from manifest file
	TupleQuery manifestNameQuery = con.prepareTupleQuery(QueryLanguage.SERQL,
			"SELECT ManifestName FROM {ManifestURL} rdfs:label {ManifestName}");
	manifestNameQuery.setBinding("ManifestURL", manifestRep.getValueFactory().createURI(manifestFileURL));
	TupleQueryResult manifestNames = manifestNameQuery.evaluate();
	try {
		if (manifestNames.hasNext()) {
			return manifestNames.next().getValue("ManifestName").stringValue();
		}
	}
	finally {
		manifestNames.close();
	}

	// Derive name from manifest URL
	int lastSlashIdx = manifestFileURL.lastIndexOf('/');
	int secLastSlashIdx = manifestFileURL.lastIndexOf('/', lastSlashIdx - 1);
	return manifestFileURL.substring(secLastSlashIdx + 1, lastSlashIdx);
}
 
Example 8
protected static String getManifestName(Repository manifestRep, RepositoryConnection con,
		String manifestFileURL)
	throws QueryEvaluationException, RepositoryException, MalformedQueryException
{
	// Try to extract suite name from manifest file
	TupleQuery manifestNameQuery = con.prepareTupleQuery(QueryLanguage.SERQL,
			"SELECT ManifestName FROM {ManifestURL} rdfs:label {ManifestName}");
	manifestNameQuery.setBinding("ManifestURL", manifestRep.getValueFactory().createURI(manifestFileURL));
	TupleQueryResult manifestNames = manifestNameQuery.evaluate();
	try {
		if (manifestNames.hasNext()) {
			return manifestNames.next().getValue("ManifestName").stringValue();
		}
	}
	finally {
		manifestNames.close();
	}

	// Derive name from manifest URL
	int lastSlashIdx = manifestFileURL.lastIndexOf('/');
	int secLastSlashIdx = manifestFileURL.lastIndexOf('/', lastSlashIdx - 1);
	return manifestFileURL.substring(secLastSlashIdx + 1, lastSlashIdx);
}
 
Example 9
Source Project: database   Source File: BigdataSparqlTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
    protected Repository newRepository() throws RepositoryException {

        if (true) {
            final Properties props = getProperties();
            
            if (cannotInlineTests.contains(testURI)){
            	// The test can not be run using XSD inlining.
                props.setProperty(Options.INLINE_XSD_DATATYPE_LITERALS, "false");
            	props.setProperty(Options.INLINE_DATE_TIMES, "false");
            }
            
            if(unicodeStrengthIdentical.contains(testURI)) {
            	// Force identical Unicode comparisons.
            	props.setProperty(Options.COLLATOR, CollatorEnum.JDK.toString());
            	props.setProperty(Options.STRENGTH, StrengthEnum.Identical.toString());
            }
            
            final BigdataSail sail = new BigdataSail(props);
//            return new DatasetRepository(new BigdataSailRepository(sail));
            return new BigdataSailRepository(sail);
        } else {
            return new DatasetRepository(new SailRepository(new MemoryStore()));
        }
    }
 
Example 10
public Repository getRepository(final RepositoryImplConfig config)
	throws RepositoryConfigException {

	if (!TYPE.equals(config.getType())) {
		throw new RepositoryConfigException(
                   "Invalid type: " + config.getType());
	}
	
	if (!(config instanceof BigdataRepositoryConfig)) {
		throw new RepositoryConfigException(
                   "Invalid type: " + config.getClass());
	}
	
       try {
           
		final BigdataRepositoryConfig bigdataConfig = (BigdataRepositoryConfig)config;
		final Properties properties = bigdataConfig.getProperties();
   		final BigdataSail sail = new BigdataSail(properties);
   		return new BigdataSailRepository(sail);
           
       } catch (Exception ex) {
           throw new RepositoryConfigException(ex);
       }
       
}
 
Example 11
Source Project: database   Source File: LoadPdb.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
		File file = new File("tmp-1Y26.jnl");

		Properties properties = new Properties();
		properties.setProperty(BigdataSail.Options.FILE, file.getAbsolutePath());

		BigdataSail sail = new BigdataSail(properties);
		Repository repo = new BigdataSailRepository(sail);
		repo.initialize();

        if(false) {
        sail.getDatabase().getDataLoader().loadData(
                "contrib/src/problems/alex/1Y26.rdf",
                new File("contrib/src/problems/alex/1Y26.rdf").toURI()
                        .toString(), RDFFormat.RDFXML);
        sail.getDatabase().commit();
        }
        
//		loadSomeDataFromADocument(repo, "contrib/src/problems/alex/1Y26.rdf");
		// readSomeData(repo);
		executeSelectQuery(repo, "SELECT * WHERE { ?s ?p ?o }");
	}
 
Example 12
public static void main(String[] args) throws IOException, OpenRDFException {

		// load journal properties from resources
		final Properties props = loadProperties("/blazegraph.properties");

		// instantiate a sail
		final BigdataSail sail = new BigdataSail(props);
		final Repository repo = new BigdataSailRepository(sail);

		try{
			repo.initialize();
			
			/*
			 * Load data from resources 
			 * src/main/resources/data.n3
			 */
	
			loadDataFromResources(repo, "/data.n3", "");
			
			final String query = "select * {<http://blazegraph.com/blazegraph> ?p ?o}";
			final TupleQueryResult result = executeSelectQuery(repo, query, QueryLanguage.SPARQL);
			
			try {
				while(result.hasNext()){
					
					final BindingSet bs = result.next();
					log.info(bs);
					
				}
			} finally {
				result.close();
			}
		} finally {
			repo.shutDown();
		}
	}
 
Example 13
public static void loadDataFromResources(final Repository repo, final String resource, final String baseURL)
		throws OpenRDFException, IOException {

	final RepositoryConnection cxn = repo.getConnection();
	
	try {
		cxn.begin();
		try {
			final InputStream is = SampleBlazegraphSesameEmbedded.class.getResourceAsStream(resource);
			if (is == null) {
				throw new IOException("Could not locate resource: " + resource);
			}
			final Reader reader = new InputStreamReader(new BufferedInputStream(is));
			try {
				cxn.add(reader, baseURL, RDFFormat.N3);
			} finally {
				reader.close();
			}
			cxn.commit();
		} catch (OpenRDFException ex) {
			cxn.rollback();
			throw ex;
		}
	} finally {
		// close the repository connection
		cxn.close();
	}
}
 
Example 14
Source Project: ldp4j   Source File: RDFModelParser.java    License: Apache License 2.0 5 votes vote down vote up
private void shutDownQuietly(Repository repository) {
	if(repository!=null) {
		try {
			repository.shutDown();
		} catch (OpenRDFException e) {
			if(LOGGER.isWarnEnabled()) {
				LOGGER.warn("Could not shutdown internal repository",e);
			}
		}
	}
}
 
Example 15
public static Repository createRepository(){
	
	final Properties props = new Properties();
	props.put(Options.BUFFER_MODE, BufferMode.DiskRW); 
	props.put(Options.FILE, journalFile); 
	final BigdataSail sail = new BigdataSail(props);
	final Repository repo = new BigdataSailRepository(sail);
	return repo;
	
}
 
Example 16
Source Project: ldp4j   Source File: QuerySupport.java    License: Apache License 2.0 5 votes vote down vote up
public static QuerySupport newInstance(QueryTemplate template) {
	Objects.requireNonNull(template, TEMPLATE_PARAM);
	try {
		Repository tmpRepo=new SailRepository(new MemoryStore());
		tmpRepo.initialize();
		return new QuerySupport(tmpRepo,template);
	} catch (RepositoryException e) {
		throw new QueryTemplateSupportFailure("Could not initialize internal Sesame repository",e);
	}
}
 
Example 17
Source Project: blazegraph-samples   Source File: Utils.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void loadDataFromResources(Repository repo, String resource, String baseURL)
		throws OpenRDFException, IOException {

	RepositoryConnection cxn = repo.getConnection();
	
	try {
		cxn.begin();
		try {
			InputStream is = SampleBlazegraphCustomFunctionEmbedded.class.getClassLoader().getResourceAsStream(resource);
			if (is == null) {
				throw new IOException("Could not locate resource: " + resource);
			}
			Reader reader = new InputStreamReader(new BufferedInputStream(is));
			try {
				cxn.add(reader, baseURL, RDFFormat.N3);
			} finally {
				reader.close();
			}
			cxn.commit();
		} catch (OpenRDFException ex) {
			cxn.rollback();
			throw ex;
		}
	} finally {
		// close the repository connection
		cxn.close();
	}
}
 
Example 18
@Test
public void testRDFSPlusInversesInferencer() throws RepositoryException {
	// create a Sail stack
	Sail sail = new MemoryStore();
	sail = new ForwardChainingRDFSPlusInverseInferencer(sail);

	// create a Repository
	Repository repository = new SailRepository(sail);
	try {
		repository.initialize();
	} catch (RepositoryException e) {
		throw new RuntimeException(e);
	}

	URI a = new URIImpl("urn:test:a");
	URI b = new URIImpl("urn:test:b");
	URI c = new URIImpl("urn:test:c");
	URI d = new URIImpl("urn:test:d");
	URI nrlInverse = ForwardChainingRDFSPlusInverseInferencerConnection.NRL_InverseProperty;

	repository.getConnection().add(a, b, c, new Resource[0]);

	Assert.assertFalse(repository.getConnection().hasStatement(c, d, a,
			true, new Resource[0]));

	repository.getConnection().add(b, nrlInverse, d, new Resource[0]);

	Assert.assertTrue(repository.getConnection().hasStatement(c, d, a,
			true, new Resource[0]));

}
 
Example 19
Source Project: semweb4j   Source File: RepositoryModel.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public RepositoryModel(Repository repository) throws ModelRuntimeException {
	if(repository == null) {
		throw new IllegalArgumentException("Repository cannot be null");
	}
	
	this.repository = repository;
	init();
}
 
Example 20
Source Project: anno4j   Source File: ObjectRepositoryFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Wrap a previously initialised repository in an ObjectRepository.
 */
public ObjectRepository createRepository(ObjectRepositoryConfig config,
		Repository delegate) throws RepositoryConfigException,
		RepositoryException {
	ObjectRepository repo = getRepository(config, delegate.getValueFactory());
	repo.setDelegate(delegate);
	return repo;
}
 
Example 21
Source Project: cumulusrdf   Source File: StatementHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Delete data from the repository.
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param response the HttpServletResponse object
 * @return EmptySuccessView if success
 * @throws HTTPException throws when there are repository update errors
 */
private ModelAndView getDeleteDataResult(final Repository repository, final HttpServletRequest request,
		final HttpServletResponse response)
		throws HTTPException {
	ProtocolUtil.logRequestParameters(request);

	ValueFactory vf = repository.getValueFactory();

	Resource subj = ProtocolUtil.parseResourceParam(request, SUBJECT_PARAM_NAME, vf);
	URI pred = ProtocolUtil.parseURIParam(request, PREDICATE_PARAM_NAME, vf);
	Value obj = ProtocolUtil.parseValueParam(request, OBJECT_PARAM_NAME, vf);
	Resource[] contexts = ProtocolUtil.parseContextParam(request, CONTEXT_PARAM_NAME, vf);

	try {
		RepositoryConnection repositoryCon = repository.getConnection();
		synchronized (repositoryCon) {
			repositoryCon.remove(subj, pred, obj, contexts);
		}
		repositoryCon.close();
		return new ModelAndView(EmptySuccessView.getInstance());
	} catch (RepositoryException e) {
		if (e.getCause() != null && e.getCause() instanceof HTTPException) {
			// custom signal from the backend, throw as HTTPException directly
			// (see SES-1016).
			throw (HTTPException) e.getCause();
		} else {
			throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
		}
	}
}
 
Example 22
Source Project: anno4j   Source File: RepositoryTestCase.java    License: Apache License 2.0 5 votes vote down vote up
protected Repository getRepository() throws Exception, RepositoryException {
	Repository repository = createRepository();
	repository.initialize();
	RepositoryConnection con = repository.getConnection();
	try {
		con.setAutoCommit(false);
		con.clear();
		con.clearNamespaces();
		con.setNamespace("test", "urn:test:");
		con.setAutoCommit(true);
	} finally {
		con.close();
	}
	return repository;
}
 
Example 23
Source Project: anno4j   Source File: ListTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Repository getRepository() throws Exception {
	ObjectRepositoryFactory factory = new ObjectRepositoryFactory();
	ObjectRepositoryConfig config = factory.getConfig();
	config.addConcept(List.class);
	return factory.createRepository(config, super.getRepository());
}
 
Example 24
Source Project: cumulusrdf   Source File: StatementHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get all statements and export them as RDF.
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param response the HttpServletResponse object
 * @return a model and view for exporting the statements.
 * @throws ClientHTTPException throws when there errors in parsing the request
 */
private ModelAndView getExportStatementsResult(final Repository repository, final HttpServletRequest request,
		final HttpServletResponse response)
		throws ClientHTTPException {
	ProtocolUtil.logRequestParameters(request);

	ValueFactory vf = repository.getValueFactory();

	Resource subj = ProtocolUtil.parseResourceParam(request, SUBJECT_PARAM_NAME, vf);
	URI pred = ProtocolUtil.parseURIParam(request, PREDICATE_PARAM_NAME, vf);
	Value obj = ProtocolUtil.parseValueParam(request, OBJECT_PARAM_NAME, vf);
	Resource[] contexts = ProtocolUtil.parseContextParam(request, CONTEXT_PARAM_NAME, vf);
	boolean useInferencing = ProtocolUtil.parseBooleanParam(request, INCLUDE_INFERRED_PARAM_NAME, true);

	RDFWriterFactory rdfWriterFactory = ProtocolUtil.getAcceptableService(request, response,
			RDFWriterRegistry.getInstance());

	Map<String, Object> model = new HashMap<String, Object>();
	model.put(ExportStatementsView.SUBJECT_KEY, subj);
	model.put(ExportStatementsView.PREDICATE_KEY, pred);
	model.put(ExportStatementsView.OBJECT_KEY, obj);
	model.put(ExportStatementsView.CONTEXTS_KEY, contexts);
	model.put(ExportStatementsView.USE_INFERENCING_KEY, Boolean.valueOf(useInferencing));
	model.put(ExportStatementsView.FACTORY_KEY, rdfWriterFactory);
	model.put(ExportStatementsView.HEADERS_ONLY, METHOD_HEAD.equals(request.getMethod()));
	model.put(ExportStatementsView.REPO_KEY, repository);
	return new ModelAndView(ExportStatementsView.getInstance(), model);
}
 
Example 25
Source Project: cumulusrdf   Source File: NamespacesHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * clear the namespaces
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object 
 * @param response the HttpServletResponse oject
 * @return EmptySuccessView object if success
 * @throws ServerHTTPException throws when errors in repository
 * @throws RepositoryException throws when errors in closing the RepositoryConnection 
 */
private ModelAndView getClearNamespacesResult(final Repository repository, final HttpServletRequest request, final HttpServletResponse response)
		throws ServerHTTPException, RepositoryException {
	RepositoryConnection repositoryCon = repository.getConnection();
	synchronized (repositoryCon) {
		try {
			repositoryCon.clearNamespaces();
		} catch (RepositoryException e) {
			throw new ServerHTTPException("Repository error: " + e.getMessage(), e);
		}
	}
	repositoryCon.close();
	return new ModelAndView(EmptySuccessView.getInstance());
}
 
Example 26
Source Project: cumulusrdf   Source File: NamespaceHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * remove the namespace.
 * 
 *@param repository the Repository object
 * @param request the HttpServletRequest object
 * @param prefix the prefix
 * @return EmptySuccessView object if successvletRequest
 * @throws ServerHTTPException throws when there is error about the repository
 */
private ModelAndView getRemoveNamespaceResult(final Repository repository, final HttpServletRequest request, final String prefix)
		throws ServerHTTPException {
	try {
		RepositoryConnection repositoryCon = repository.getConnection();
		synchronized (repositoryCon) {
			repositoryCon.removeNamespace(prefix);
		}
		repositoryCon.close();
	} catch (RepositoryException e) {
		throw new ServerHTTPException("Repository error: " + e.getMessage(), e);
	}

	return new ModelAndView(EmptySuccessView.getInstance());
}
 
Example 27
Source Project: cumulusrdf   Source File: ContextsHandler.java    License: 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 28
Source Project: database   Source File: SampleCode.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute a "select" query.
 * 
 * @param repo
 * @param query
 * @param ql
 * @throws Exception
 */
public void executeSelectQuery(Repository repo, String query, 
    QueryLanguage ql) 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 {

        final TupleQuery tupleQuery = cxn.prepareTupleQuery(ql, query);
        tupleQuery.setIncludeInferred(true /* includeInferred */);
        TupleQueryResult result = tupleQuery.evaluate();
        // do something with the results
        while (result.hasNext()) {
            BindingSet bindingSet = result.next();
            log.info(bindingSet);
        }
        
    } finally {
        // close the repository connection
        cxn.close();
    }
    
}
 
Example 29
Source Project: database   Source File: SampleCode.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute a "construct" query.
 * 
 * @param repo
 * @param query
 * @param ql
 * @throws Exception
 */
public void executeConstructQuery(Repository repo, String query, 
    QueryLanguage ql) 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 {

        // silly construct queries, can't guarantee distinct results
        final Set<Statement> results = new LinkedHashSet<Statement>();
        final GraphQuery graphQuery = cxn.prepareGraphQuery(ql, query);
        graphQuery.setIncludeInferred(true /* includeInferred */);
        graphQuery.evaluate(new StatementCollector(results));
        // do something with the results
        for (Statement stmt : results) {
            log.info(stmt);
        }

    } finally {
        // close the repository connection
        cxn.close();
    }
    
}
 
Example 30
Source Project: cumulusrdf   Source File: RepositoryManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Closes all the repositories.
 */
public void shutDownAll() {
	synchronized (_repoMap) {
		for (String id : _repoMap.keySet()) {
			Repository repo = _repoMap.remove(id);
			if (repo != null) {
				shutdown(repo);
			}
		}
		_repoMap.clear();
	}
}