org.eclipse.rdf4j.model.Namespace Java Examples

The following examples show how to use org.eclipse.rdf4j.model.Namespace. 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: NamespacesTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#asMap(java.util.Set)}.
 */
@Test
public final void testAsMapMultiple() {
	Set<Namespace> input = new HashSet<>();
	input.add(new SimpleNamespace(RDF.PREFIX, RDF.NAMESPACE));
	input.add(new SimpleNamespace(RDFS.PREFIX, RDFS.NAMESPACE));
	input.add(new SimpleNamespace(DC.PREFIX, DC.NAMESPACE));
	input.add(new SimpleNamespace(SKOS.PREFIX, SKOS.NAMESPACE));
	input.add(new SimpleNamespace(SESAME.PREFIX, SESAME.NAMESPACE));

	Map<String, String> map = Namespaces.asMap(input);

	assertFalse(map.isEmpty());
	assertEquals(5, map.size());

	assertTrue(map.containsKey(RDF.PREFIX));
	assertEquals(RDF.NAMESPACE, map.get(RDF.PREFIX));
	assertTrue(map.containsKey(RDFS.PREFIX));
	assertEquals(RDFS.NAMESPACE, map.get(RDFS.PREFIX));
	assertTrue(map.containsKey(DC.PREFIX));
	assertEquals(DC.NAMESPACE, map.get(DC.PREFIX));
	assertTrue(map.containsKey(SKOS.PREFIX));
	assertEquals(SKOS.NAMESPACE, map.get(SKOS.PREFIX));
	assertTrue(map.containsKey(SESAME.PREFIX));
	assertEquals(SESAME.NAMESPACE, map.get(SESAME.PREFIX));
}
 
Example #2
Source File: NamespacesTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}.
 */
@Test
public final void testWrapContainsValue() throws Exception {
	Set<Namespace> testSet = new LinkedHashSet<>();
	Map<String, String> testMap = Namespaces.wrap(testSet);
	// Check no exceptions when calling containsKey on empty backing set
	assertFalse(testMap.containsValue(testName1));

	testSet.add(new SimpleNamespace(testPrefix1, testName1));

	assertTrue(testMap.containsValue(testName1));

	testSet.clear();

	assertFalse(testMap.containsValue(testName1));
}
 
Example #3
Source File: NamespacesTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}.
 */
@Test
public final void testWrapValues() throws Exception {
	Set<Namespace> testSet = new LinkedHashSet<>();
	Map<String, String> testMap = Namespaces.wrap(testSet);

	Collection<String> values1 = testMap.values();
	assertNotNull(values1);
	assertTrue(values1.isEmpty());

	testSet.add(new SimpleNamespace(testPrefix1, testName1));

	Collection<String> values2 = testMap.values();
	assertNotNull(values2);
	assertFalse(values2.isEmpty());
	assertEquals(1, values2.size());
	String nextValue = values2.iterator().next();
	assertEquals(testName1, nextValue);

	testSet.clear();

	Collection<String> values3 = testMap.values();
	assertNotNull(values3);
	assertTrue(values3.isEmpty());
}
 
Example #4
Source File: TupleServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void service(WorkbenchRequest req, HttpServletResponse resp, String xslPath) throws Exception {
	TupleResultBuilder builder = getTupleResultBuilder(req, resp, resp.getOutputStream());
	RepositoryConnection con = repository.getConnection();
	con.setParserConfig(NON_VERIFYING_PARSER_CONFIG);
	try {
		for (Namespace ns : Iterations.asList(con.getNamespaces())) {
			builder.prefix(ns.getPrefix(), ns.getName());
		}
		if (xsl != null) {
			builder.transform(xslPath, xsl);
		}
		builder.start(variables);
		builder.link(Arrays.asList("info"));
		this.service(req, resp, builder, con);
		builder.end();
	} finally {
		con.close();
	}
}
 
Example #5
Source File: Show.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Show namespaces
 */
private void showNamespaces() {
	Repository repository = state.getRepository();
	if (repository == null) {
		writeUnopenedError();
		return;
	}

	try (RepositoryConnection con = repository.getConnection()) {
		try (CloseableIteration<? extends Namespace, RepositoryException> namespaces = con.getNamespaces()) {
			if (namespaces.hasNext()) {
				writeln(OUTPUT_SEPARATOR);
				while (namespaces.hasNext()) {
					final Namespace namespace = namespaces.next();
					writeln("|" + namespace.getPrefix() + "  " + namespace.getName());
				}
				writeln(OUTPUT_SEPARATOR);
			} else {
				writeln("No namespaces found");
			}
		}
	} catch (RepositoryException e) {
		writeError("Failed to show namespaces", e);
	}
}
 
Example #6
Source File: NamespacesTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}.
 */
@Test
public final void testWrapEntrySet() throws Exception {
	Set<Namespace> testSet = new LinkedHashSet<>();
	Map<String, String> testMap = Namespaces.wrap(testSet);

	Set<Entry<String, String>> entrySet1 = testMap.entrySet();
	assertNotNull(entrySet1);
	assertTrue(entrySet1.isEmpty());

	testSet.add(new SimpleNamespace(testPrefix1, testName1));

	Set<Entry<String, String>> entrySet2 = testMap.entrySet();
	assertNotNull(entrySet2);
	assertFalse(entrySet2.isEmpty());
	assertEquals(1, entrySet2.size());
	Entry<String, String> nextEntry = entrySet2.iterator().next();
	assertEquals(testPrefix1, nextEntry.getKey());
	assertEquals(testName1, nextEntry.getValue());

	testSet.clear();

	Set<Entry<String, String>> entrySet3 = testMap.entrySet();
	assertNotNull(entrySet3);
	assertTrue(entrySet3.isEmpty());
}
 
Example #7
Source File: HTTPRepositoryConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public RepositoryResult<Namespace> getNamespaces() throws RepositoryException {
	try {
		List<Namespace> namespaceList = new ArrayList<>();

		try (TupleQueryResult namespaces = client.getNamespaces()) {
			while (namespaces.hasNext()) {
				BindingSet bindingSet = namespaces.next();
				Value prefix = bindingSet.getValue("prefix");
				Value namespace = bindingSet.getValue("namespace");

				if (prefix instanceof Literal && namespace instanceof Literal) {
					String prefixStr = ((Literal) prefix).getLabel();
					String namespaceStr = ((Literal) namespace).getLabel();
					namespaceList.add(new SimpleNamespace(prefixStr, namespaceStr));
				}
			}
		}

		return createRepositoryResult(namespaceList);
	} catch (QueryEvaluationException | IOException e) {
		throw new RepositoryException(e);
	}
}
 
Example #8
Source File: NotifyingRepositoryConnectionWrapper.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void clearNamespaces() throws RepositoryException {
	if (activated && reportDeltas()) {

		List<String> prefix;
		try (Stream<Namespace> stream = getDelegate().getNamespaces().stream()) {
			prefix = stream.map(Namespace::getPrefix).collect(Collectors.toList());
		}

		getDelegate().clearNamespaces();
		for (String p : prefix) {
			removeNamespace(p);
		}
	} else if (activated) {
		getDelegate().clearNamespaces();
		for (RepositoryConnectionListener listener : listeners) {
			listener.clearNamespaces(getDelegate());
		}
	} else {
		getDelegate().clearNamespaces();
	}
}
 
Example #9
Source File: RDFStoreTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testGetNamespaces() throws Exception {
	con.begin();
	con.setNamespace("rdf", RDF.NAMESPACE);
	con.commit();

	CloseableIteration<? extends Namespace, SailException> namespaces = con.getNamespaces();
	try {
		Assert.assertTrue(namespaces.hasNext());
		Namespace rdf = namespaces.next();
		Assert.assertEquals("rdf", rdf.getPrefix());
		Assert.assertEquals(RDF.NAMESPACE, rdf.getName());
		Assert.assertTrue(!namespaces.hasNext());
	} finally {
		namespaces.close();
	}
}
 
Example #10
Source File: TripleStoreRDF4J.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public List<PrefixNamespace> getNamespaces() {
    List<PrefixNamespace> namespaces = new ArrayList<>();
    try (RepositoryConnection conn = repo.getConnection()) {
        RepositoryResult<Namespace> ns = conn.getNamespaces();
        while (ns.hasNext()) {
            Namespace namespace = ns.next();
            namespaces.add(new PrefixNamespace(namespace.getPrefix(), namespace.getName()));
        }
    }
    return namespaces;
}
 
Example #11
Source File: CustomTurtleParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testParsingNamespacesWithOverride() throws Exception {
	ParserConfig aConfig = new ParserConfig();

	aConfig.set(BasicParserSettings.NAMESPACES,
			Collections.<Namespace>singleton(new NamespaceImpl("foo", SKOS.NAMESPACE)));

	Model model = Rio.parse(new StringReader("@prefix skos : <urn:not_skos:> ." + "<urn:a> skos:broader <urn:b>."),
			"", RDFFormat.TURTLE, aConfig, vf, new ParseErrorLogger());

	assertEquals(1, model.size());
	assertTrue(model.contains(vf.createIRI("urn:a"), vf.createIRI("urn:not_skos:broader"), vf.createIRI("urn:b")));
}
 
Example #12
Source File: FedXConnection.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected CloseableIteration<? extends Namespace, SailException> getNamespacesInternal() throws SailException {
    log.warn("Operation is not yet supported. (getNamespacesInternal)");
    return new AbstractCloseableIteration<Namespace, SailException>() {
           @Override
           public boolean hasNext() throws SailException { return false; }

           @Override
           public Namespace next() throws SailException { return null; }

           @Override
           public void remove() throws SailException {}
    };
	//throw new UnsupportedOperationException("Operation is not yet supported.");		
}
 
Example #13
Source File: SimpleNamespace.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public int compareTo(Namespace o) {
	if (getPrefix().equals(o.getPrefix())) {
		if (getName().equals(o.getName())) {
			return 0;
		} else {
			return getName().compareTo(o.getName());
		}
	} else {
		return getPrefix().compareTo(o.getPrefix());
	}
}
 
Example #14
Source File: Rio.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Writes the given statements to the given {@link RDFHandler}.
 * <p>
 * If the collection is a {@link Model}, its namespaces will also be written.
 *
 * @param model  A collection of statements, such as a {@link Model}, to be written.
 * @param writer
 * @throws RDFHandlerException Thrown if there is an error writing the statements.
 */
public static void write(Iterable<Statement> model, RDFHandler writer) throws RDFHandlerException {
	writer.startRDF();

	if (model instanceof NamespaceAware) {
		for (Namespace nextNamespace : ((NamespaceAware) model).getNamespaces()) {
			writer.handleNamespace(nextNamespace.getPrefix(), nextNamespace.getName());
		}
	}

	for (final Statement st : model) {
		writer.handleStatement(st);
	}
	writer.endRDF();
}
 
Example #15
Source File: NamespacesController.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private ModelAndView getExportNamespacesResult(HttpServletRequest request, HttpServletResponse response)
		throws ClientHTTPException, ServerHTTPException {
	final boolean headersOnly = METHOD_HEAD.equals(request.getMethod());

	Map<String, Object> model = new HashMap<>();
	if (!headersOnly) {
		List<String> columnNames = Arrays.asList("prefix", "namespace");
		List<BindingSet> namespaces = new ArrayList<>();

		try (RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request)) {
			final ValueFactory vf = repositoryCon.getValueFactory();
			try {
				try (CloseableIteration<? extends Namespace, RepositoryException> iter = repositoryCon
						.getNamespaces()) {
					while (iter.hasNext()) {
						Namespace ns = iter.next();

						Literal prefix = vf.createLiteral(ns.getPrefix());
						Literal namespace = vf.createLiteral(ns.getName());

						BindingSet bindingSet = new ListBindingSet(columnNames, prefix, namespace);
						namespaces.add(bindingSet);
					}
				}
			} catch (RepositoryException e) {
				throw new ServerHTTPException("Repository error: " + e.getMessage(), e);
			}
		}
		model.put(QueryResultView.QUERY_RESULT_KEY, new IteratingTupleQueryResult(columnNames, namespaces));
	}

	TupleQueryResultWriterFactory factory = ProtocolUtil.getAcceptableService(request, response,
			TupleQueryResultWriterRegistry.getInstance());

	model.put(QueryResultView.FILENAME_HINT_KEY, "namespaces");
	model.put(QueryResultView.HEADERS_ONLY, headersOnly);
	model.put(QueryResultView.FACTORY_KEY, factory);

	return new ModelAndView(TupleQueryResultView.getInstance(), model);
}
 
Example #16
Source File: SailRepositoryConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public RepositoryResult<Namespace> getNamespaces() throws RepositoryException {
	try {
		return createRepositoryResult(sailConnection.getNamespaces());
	} catch (SailException e) {
		throw new RepositoryException("Unable to get namespaces from Sail", e);
	}
}
 
Example #17
Source File: CustomTurtleParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testParsingNamespacesWithOption() throws Exception {
	ParserConfig aConfig = new ParserConfig();

	aConfig.set(BasicParserSettings.NAMESPACES,
			Collections.<Namespace>singleton(new NamespaceImpl("foo", SKOS.NAMESPACE)));

	Model model = Rio.parse(new StringReader("<urn:a> foo:broader <urn:b>."), "", RDFFormat.TURTLE, aConfig, vf,
			new ParseErrorLogger());

	assertEquals(1, model.size());
	assertTrue(model.contains(vf.createURI("urn:a"), SKOS.BROADER, vf.createURI("urn:b")));
}
 
Example #18
Source File: SailModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Optional<Namespace> removeNamespace(String prefix) {
	Namespace namespace = getNamespace(prefix).orElse(null);
	if (namespace != null) {
		try {
			conn.removeNamespace(prefix);
		} catch (SailException e) {
			throw new ModelException(e);
		}
	}
	return Optional.ofNullable(namespace);
}
 
Example #19
Source File: Serql.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void addQueryPrefixes(StringBuffer result, Collection<Namespace> namespaces) {
	StringBuilder str = new StringBuilder(512);

	str.append(" ").append(NAMESPACE).append(" ");
	for (Namespace namespace : namespaces) {
		str.append(namespace.getPrefix()).append(" = ");
		str.append("<").append(SeRQLUtil.encodeString(namespace.getName())).append(">, ");
	}
}
 
Example #20
Source File: FileIO.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void writeNamespaces(SailDataset store, DataOutputStream dataOut) throws IOException, SailException {
	try (CloseableIteration<? extends Namespace, SailException> iter = store.getNamespaces();) {
		while (iter.hasNext()) {
			Namespace ns = iter.next();
			dataOut.writeByte(NAMESPACE_MARKER);
			writeString(ns.getPrefix(), dataOut);
			writeString(ns.getName(), dataOut);
		}
	}
}
 
Example #21
Source File: NamespaceStore.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void writeNamespacesToFile() throws IOException {
	synchronized (file) {
		try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) {
			out.write(MAGIC_NUMBER);
			out.writeByte(FILE_FORMAT_VERSION);

			for (Namespace ns : namespacesMap.values()) {
				out.writeUTF(ns.getName());
				out.writeUTF(ns.getPrefix());
			}
		}
	}
}
 
Example #22
Source File: SailModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void setNamespace(Namespace namespace) {
	try {
		conn.setNamespace(namespace.getPrefix(), namespace.getName());
	} catch (SailException e) {
		throw new ModelException(e);
	}
}
 
Example #23
Source File: SailModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Namespace setNamespace(String prefix, String name) {
	try {
		conn.setNamespace(prefix, name);
	} catch (SailException e) {
		throw new ModelException(e);
	}
	return new SimpleNamespace(prefix, name);
}
 
Example #24
Source File: SailSourceModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Optional<Namespace> getNamespace(String prefix) {
	try {
		String name = dataset().getNamespace(prefix);
		return Optional.of(new SimpleNamespace(prefix, name));
	} catch (SailException e) {
		throw new ModelException(e);
	}
}
 
Example #25
Source File: SailSourceModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Namespace setNamespace(String prefix, String name) {
	try {
		sink().setNamespace(prefix, name);
	} catch (SailException e) {
		throw new ModelException(e);
	}
	return new SimpleNamespace(prefix, name);
}
 
Example #26
Source File: SailModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Optional<Namespace> getNamespace(String prefix) {
	try {
		String name = conn.getNamespace(prefix);
		return (name != null) ? Optional.of(new SimpleNamespace(prefix, name)) : Optional.ofNullable(null);
	} catch (SailException e) {
		throw new ModelException(e);
	}
}
 
Example #27
Source File: SailSourceModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Optional<Namespace> removeNamespace(String prefix) {
	Optional<Namespace> ret = getNamespace(prefix);
	try {
		sink().removeNamespace(prefix);
	} catch (SailException e) {
		throw new ModelException(e);
	}
	return ret;
}
 
Example #28
Source File: Namespaces.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Converts a set of {@link Namespace}s into a map containing the {@link Namespace#getPrefix()} strings as keys,
 * with the {@link Namespace#getName()} strings as values in the map for each namespace in the given set.
 *
 * @param namespaces The {@link Set} of {@link Namespace}s to transform.
 * @return A {@link Map} of {@link String} to {@link String} where the key/value combinations are created based on
 *         the prefix and names from {@link Namespace}s in the input set.
 */
public static Map<String, String> asMap(Set<Namespace> namespaces) {
	Map<String, String> result = new HashMap<>();

	for (Namespace nextNamespace : namespaces) {
		result.put(nextNamespace.getPrefix(), nextNamespace.getName());
	}

	return result;
}
 
Example #29
Source File: NamespacesTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}.
 */
@Test
public final void testWrapGet() throws Exception {
	Set<Namespace> testSet = new LinkedHashSet<>();
	Map<String, String> testMap = Namespaces.wrap(testSet);
	assertNull(testMap.get(testPrefix1));

	testSet.add(new SimpleNamespace(testPrefix1, testName1));
	assertEquals(testName1, testMap.get(testPrefix1));

	testSet.clear();
	assertNull(testMap.get(testPrefix1));
}
 
Example #30
Source File: AbstractSailConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public final CloseableIteration<? extends Namespace, SailException> getNamespaces() throws SailException {
	connectionLock.readLock().lock();
	try {
		verifyIsOpen();
		return registerIteration(getNamespacesInternal());
	} finally {
		connectionLock.readLock().unlock();
	}
}