org.eclipse.rdf4j.repository.config.RepositoryConfig Java Examples

The following examples show how to use org.eclipse.rdf4j.repository.config.RepositoryConfig. 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: ConfigControllerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void getRequestRetrievesConfiguration() throws Exception {
	request.setMethod(HttpMethod.GET.name());
	request.addHeader("Accept", RDFFormat.NTRIPLES.getDefaultMIMEType());

	RepositoryConfig config = new RepositoryConfig(repositoryId, new SailRepositoryConfig(new MemoryStoreConfig()));
	when(manager.getRepositoryConfig(repositoryId)).thenReturn(config);

	ModelAndView result = controller.handleRequest(request, response);

	verify(manager).getRepositoryConfig(repositoryId);
	assertThat(result.getModel().containsKey(ConfigView.CONFIG_DATA_KEY));

	Model resultData = (Model) result.getModel().get(ConfigView.CONFIG_DATA_KEY);
	RepositoryConfig resultConfig = RepositoryConfigUtil.getRepositoryConfig(resultData, repositoryId);
	assertThat(resultConfig).isNotNull();
}
 
Example #2
Source File: SPARQLEmbeddedServer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @throws RepositoryException
 */
private void createTestRepositories()
		throws RepositoryException, RepositoryConfigException {

	RemoteRepositoryManager repoManager = RemoteRepositoryManager.getInstance(getServerUrl());
	try {
		repoManager.init();

		// create a memory store for each provided repository id
		for (String repId : repositoryIds) {
			MemoryStoreConfig memStoreConfig = new MemoryStoreConfig();
			SailRepositoryConfig sailRepConfig = new ConfigurableSailRepositoryFactory.ConfigurableSailRepositoryConfig(
					memStoreConfig);
			RepositoryConfig repConfig = new RepositoryConfig(repId, sailRepConfig);

			repoManager.addRepositoryConfig(repConfig);
		}
	} finally {
		repoManager.shutDown();
	}

}
 
Example #3
Source File: RemoteRepositoryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public RepositoryConfig getRepositoryConfig(String id) throws RepositoryException {
	Model model = getModelFactory().createEmptyModel();
	try (RDF4JProtocolSession protocolSession = getSharedHttpClientSessionManager()
			.createRDF4JProtocolSession(serverURL)) {
		protocolSession.setUsernameAndPassword(username, password);

		int serverProtocolVersion = Integer.parseInt(protocolSession.getServerProtocol());
		if (serverProtocolVersion < 10) { // explicit per-repo config endpoint was introduced in Protocol version 10
			protocolSession.setRepository(Protocol.getRepositoryLocation(serverURL, SystemRepository.ID));
			protocolSession.getStatements(null, null, null, true, new StatementCollector(model));
		} else {
			protocolSession.setRepository(Protocol.getRepositoryLocation(serverURL, id));
			protocolSession.getRepositoryConfig(new StatementCollector(model));
		}

	} catch (IOException | QueryEvaluationException | UnauthorizedException ue) {
		throw new RepositoryException(ue);
	}
	return RepositoryConfigUtil.getRepositoryConfig(model, id);
}
 
Example #4
Source File: FedXWithLocalRepositoryManagerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testWithLocalRepositoryManager_FactoryInitialization() throws Exception {

	addMemoryStore("repo1");
	addMemoryStore("repo2");

	ValueFactory vf = SimpleValueFactory.getInstance();
	addData("repo1", Lists.newArrayList(
			vf.createStatement(vf.createIRI("http://ex.org/p1"), RDF.TYPE, FOAF.PERSON)));
	addData("repo2", Lists.newArrayList(
			vf.createStatement(vf.createIRI("http://ex.org/p2"), RDF.TYPE, FOAF.PERSON)));

	FedXRepositoryConfig fedXRepoConfig = FedXRepositoryConfigBuilder.create()
			.withResolvableEndpoint(Arrays.asList("repo1", "repo2"))
			.build();
	repoManager.addRepositoryConfig(new RepositoryConfig("federation", fedXRepoConfig));

	Repository repo = repoManager.getRepository("federation");

	try (RepositoryConnection conn = repo.getConnection()) {

		List<Statement> sts = Iterations.asList(conn.getStatements(null, RDF.TYPE, FOAF.PERSON));
		Assertions.assertEquals(2, sts.size()); // two persons
	}

}
 
Example #5
Source File: TypeFilteringRepositoryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public RepositoryConfig getRepositoryConfig(String repositoryID)
		throws RepositoryConfigException, RepositoryException {
	RepositoryConfig result = delegate.getRepositoryConfig(repositoryID);

	if (result != null) {
		if (!isCorrectType(result)) {
			logger.debug(
					"Surpressing retrieval of repository {}: repository type {} did not match expected type {}",
					new Object[] { result.getID(), result.getRepositoryImplConfig().getType(), type });

			result = null;
		}
	}

	return result;
}
 
Example #6
Source File: RemoteRepositoryManagerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testAddRepositoryConfig() {
	wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/protocol"))
			.willReturn(aResponse().withStatus(200).withBody(Protocol.VERSION)));
	wireMockRule
			.stubFor(put(urlEqualTo("/rdf4j-server/repositories/test")).willReturn(aResponse().withStatus(204)));
	wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/repositories"))
			.willReturn(aResponse().withHeader("Content-type", TupleQueryResultFormat.SPARQL.getDefaultMIMEType())
					.withBodyFile("repository-list-response.srx")
					.withStatus(200)));

	RepositoryConfig config = new RepositoryConfig("test");

	subject.addRepositoryConfig(config);

	wireMockRule.verify(
			putRequestedFor(urlEqualTo("/rdf4j-server/repositories/test")).withRequestBody(matching("^BRDF.*"))
					.withHeader("Content-Type", equalTo("application/x-binary-rdf")));
}
 
Example #7
Source File: RemoteRepositoryManagerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testAddRepositoryConfigExisting() throws Exception {
	wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/protocol"))
			.willReturn(aResponse().withStatus(200).withBody(Protocol.VERSION)));
	wireMockRule
			.stubFor(post(urlEqualTo("/rdf4j-server/repositories/mem-rdf/config"))
					.willReturn(aResponse().withStatus(204)));
	wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/repositories"))
			.willReturn(aResponse().withHeader("Content-type", TupleQueryResultFormat.SPARQL.getDefaultMIMEType())
					.withBodyFile("repository-list-response.srx")
					.withStatus(200)));

	RepositoryConfig config = new RepositoryConfig("mem-rdf"); // this repo already exists

	subject.addRepositoryConfig(config);

	wireMockRule.verify(
			postRequestedFor(urlEqualTo("/rdf4j-server/repositories/mem-rdf/config"))
					.withRequestBody(matching("^BRDF.*"))
					.withHeader("Content-Type", equalTo("application/x-binary-rdf")));
}
 
Example #8
Source File: RemoteRepositoryManagerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testAddRepositoryConfigLegacy() {
	wireMockRule.stubFor(
			get(urlEqualTo("/rdf4j-server/protocol")).willReturn(aResponse().withStatus(200).withBody("8")));
	wireMockRule.stubFor(post(urlPathEqualTo("/rdf4j-server/repositories/SYSTEM/statements"))
			.willReturn(aResponse().withStatus(204)));
	wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/repositories"))
			.willReturn(aResponse().withHeader("Content-type", TupleQueryResultFormat.SPARQL.getDefaultMIMEType())
					.withBodyFile("repository-list-response.srx")
					.withStatus(200)));

	RepositoryConfig config = new RepositoryConfig("test");

	subject.addRepositoryConfig(config);

	wireMockRule.verify(postRequestedFor(urlPathEqualTo("/rdf4j-server/repositories/SYSTEM/statements"))
			.withRequestBody(matching("^BRDF.*"))
			.withHeader("Content-Type", equalTo("application/x-binary-rdf")));
}
 
Example #9
Source File: RepositoryManagerFederator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Adds a new repository to the {@link org.eclipse.rdf4j.repository.manager.RepositoryManager}, which is a
 * federation of the given repository id's, which must also refer to repositories already managed by the
 * {@link org.eclipse.rdf4j.repository.manager.RepositoryManager}.
 *
 * @param fedID       the desired identifier for the new federation repository
 * @param description the desired description for the new federation repository
 * @param members     the identifiers of the repositories to federate, which must already exist and be managed by
 *                    the {@link org.eclipse.rdf4j.repository.manager.RepositoryManager}
 * @param readonly    whether the federation is read-only
 * @param distinct    whether the federation enforces distinct results from its members
 * @throws MalformedURLException if the {@link org.eclipse.rdf4j.repository.manager.RepositoryManager} has a
 *                               malformed location
 * @throws RDF4JException        if a problem otherwise occurs while creating the federation
 */
public void addFed(String fedID, String description, Collection<String> members, boolean readonly, boolean distinct)
		throws MalformedURLException, RDF4JException {
	if (members.contains(fedID)) {
		throw new RepositoryConfigException("A federation member may not have the same ID as the federation.");
	}
	Model graph = new LinkedHashModel();
	BNode fedRepoNode = valueFactory.createBNode();
	LOGGER.debug("Federation repository root node: {}", fedRepoNode);
	addToGraph(graph, fedRepoNode, RDF.TYPE, RepositoryConfigSchema.REPOSITORY);
	addToGraph(graph, fedRepoNode, RepositoryConfigSchema.REPOSITORYID, valueFactory.createLiteral(fedID));
	addToGraph(graph, fedRepoNode, RDFS.LABEL, valueFactory.createLiteral(description));
	addImplementation(members, graph, fedRepoNode, readonly, distinct);
	RepositoryConfig fedConfig = RepositoryConfig.create(graph, fedRepoNode);
	fedConfig.validate();
	manager.addRepositoryConfig(fedConfig);
}
 
Example #10
Source File: AbstractCommandTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/***
 * Add a new repository to the manager.
 *
 * @param configStream input stream of the repository configuration
 * @return ID of the repository as string
 * @throws IOException
 * @throws RDF4JException
 */
protected String addRepository(InputStream configStream) throws IOException, RDF4JException {
	RDFParser rdfParser = Rio.createParser(RDFFormat.TURTLE, SimpleValueFactory.getInstance());

	Model graph = new LinkedHashModel();
	rdfParser.setRDFHandler(new StatementCollector(graph));
	rdfParser.parse(
			new StringReader(IOUtil.readString(new InputStreamReader(configStream, StandardCharsets.UTF_8))),
			RepositoryConfigSchema.NAMESPACE);
	configStream.close();

	Resource repositoryNode = Models.subject(graph.filter(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY))
			.orElseThrow(() -> new RepositoryConfigException("could not find subject resource"));

	RepositoryConfig repoConfig = RepositoryConfig.create(graph, repositoryNode);
	repoConfig.validate();
	manager.addRepositoryConfig(repoConfig);

	String repId = Models.objectLiteral(graph.filter(repositoryNode, RepositoryConfigSchema.REPOSITORYID, null))
			.orElseThrow(() -> new RepositoryConfigException("missing repository id"))
			.stringValue();

	return repId;
}
 
Example #11
Source File: Create.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get the names of the built-in repository templates, located in the JAR containing RepositoryConfig.
 *
 * @return concatenated list of names
 */
private String getBuiltinTemplates() {
	// assume the templates are all located in the same jar "directory" as the RepositoryConfig class
	Class cl = RepositoryConfig.class;

	try {
		URI dir = cl.getResource(cl.getSimpleName() + ".class").toURI();
		if (dir.getScheme().equals("jar")) {
			try (FileSystem fs = FileSystems.newFileSystem(dir, Collections.EMPTY_MAP, null)) {
				// turn package structure into directory structure
				String pkg = cl.getPackage().getName().replaceAll("\\.", "/");
				return getOrderedTemplates(fs.getPath(pkg));
			}
		}
	} catch (NullPointerException | URISyntaxException | IOException e) {
		writeError("Could not get built-in config templates from JAR", e);
	}
	return "";
}
 
Example #12
Source File: ConfigControllerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void postRequestModifiesConfiguration() throws Exception {
	request.setMethod(HttpMethod.POST.name());
	request.setContentType(RDFFormat.NTRIPLES.getDefaultMIMEType());
	request.setContent(
			("_:node1 <" + RepositoryConfigSchema.REPOSITORYID + "> \"" + repositoryId + "\" .")
					.getBytes(Charsets.UTF_8));

	when(manager.hasRepositoryConfig(repositoryId)).thenReturn(true);

	ArgumentCaptor<RepositoryConfig> config = ArgumentCaptor.forClass(RepositoryConfig.class);

	controller.handleRequest(request, new MockHttpServletResponse());

	verify(manager).addRepositoryConfig(config.capture());
	assertThat(config.getValue().getID()).isEqualTo(repositoryId);
}
 
Example #13
Source File: RepositoryControllerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void putOnNewRepoSucceeds() throws Exception {
	request.setMethod(HttpMethod.PUT.name());
	request.setContentType(RDFFormat.NTRIPLES.getDefaultMIMEType());
	request.setContent(
			("_:node1 <" + RepositoryConfigSchema.REPOSITORYID + "> \"" + repositoryId + "\" .")
					.getBytes(Charsets.UTF_8));

	when(manager.hasRepositoryConfig(repositoryId)).thenReturn(false);

	ArgumentCaptor<RepositoryConfig> config = ArgumentCaptor.forClass(RepositoryConfig.class);

	controller.handleRequest(request, response);

	verify(manager).addRepositoryConfig(config.capture());
	assertThat(config.getValue().getID()).isEqualTo(repositoryId);
}
 
Example #14
Source File: TestProxyRepositoryFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public final void testGetRepository() throws RDF4JException, IOException {
	Model graph = Rio.parse(this.getClass().getResourceAsStream("/proxy.ttl"), RepositoryConfigSchema.NAMESPACE,
			RDFFormat.TURTLE);
	RepositoryConfig config = RepositoryConfig.create(graph,
			Models.subject(graph.getStatements(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY))
					.orElseThrow(() -> new RepositoryConfigException("missing Repository instance in config")));
	config.validate();
	assertThat(config.getID()).isEqualTo("proxy");
	assertThat(config.getTitle()).isEqualTo("Test Proxy for 'memory'");
	RepositoryImplConfig implConfig = config.getRepositoryImplConfig();
	assertThat(implConfig.getType()).isEqualTo("openrdf:ProxyRepository");
	assertThat(implConfig).isInstanceOf(ProxyRepositoryConfig.class);
	assertThat(((ProxyRepositoryConfig) implConfig).getProxiedRepositoryID()).isEqualTo("memory");

	// Factory just needs a resolver instance to proceed with construction.
	// It doesn't actually invoke the resolver until the repository is
	// accessed. Normally LocalRepositoryManager is the caller of
	// getRepository(), and will have called this setter itself.
	ProxyRepository repository = (ProxyRepository) factory.getRepository(implConfig);
	repository.setRepositoryResolver(mock(RepositoryResolver.class));
	assertThat(repository).isInstanceOf(ProxyRepository.class);
}
 
Example #15
Source File: ConfigController.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private ModelAndView handleQuery(HttpServletRequest request, HttpServletResponse response)
		throws ClientHTTPException {

	RDFWriterFactory rdfWriterFactory = ProtocolUtil.getAcceptableService(request, response,
			RDFWriterRegistry.getInstance());
	String repId = RepositoryInterceptor.getRepositoryID(request);
	RepositoryConfig repositoryConfig = repositoryManager.getRepositoryConfig(repId);

	Model configData = modelFactory.createEmptyModel();
	String baseURI = request.getRequestURL().toString();
	Resource ctx = SimpleValueFactory.getInstance().createIRI(baseURI + "#" + repositoryConfig.getID());

	repositoryConfig.export(configData, ctx);
	Map<String, Object> model = new HashMap<>();
	model.put(ConfigView.FORMAT_KEY, rdfWriterFactory.getRDFFormat());
	model.put(ConfigView.CONFIG_DATA_KEY, configData);
	model.put(ConfigView.HEADERS_ONLY, METHOD_HEAD.equals(request.getMethod()));
	return new ModelAndView(ConfigView.getInstance(), model);
}
 
Example #16
Source File: LocalRepositoryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private synchronized void upgrade() {
	File repositoriesDir = resolvePath(REPOSITORIES_DIR);
	String[] dirs = repositoriesDir.list((File repositories, String name) -> {
		File dataDir = new File(repositories, name);
		return dataDir.isDirectory() && new File(dataDir, CFG_FILE).exists();
	});
	if (dirs != null && dirs.length > 0) {
		return; // already upgraded
	}
	SystemRepository systemRepository = getSystemRepository();
	if (systemRepository == null) {
		return; // no legacy SYSTEM
	}
	Set<String> ids = RepositoryConfigUtil.getRepositoryIDs(systemRepository);
	List<RepositoryConfig> configs = new ArrayList<>();
	for (String id : ids) {
		configs.add(getRepositoryConfig(id));
	}
	for (RepositoryConfig config : configs) {
		addRepositoryConfig(config);
	}
}
 
Example #17
Source File: LocalRepositoryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public RepositoryInfo getRepositoryInfo(String id) {
	RepositoryConfig config = getRepositoryConfig(id);
	if (config == null) {
		return null;
	}
	RepositoryInfo repInfo = new RepositoryInfo();
	repInfo.setId(config.getID());
	repInfo.setDescription(config.getTitle());
	try {
		repInfo.setLocation(getRepositoryDir(config.getID()).toURI().toURL());
	} catch (MalformedURLException mue) {
		throw new RepositoryException("Location of repository does not resolve to a valid URL", mue);
	}
	repInfo.setReadable(true);
	repInfo.setWritable(true);
	return repInfo;
}
 
Example #18
Source File: LocalRepositoryManagerIntegrationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@Deprecated
public void testRemoveFromSystemRepository() {
	RepositoryConfig config = subject.getRepositoryConfig(TEST_REPO);
	subject.addRepositoryConfig(new RepositoryConfig(SystemRepository.ID, new SystemRepositoryConfig()));
	subject.shutDown();
	subject = new LocalRepositoryManager(datadir);
	subject.initialize();
	try (RepositoryConnection con = subject.getSystemRepository().getConnection()) {
		Model model = new TreeModel();
		config.setID("changed");
		config.export(model, con.getValueFactory().createBNode());
		con.begin();
		con.add(model, con.getValueFactory().createBNode());
		con.commit();
	}
	assertTrue(subject.hasRepositoryConfig("changed"));
	try (RepositoryConnection con = subject.getSystemRepository().getConnection()) {
		con.begin();
		con.clear(RepositoryConfigUtil.getContext(con, config.getID()));
		con.commit();
	}
	assertFalse(subject.hasRepositoryConfig(config.getID()));
}
 
Example #19
Source File: LocalRepositoryManagerIntegrationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@Deprecated
public void testModifySystemRepository() {
	RepositoryConfig config = subject.getRepositoryConfig(TEST_REPO);
	subject.addRepositoryConfig(new RepositoryConfig(SystemRepository.ID, new SystemRepositoryConfig()));
	subject.shutDown();
	subject = new LocalRepositoryManager(datadir);
	subject.initialize();
	try (RepositoryConnection con = subject.getSystemRepository().getConnection()) {
		Model model = new TreeModel();
		config.setTitle("Changed");
		config.export(model, con.getValueFactory().createBNode());
		Resource ctx = RepositoryConfigUtil.getContext(con, config.getID());
		con.begin();
		con.clear(ctx);
		con.add(model, ctx == null ? con.getValueFactory().createBNode() : ctx);
		con.commit();
	}
	assertEquals("Changed", subject.getRepositoryConfig(TEST_REPO).getTitle());
}
 
Example #20
Source File: LocalRepositoryManagerIntegrationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@Deprecated
public void testAddToSystemRepository() {
	RepositoryConfig config = subject.getRepositoryConfig(TEST_REPO);
	subject.addRepositoryConfig(new RepositoryConfig(SystemRepository.ID, new SystemRepositoryConfig()));
	subject.shutDown();
	subject = new LocalRepositoryManager(datadir);
	subject.initialize();
	try (RepositoryConnection con = subject.getSystemRepository().getConnection()) {
		Model model = new TreeModel();
		config.setID("changed");
		config.export(model, con.getValueFactory().createBNode());
		con.begin();
		con.add(model, con.getValueFactory().createBNode());
		con.commit();
	}
	assertTrue(subject.hasRepositoryConfig("changed"));
}
 
Example #21
Source File: LocalRepositoryManagerIntegrationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @throws java.lang.Exception
 */
@Before
@Override
public void setUp() throws Exception {
	datadir = tempDir.newFolder("local-repositorysubject-test");
	subject = new LocalRepositoryManager(datadir);
	subject.init();

	// Create configurations for the SAIL stack, and the repository
	// implementation.
	subject.addRepositoryConfig(
			new RepositoryConfig(TEST_REPO, new SailRepositoryConfig(new MemoryStoreConfig(true))));

	// Create configuration for proxy repository to previous repository.
	subject.addRepositoryConfig(new RepositoryConfig(PROXY_ID, new ProxyRepositoryConfig(TEST_REPO)));
}
 
Example #22
Source File: SystemRepository.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void initialize() throws RepositoryException {
	super.initialize();

	try (RepositoryConnection con = getConnection()) {
		if (con.isEmpty()) {
			logger.debug("Initializing empty {} repository", ID);

			con.begin();
			con.setNamespace("rdf", RDF.NAMESPACE);
			con.setNamespace("sys", RepositoryConfigSchema.NAMESPACE);
			con.commit();

			RepositoryConfig repConfig = new RepositoryConfig(ID, TITLE, new SystemRepositoryConfig());
			RepositoryConfigUtil.updateRepositoryConfigs(con, repConfig);

		}
	} catch (RepositoryConfigException e) {
		throw new RepositoryException(e.getMessage(), e);
	}
}
 
Example #23
Source File: KnowledgeBaseServiceImpl.java    From inception with Apache License 2.0 6 votes vote down vote up
private void reconfigureLocalKnowledgeBase(KnowledgeBase aKB)
{
    /*
    log.info("Forcing update of configuration for {}", aKB);
    Model model = new TreeModel();
    ValueFactory vf = SimpleValueFactory.getInstance();
    IRI root = vf
            .createIRI("http://inception-project.github.io/kbexport#" + aKB.getRepositoryId());
    repoManager.getRepositoryConfig(aKB.getRepositoryId()).export(model, root);
    StringWriter out = new StringWriter();
    Rio.write(model, out, RDFFormat.TURTLE);
    log.info("Current configuration: {}", out.toString());
    */
    
    RepositoryImplConfig config = getNativeConfig();
    setIndexDir(aKB, config);
    repoManager.addRepositoryConfig(new RepositoryConfig(aKB.getRepositoryId(), config));
}
 
Example #24
Source File: KnowledgeBaseServiceImpl.java    From inception with Apache License 2.0 6 votes vote down vote up
@Transactional
@Override
public void registerKnowledgeBase(KnowledgeBase aKB, RepositoryImplConfig aCfg)
    throws RepositoryException, RepositoryConfigException
{
    // Obtain unique repository id
    String baseName = "pid-" + Long.toString(aKB.getProject().getId()) + "-kbid-";
    String repositoryId = repoManager.getNewRepositoryID(baseName);
    aKB.setRepositoryId(repositoryId);
    
    // We want to have a separate Lucene index for every local repo, so we need to hack the
    // index dir in here because this is the place where we finally know the repo ID.
    setIndexDir(aKB, aCfg);

    repoManager.addRepositoryConfig(new RepositoryConfig(repositoryId, aCfg));
    entityManager.persist(aKB);
}
 
Example #25
Source File: LocalRepositoryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public synchronized RepositoryConfig getRepositoryConfig(String id) {
	File dataDir = getRepositoryDir(id);
	if (new File(dataDir, CFG_FILE).exists()) {
		File configFile = new File(dataDir, CFG_FILE);
		try (InputStream input = new FileInputStream(configFile)) {
			Model model = Rio.parse(input, configFile.toURI().toString(), CONFIG_FORMAT);
			Set<String> repositoryIDs = RepositoryConfigUtil.getRepositoryIDs(model);
			if (repositoryIDs.isEmpty()) {
				throw new RepositoryConfigException("No repository ID in configuration: " + configFile);
			} else if (repositoryIDs.size() != 1) {
				throw new RepositoryConfigException("Multiple repository IDs in configuration: " + configFile);
			}
			String repositoryID = repositoryIDs.iterator().next();
			if (!id.equals(repositoryID)
					&& !getRepositoryDir(repositoryID).getCanonicalFile().equals(dataDir.getCanonicalFile())) {
				throw new RepositoryConfigException("Wrong repository ID in configuration: " + configFile);
			}
			return RepositoryConfigUtil.getRepositoryConfig(model, repositoryID);
		} catch (IOException e) {
			throw new RepositoryConfigException(e);
		}
	} else if (id.equals(SystemRepository.ID)) {
		return new RepositoryConfig(id, new SystemRepositoryConfig());
	} else {
		return super.getRepositoryConfig(id);
	}
}
 
Example #26
Source File: RepositoryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public RepositoryConfig getRepositoryConfig(String repositoryID)
		throws RepositoryConfigException, RepositoryException {
	Repository systemRepository = getSystemRepository();
	if (systemRepository == null) {
		return null;
	} else {
		return RepositoryConfigUtil.getRepositoryConfig(systemRepository, repositoryID);
	}
}
 
Example #27
Source File: RepositoryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Checks on whether the given repository is referred to by a
 * {@link org.eclipse.rdf4j.repository.sail.ProxyRepository} configuration.
 *
 * @param repositoryID id to check
 * @return true if there is no existing proxy reference to the given id, false otherwise
 * @throws RepositoryException
 */
public boolean isSafeToRemove(String repositoryID) throws RepositoryException {
	SimpleValueFactory vf = SimpleValueFactory.getInstance();
	for (String id : getRepositoryIDs()) {
		RepositoryConfig config = getRepositoryConfig(id);
		Model model = new LinkedHashModel();
		config.export(model, vf.createBNode());
		if (model.contains(null, PROXIED_ID, vf.createLiteral(repositoryID))) {
			return false;
		}
	}
	return true;
}
 
Example #28
Source File: KnowledgeBaseServiceImpl.java    From inception with Apache License 2.0 5 votes vote down vote up
@Transactional
@Override
public void updateKnowledgeBase(KnowledgeBase kb, RepositoryImplConfig cfg)
    throws RepositoryException, RepositoryConfigException
{
    assertRegistration(kb);
    repoManager.addRepositoryConfig(new RepositoryConfig(kb.getRepositoryId(), cfg));
    entityManager.merge(kb);
}
 
Example #29
Source File: RemoteRepositoryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void addRepositoryConfig(RepositoryConfig config) throws RepositoryException, RepositoryConfigException {
	try (RDF4JProtocolSession protocolSession = getSharedHttpClientSessionManager()
			.createRDF4JProtocolSession(serverURL)) {
		protocolSession.setUsernameAndPassword(username, password);

		int serverProtocolVersion = Integer.parseInt(protocolSession.getServerProtocol());
		if (serverProtocolVersion < 9) { // explicit PUT create operation was introduced in Protocol version 9
			String baseURI = Protocol.getRepositoryLocation(serverURL, config.getID());
			Resource ctx = SimpleValueFactory.getInstance().createIRI(baseURI + "#" + config.getID());
			protocolSession.setRepository(Protocol.getRepositoryLocation(serverURL, SystemRepository.ID));
			Model model = getModelFactory().createEmptyModel();
			config.export(model, ctx);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			Rio.write(model, baos, protocolSession.getPreferredRDFFormat());
			removeRepository(config.getID());
			try (InputStream contents = new ByteArrayInputStream(baos.toByteArray())) {
				protocolSession.upload(contents, baseURI, protocolSession.getPreferredRDFFormat(), false, true,
						ctx);
			}
		} else {
			if (hasRepositoryConfig(config.getID())) {
				protocolSession.updateRepository(config);
			} else {
				protocolSession.createRepository(config);
			}
		}
	} catch (IOException | QueryEvaluationException | UnauthorizedException | NumberFormatException e) {
		throw new RepositoryException(e);
	}
}
 
Example #30
Source File: TypeFilteringRepositoryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void addRepositoryConfig(RepositoryConfig config) throws RepositoryException, RepositoryConfigException {
	if (isCorrectType(config)) {
		delegate.addRepositoryConfig(config);
	} else {
		throw new UnsupportedOperationException(
				"Only repositories of type " + type + " can be added to this manager.");
	}
}