下面列出了javax.xml.bind.annotation.adapters.HexBinaryAdapter#org.eclipse.rdf4j.model.BNode 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static StringBuilder toSPARQL(Value value, StringBuilder builder) {
if(value instanceof IRI) {
IRI aLit = (IRI)value;
builder.append("<").append(aLit.toString()).append(">");
} else if(value instanceof BNode) {
builder.append("_:").append(((BNode)value).getID());
} else if(value instanceof Literal) {
Literal aLit1 = (Literal)value;
builder.append("\"\"\"").append(RenderUtils.escape(aLit1.getLabel())).append("\"\"\"");
if(Literals.isLanguageLiteral(aLit1)) {
builder.append("@").append(aLit1.getLanguage());
} else if (value instanceof PlainLiteral) {
// do not print type
} else {
builder.append("^^<").append(aLit1.getDatatype().toString()).append(">");
}
}
return builder;
}
@Test
public void testWriteOneStatementsObjectBNodeSinglePredicateSingleContextBNodeReusedWithNamespace()
throws Exception {
Model input = new LinkedHashModel();
input.setNamespace("ex", exNs);
input.add(vf.createStatement(uri1, uri1, bnode, bnode));
ByteArrayOutputStream outputWriter = new ByteArrayOutputStream();
write(input, outputWriter);
ByteArrayInputStream inputReader = new ByteArrayInputStream(outputWriter.toByteArray());
Model parsedOutput = parse(inputReader, "");
assertEquals(1, parsedOutput.size());
Model doubleBNodeStatement = parsedOutput.filter(uri1, uri1, null);
assertEquals(1, doubleBNodeStatement.size());
assertEquals(1, parsedOutput.contexts().size());
if (rdfWriterFactory.getRDFFormat().supportsContexts()) {
assertTrue(parsedOutput.contexts().iterator().next() instanceof BNode);
}
assertEquals(1, parsedOutput.objects().size());
assertTrue(parsedOutput.objects().iterator().next() instanceof BNode);
assertTrue(doubleBNodeStatement.objects().iterator().next() instanceof BNode);
if (rdfWriterFactory.getRDFFormat().supportsContexts()) {
assertEquals(doubleBNodeStatement.objects().iterator().next(),
doubleBNodeStatement.contexts().iterator().next());
}
}
@Test
public void testDescribeAWhere() throws Exception {
loadTestData("/testdata-query/dataset-describe.trig");
StringBuilder query = new StringBuilder();
query.append(getNamespaceDeclarations());
query.append("DESCRIBE ?x WHERE {?x rdfs:label \"a\". } ");
GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());
ValueFactory f = conn.getValueFactory();
IRI a = f.createIRI("http://example.org/a");
IRI p = f.createIRI("http://example.org/p");
try (GraphQueryResult evaluate = gq.evaluate();) {
Model result = QueryResults.asModel(evaluate);
Set<Value> objects = result.filter(a, p, null).objects();
assertNotNull(objects);
for (Value object : objects) {
if (object instanceof BNode) {
assertTrue(result.contains((Resource) object, null, null));
assertEquals(2, result.filter((Resource) object, null, null).size());
}
}
}
}
public void end() throws RDFHandlerException {
if (list != null) {
endList(null);
}
// end any named graph lists
for (ListContext elementsCtx : namedGraphLists.values()) {
restore(elementsCtx);
endList(null);
}
// output all the var BNodes together to give a more friendlier RDF
// structure
for (Map.Entry<String, BNode> entry : varBNodes.entrySet()) {
handler.handleStatement(valueFactory.createStatement(entry.getValue(), SP.VAR_NAME_PROPERTY,
valueFactory.createLiteral(entry.getKey())));
}
}
private void writeBNode(BNode bNode) throws IOException {
String nextId = bNode.getID();
writer.append("_:");
if (nextId.isEmpty()) {
writer.append("genid");
writer.append(Integer.toHexString(bNode.hashCode()));
} else {
if (!ASCIIUtil.isLetter(nextId.charAt(0))) {
writer.append("genid");
writer.append(Integer.toHexString(nextId.charAt(0)));
}
for (int i = 0; i < nextId.length(); i++) {
if (ASCIIUtil.isLetterOrNumber(nextId.charAt(i))) {
writer.append(nextId.charAt(i));
} else {
// Append the character as its hex representation
writer.append(Integer.toHexString(nextId.charAt(i)));
}
}
}
}
@Test
public void testWriteUnsupportedEntityIdValue() throws RDFHandlerException,
RDFParseException, IOException {
AnyValueConverter valueConverter = new AnyValueConverter(
this.rdfWriter, this.rdfConversionBuffer, this.propertyRegister);
UnsupportedEntityIdValue value = mapper.readValue(
"{\"type\":\"wikibase-entityid\",\"value\":{\"entity-type\":\"funky\",\"id\":\"Z343\"}}",
UnsupportedEntityIdValueImpl.class);
PropertyIdValue propertyIdValue = objectFactory.getPropertyIdValue(
"P569", "http://www.wikidata.org/entity/");
Value valueURI = valueConverter.getRdfValue(value, propertyIdValue,
false);
this.rdfWriter.finish();
assertTrue(valueURI instanceof BNode);
}
/**
* Return the query string rendering of the {@link Value}
*
* @param theValue the value to render
* @return the value rendered in its query string representation
*/
public static String toSeRQL(Value theValue) {
StringBuilder aBuffer = new StringBuilder();
if (theValue instanceof IRI) {
IRI aURI = (IRI) theValue;
aBuffer.append("<").append(aURI.toString()).append(">");
} else if (theValue instanceof BNode) {
aBuffer.append("_:").append(((BNode) theValue).getID());
} else if (theValue instanceof Literal) {
Literal aLit = (Literal) theValue;
aBuffer.append("\"").append(escape(aLit.getLabel())).append("\"");
if (Literals.isLanguageLiteral(aLit)) {
aBuffer.append("@").append(aLit.getLanguage());
} else {
aBuffer.append("^^<").append(aLit.getDatatype().toString()).append(">");
}
}
return aBuffer.toString();
}
/**
* Tests basic N-Quads parsing with blank node.
*/
@Test
public void testParseBasicBNode() throws RDFHandlerException, IOException, RDFParseException {
final ByteArrayInputStream bais = new ByteArrayInputStream(
"_:a123456768 <http://www.w3.org/20/ica#dtend> <http://sin/value/2> <http://sin.siteserv.org/def/>."
.getBytes());
final TestRDFHandler rdfHandler = new TestRDFHandler();
parser.setRDFHandler(rdfHandler);
parser.parse(bais, "http://test.base.uri");
assertThat(rdfHandler.getStatements()).hasSize(1);
final Statement statement = rdfHandler.getStatements().iterator().next();
Assert.assertTrue(statement.getSubject() instanceof BNode);
Assert.assertEquals("http://www.w3.org/20/ica#dtend", statement.getPredicate().stringValue());
Assert.assertTrue(statement.getObject() instanceof IRI);
Assert.assertEquals("http://sin/value/2", statement.getObject().stringValue());
Assert.assertEquals("http://sin.siteserv.org/def/", statement.getContext().stringValue());
}
@Test
public void testBlankNodePredicateInference() {
Repository sailRepository = new SailRepository(createSail());
ValueFactory vf = sailRepository.getValueFactory();
try (RepositoryConnection connection = sailRepository.getConnection()) {
BNode bNode = vf.createBNode();
connection.add(vf.createStatement(vf.createIRI("http://a"), RDFS.SUBPROPERTYOF, bNode)); // 1
connection.add(vf.createStatement(bNode, RDFS.DOMAIN, vf.createIRI("http://c"))); // 2
connection.add(
vf.createStatement(vf.createIRI("http://d"), vf.createIRI("http://a"), vf.createIRI("http://e"))); // 3
}
try (RepositoryConnection connection = sailRepository.getConnection()) {
boolean correctInference = connection.hasStatement(vf.createIRI("http://d"), RDF.TYPE,
vf.createIRI("http://c"), true);
assertTrue("d should be type c, because 3 and 1 entail 'd _:bNode e' with 2 entail 'd type c'",
correctInference);
}
}
@Test
public void testRollbackClearSimple() {
SailRepository elasticsearchStore = new SailRepository(this.elasticsearchStore);
try (SailRepositoryConnection connection = elasticsearchStore.getConnection()) {
BNode context = vf.createBNode();
connection.begin(IsolationLevels.READ_COMMITTED);
connection.add(RDF.TYPE, RDF.TYPE, RDFS.RESOURCE);
connection.add(RDF.TYPE, RDF.TYPE, RDF.PROPERTY, context);
connection.commit();
connection.begin();
connection.clear();
assertEquals(0, connection.size());
connection.rollback();
assertEquals(2, connection.size());
}
}
@Test
public void testClear() {
SailRepository elasticsearchStore = new SailRepository(this.elasticsearchStore);
try (SailRepositoryConnection connection = elasticsearchStore.getConnection()) {
BNode context = vf.createBNode();
connection.begin(IsolationLevels.READ_COMMITTED);
connection.add(RDF.TYPE, RDF.TYPE, RDFS.RESOURCE);
connection.add(RDF.TYPE, RDF.TYPE, RDF.PROPERTY, context);
connection.commit();
connection.begin(IsolationLevels.NONE);
connection.clear();
connection.commit();
}
}
@Test
public void testWriteSingleStatementSubjectBNodeSingleContextBNode() throws Exception {
Model input = new LinkedHashModel();
input.add(vf.createStatement(bnodeSingleUseSubject, uri1, uri1, bnode));
ByteArrayOutputStream outputWriter = new ByteArrayOutputStream();
write(input, outputWriter);
ByteArrayInputStream inputReader = new ByteArrayInputStream(outputWriter.toByteArray());
Model parsedOutput = parse(inputReader, "");
assertEquals(1, parsedOutput.size());
assertEquals(1, parsedOutput.filter(null, uri1, uri1).size());
assertEquals(1, parsedOutput.contexts().size());
if (rdfWriterFactory.getRDFFormat().supportsContexts()) {
assertTrue(parsedOutput.contexts().iterator().next() instanceof BNode);
}
assertEquals(1, parsedOutput.subjects().size());
assertTrue(parsedOutput.subjects().iterator().next() instanceof BNode);
}
@Test
public void maxCount() throws Exception {
ShaclSail shaclSail = Utils.getInitializedShaclSail("shaclMax.ttl");
try (NotifyingSailConnection connection = shaclSail.getConnection()) {
SimpleValueFactory vf = SimpleValueFactory.getInstance();
connection.begin();
BNode bNode = vf.createBNode();
connection.addStatement(bNode, RDF.TYPE, RDFS.RESOURCE);
connection.addStatement(bNode, RDFS.LABEL, vf.createLiteral(""));
connection.commit();
shaclSail.setLogValidationPlans(true);
connection.begin();
BNode bNode2 = vf.createBNode();
connection.addStatement(bNode2, RDF.TYPE, RDFS.RESOURCE);
connection.removeStatement(null, bNode, RDFS.LABEL, vf.createLiteral(""));
connection.commit();
}
}
@Test(expected = SailException.class)
public void minCount() throws Exception {
ShaclSail shaclSail = Utils.getInitializedShaclSail("shacl.ttl");
try (NotifyingSailConnection connection = shaclSail.getConnection()) {
SimpleValueFactory vf = SimpleValueFactory.getInstance();
connection.begin();
BNode bNode = vf.createBNode();
connection.addStatement(bNode, RDF.TYPE, RDFS.RESOURCE);
connection.addStatement(bNode, RDFS.LABEL, vf.createLiteral(""));
connection.commit();
shaclSail.setLogValidationPlans(true);
connection.begin();
BNode bNode2 = vf.createBNode();
connection.addStatement(bNode2, RDF.TYPE, RDFS.RESOURCE);
connection.removeStatement(null, bNode, RDFS.LABEL, vf.createLiteral(""));
connection.commit();
}
}
private void assertSameModel(Model expected, Model actual) {
assertEquals(expected.size(), actual.size());
assertEquals(expected.subjects().size(), actual.subjects().size());
assertEquals(expected.predicates().size(), actual.predicates().size());
assertEquals(expected.objects().size(), actual.objects().size());
Set<Value> inputNodes = new HashSet<>(expected.subjects());
inputNodes.addAll(expected.objects());
Set<Value> outputNodes = new HashSet<>(actual.subjects());
outputNodes.addAll(actual.objects());
assertEquals(inputNodes.size(), outputNodes.size());
for (Statement st : expected) {
Resource subj = st.getSubject() instanceof IRI ? st.getSubject() : null;
IRI pred = st.getPredicate();
Value obj = st.getObject() instanceof BNode ? null : st.getObject();
assertTrue("Missing " + st, actual.contains(subj, pred, obj));
assertEquals(actual.filter(subj, pred, obj).size(), actual.filter(subj, pred, obj).size());
}
}
@Test
public void testWriteTwoStatementsSubjectBNodeSinglePredicateSingleContextIRIWithNamespace() throws Exception {
Model input = new LinkedHashModel();
input.setNamespace("ex", exNs);
input.add(vf.createStatement(bnodeSingleUseSubject, uri1, uri1, uri1));
input.add(vf.createStatement(bnodeSingleUseSubject, uri1, uri2, uri1));
ByteArrayOutputStream outputWriter = new ByteArrayOutputStream();
write(input, outputWriter);
ByteArrayInputStream inputReader = new ByteArrayInputStream(outputWriter.toByteArray());
Model parsedOutput = parse(inputReader, "");
assertEquals(2, parsedOutput.size());
if (rdfWriterFactory.getRDFFormat().supportsContexts()) {
assertEquals(1, parsedOutput.filter(null, uri1, uri1, uri1).size());
assertEquals(1, parsedOutput.filter(null, uri1, uri2, uri1).size());
} else {
assertEquals(1, parsedOutput.filter(null, uri1, uri1).size());
assertEquals(1, parsedOutput.filter(null, uri1, uri2).size());
}
assertEquals(1, parsedOutput.subjects().size());
assertTrue(parsedOutput.subjects().iterator().next() instanceof BNode);
}
/**
* 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);
}
@Test
public void testWriteSingleStatementSubjectBNodeSingleContextBNodeWithNamespace() throws Exception {
Model input = new LinkedHashModel();
input.setNamespace("ex", exNs);
input.add(vf.createStatement(bnodeSingleUseSubject, uri1, uri1, bnode));
ByteArrayOutputStream outputWriter = new ByteArrayOutputStream();
write(input, outputWriter);
ByteArrayInputStream inputReader = new ByteArrayInputStream(outputWriter.toByteArray());
Model parsedOutput = parse(inputReader, "");
assertEquals(1, parsedOutput.size());
assertEquals(1, parsedOutput.filter(null, uri1, uri1).size());
assertEquals(1, parsedOutput.contexts().size());
if (rdfWriterFactory.getRDFFormat().supportsContexts()) {
assertTrue(parsedOutput.contexts().iterator().next() instanceof BNode);
}
assertEquals(1, parsedOutput.subjects().size());
assertTrue(parsedOutput.subjects().iterator().next() instanceof BNode);
}
@Test
public void testEncodeValueRoundtrip() {
final ValueFactory vf = SimpleValueFactory.getInstance();
IRI uri = vf.createIRI("http://example.org/foo-bar");
String encodedUri = Protocol.encodeValue(uri);
IRI decodedUri = (IRI) Protocol.decodeValue(encodedUri, vf);
assertEquals(uri, decodedUri);
BNode bnode = vf.createBNode("foo-bar-1");
String encodedBnode = Protocol.encodeValue(bnode);
BNode decodedNode = (BNode) Protocol.decodeValue(encodedBnode, vf);
assertEquals(bnode, decodedNode);
Triple triple1 = vf.createTriple(bnode, uri, vf.createLiteral(16));
String encodedTriple1 = Protocol.encodeValue(triple1);
Triple decodedTriple1 = (Triple) Protocol.decodeValue(encodedTriple1, vf);
assertEquals(triple1, decodedTriple1);
Triple triple2 = vf.createTriple(bnode, uri, triple1);
String encodedTriple2 = Protocol.encodeValue(triple2);
Triple decodedTriple2 = (Triple) Protocol.decodeValue(encodedTriple2, vf);
assertEquals(triple2, decodedTriple2);
}
/**
* Append the SPARQL query string rendering of the {@link org.eclipse.rdf4j.model.Value} to the supplied
* {@link StringBuilder}.
*
* @param value the value to render
* @param builder the {@link StringBuilder} to append to
* @return the original {@link StringBuilder} with the value appended.
*/
public static StringBuilder toSPARQL(Value value, StringBuilder builder) {
if (value instanceof IRI) {
IRI aURI = (IRI) value;
builder.append("<").append(aURI.toString()).append(">");
} else if (value instanceof BNode) {
builder.append("_:").append(((BNode) value).getID());
} else if (value instanceof Literal) {
Literal aLit = (Literal) value;
builder.append("\"\"\"").append(escape(aLit.getLabel())).append("\"\"\"");
if (Literals.isLanguageLiteral(aLit)) {
aLit.getLanguage().ifPresent(lang -> builder.append("@").append(lang));
} else {
builder.append("^^<").append(aLit.getDatatype().toString()).append(">");
}
}
return builder;
}
@Test
public void testWriteTwoStatementsSubjectBNodeSinglePredicateSingleContextBNodeWithNamespace() throws Exception {
Model input = new LinkedHashModel();
input.setNamespace("ex", exNs);
input.add(vf.createStatement(bnodeSingleUseSubject, uri1, uri1, bnode));
input.add(vf.createStatement(bnodeSingleUseSubject, uri1, uri2, bnode));
ByteArrayOutputStream outputWriter = new ByteArrayOutputStream();
write(input, outputWriter);
ByteArrayInputStream inputReader = new ByteArrayInputStream(outputWriter.toByteArray());
Model parsedOutput = parse(inputReader, "");
assertEquals(2, parsedOutput.size());
assertEquals(1, parsedOutput.filter(null, uri1, uri1).size());
assertEquals(1, parsedOutput.filter(null, uri1, uri2).size());
assertEquals(1, parsedOutput.contexts().size());
if (rdfWriterFactory.getRDFFormat().supportsContexts()) {
assertTrue(parsedOutput.contexts().iterator().next() instanceof BNode);
}
assertEquals(1, parsedOutput.subjects().size());
assertTrue(parsedOutput.subjects().iterator().next() instanceof BNode);
}
@Test
public void testWriteSingleStatementSubjectBNodeSingleContextIRI() throws Exception {
Model input = new LinkedHashModel();
input.add(vf.createStatement(bnodeSingleUseSubject, uri1, uri1, uri1));
ByteArrayOutputStream outputWriter = new ByteArrayOutputStream();
write(input, outputWriter);
ByteArrayInputStream inputReader = new ByteArrayInputStream(outputWriter.toByteArray());
Model parsedOutput = parse(inputReader, "");
assertEquals(1, parsedOutput.size());
if (rdfWriterFactory.getRDFFormat().supportsContexts()) {
assertEquals(1, parsedOutput.filter(null, uri1, uri1, uri1).size());
} else {
assertEquals(1, parsedOutput.filter(null, uri1, uri1).size());
}
assertEquals(1, parsedOutput.subjects().size());
assertTrue(parsedOutput.subjects().iterator().next() instanceof BNode);
}
/**
* Tests basic N-Quads parsing with literal.
*/
@Test
public void testParseBasicLiteral() throws RDFHandlerException, IOException, RDFParseException {
final ByteArrayInputStream bais = new ByteArrayInputStream(
"_:a123456768 <http://www.w3.org/20/ica#dtend> \"2010-05-02\" <http://sin.siteserv.org/def/>."
.getBytes());
final TestRDFHandler rdfHandler = new TestRDFHandler();
parser.setRDFHandler(rdfHandler);
parser.parse(bais, "http://test.base.uri");
assertThat(rdfHandler.getStatements()).hasSize(1);
final Statement statement = rdfHandler.getStatements().iterator().next();
Assert.assertTrue(statement.getSubject() instanceof BNode);
Assert.assertEquals("http://www.w3.org/20/ica#dtend", statement.getPredicate().stringValue());
Assert.assertTrue(statement.getObject() instanceof Literal);
Assert.assertEquals("2010-05-02", statement.getObject().stringValue());
Assert.assertEquals("http://sin.siteserv.org/def/", statement.getContext().stringValue());
}
/**
* Write out the opening tag of the subject or object of a statement up to (but not including) the end of the tag.
* Used both in writeStartSubject and writeEmptySubject.
*/
private void writeNodeStartOfStartTag(Node node) throws IOException, RDFHandlerException {
Value value = node.getValue();
if (node.hasType()) {
// We can use abbreviated syntax
writeStartOfStartTag(node.getType().getNamespace(), node.getType().getLocalName());
} else {
// We cannot use abbreviated syntax
writeStartOfStartTag(RDF.NAMESPACE, "Description");
}
if (value instanceof IRI) {
IRI uri = (IRI) value;
writeAttribute(RDF.NAMESPACE, "about", uri.toString());
} else {
BNode bNode = (BNode) value;
writeAttribute(RDF.NAMESPACE, "nodeID", getValidNodeId(bNode));
}
}
/**
* Applies the projection to a value. If the result has a blank node whose ID is not mapped to a value in
* {@code blankNodes}, then a random UUID will be used.
*
* @param bs - The value the projection will be applied to. (not null)
* @param blankNodes - A map from node source names to the blank nodes that will be used for those names. (not null)
* @return A new value that is the result of the projection.
*/
public VisibilityBindingSet project(final VisibilityBindingSet bs, final Map<String, BNode> blankNodes) {
requireNonNull(bs);
requireNonNull(blankNodes);
// Apply the projection elements against the original binding set.
final MapBindingSet result = new MapBindingSet();
for (final ProjectionElem elem : projectionElems.getElements()) {
final String sourceName = elem.getSourceName();
Value value = null;
// If the binding set already has the source name, then use the target name.
if (bs.hasBinding(sourceName)) {
value = bs.getValue(elem.getSourceName());
}
// If the source name represents a constant value, then use the constant.
else if(constantSources.containsKey(sourceName)) {
value = constantSources.get(sourceName);
}
// If the source name represents an anonymous value, then create a Blank Node.
else if(anonymousSources.contains(sourceName)) {
if(blankNodes.containsKey(sourceName)) {
value = blankNodes.get(sourceName);
} else {
value = VF.createBNode( UUID.randomUUID().toString() );
}
}
// Only add the value if there is one. There may not be one if a binding is optional.
if(value != null) {
result.addBinding(elem.getTargetName(), value);
}
}
return new VisibilityBindingSet(result, bs.getVisibility());
}
public void setValue(Object aValue)
{
if (aValue instanceof Value) {
if (aValue instanceof Literal) {
Literal litValue = (Literal) aValue;
try {
language = litValue.getLanguage().orElse(null);
value = new DefaultDatatypeMapper().getJavaObject(litValue);
}
catch (Exception e) {
value = "ERROR converting [" + litValue + "]: " + e.getMessage();
}
}
else if (aValue instanceof IRI) {
value = aValue;
}
else if (aValue instanceof BNode) {
value = null;
}
else {
value = "ERROR: Unknown object type: " + aValue.getClass();
}
}
else {
value = aValue;
}
}
/**
* Appends the N-Triples representation of the given {@link Resource} to the given {@link Appendable}.
*
* @param resource The resource to write.
* @param appendable The object to append to.
* @throws IOException
*/
public static void append(Resource resource, Appendable appendable) throws IOException {
if (resource instanceof IRI) {
append((IRI) resource, appendable);
} else if (resource instanceof BNode) {
append((BNode) resource, appendable);
} else if (resource instanceof Triple) {
append((Triple) resource, appendable);
} else {
throw new IllegalArgumentException("Unknown resource type: " + resource.getClass());
}
}
@Test
public void testWriteSingleStatementNoBNodesSingleContextBnode() throws Exception {
Model input = new LinkedHashModel();
input.add(vf.createStatement(uri1, uri1, uri1, bnode));
ByteArrayOutputStream outputWriter = new ByteArrayOutputStream();
write(input, outputWriter);
ByteArrayInputStream inputReader = new ByteArrayInputStream(outputWriter.toByteArray());
Model parsedOutput = parse(inputReader, "");
assertEquals(1, parsedOutput.size());
assertEquals(1, parsedOutput.filter(uri1, uri1, uri1).size());
assertEquals(1, parsedOutput.contexts().size());
if (rdfWriterFactory.getRDFFormat().supportsContexts()) {
assertTrue(parsedOutput.contexts().iterator().next() instanceof BNode);
}
}
@Override
public BNode createBNode(String nodeID) {
if (nodeID.length() < 1) {
throw new IllegalArgumentException("Blank node ID cannot be empty");
}
if (!isMember(PN_CHARS_U, nodeID.codePointAt(0))) {
throw new IllegalArgumentException("Blank node ID must start with alphanumber or underscore");
}
for (int i = 0, n = nodeID.codePointCount(0, nodeID.length()); i < n; i++) {
if (!isMember(PN_CHARS, nodeID.codePointAt(nodeID.offsetByCodePoints(0, i)))) {
throw new IllegalArgumentException("Illegal blank node ID character");
}
}
return delegate.createBNode(nodeID);
}
@Test
public void testDescribeD() throws Exception {
loadTestData("/testdata-query/dataset-describe.trig");
StringBuilder query = new StringBuilder();
query.append(getNamespaceDeclarations());
query.append("DESCRIBE ex:d");
GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());
ValueFactory f = conn.getValueFactory();
IRI d = f.createIRI("http://example.org/d");
IRI p = f.createIRI("http://example.org/p");
IRI e = f.createIRI("http://example.org/e");
try (GraphQueryResult evaluate = gq.evaluate();) {
Model result = QueryResults.asModel(evaluate);
assertNotNull(result);
assertTrue(result.contains(null, p, e));
assertFalse(result.contains(e, null, null));
Set<Value> objects = result.filter(d, p, null).objects();
assertNotNull(objects);
for (Value object : objects) {
if (object instanceof BNode) {
Set<Value> childObjects = result.filter((BNode) object, null, null).objects();
assertNotNull(childObjects);
for (Value childObject : childObjects) {
if (childObject instanceof BNode) {
assertTrue(result.contains((BNode) childObject, null, null));
}
}
}
}
}
}