org.eclipse.rdf4j.rio.RDFWriter Java Examples
The following examples show how to use
org.eclipse.rdf4j.rio.RDFWriter.
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: JSONLDWriterTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testEmptyNamespace() throws Exception { IRI uri1 = vf.createIRI(exNs, "uri1"); IRI uri2 = vf.createIRI(exNs, "uri2"); StringWriter w = new StringWriter(); RDFWriter rdfWriter = rdfWriterFactory.getWriter(w); rdfWriter.getWriterConfig().set(JSONLDSettings.JSONLD_MODE, JSONLDMode.COMPACT); rdfWriter.startRDF(); rdfWriter.handleNamespace("", exNs); rdfWriter.handleNamespace(DCTERMS.PREFIX, DCTERMS.NAMESPACE); rdfWriter.handleStatement(vf.createStatement(uri1, DCTERMS.TITLE, vf.createBNode())); rdfWriter.handleStatement(vf.createStatement(uri1, uri2, vf.createBNode())); rdfWriter.endRDF(); assertTrue("Does not contain @vocab", w.toString().contains("@vocab")); }
Example #2
Source File: RDFXMLPrettyWriterTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void inSequenceItemsMixedWithOtherElementsAreAbbreviated() throws RDFHandlerException, IOException { StringWriter writer = new StringWriter(); RDFWriter rdfWriter = rdfWriterFactory.getWriter(writer); rdfWriter.startRDF(); Resource res = vf.createIRI("http://example.com/#"); rdfWriter.handleStatement(vf.createStatement(res, RDF.TYPE, RDF.BAG)); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_2"), vf.createIRI("http://example.com/#2"))); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_1"), vf.createIRI("http://example.com/#1"))); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_3"), vf.createIRI("http://example.com/#3"))); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_2"), vf.createIRI("http://example.com/#2"))); rdfWriter.endRDF(); List<String> rdfLines = rdfOpenTags(writer.toString()); assertEquals(Arrays.asList("<rdf:RDF", "<rdf:Bag", "<rdf:_2", "<rdf:li", "<rdf:_3", "<rdf:li"), rdfLines); }
Example #3
Source File: InferencingTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
private File dumpStatements(String name, Collection<? extends Statement> statements) throws Exception { // Dump results to tmp file for debugging String tmpDir = System.getProperty("java.io.tmpdir"); name = name.replace("/", "_"); File tmpFile = new File(tmpDir, "junit-" + name + ".nt"); tmpFile.createNewFile(); try (OutputStream export = new BufferedOutputStream(new FileOutputStream(tmpFile))) { RDFWriter writer = Rio.createWriter(RDFFormat.NTRIPLES, export); writer.startRDF(); for (Statement st : statements) { writer.handleStatement(st); } writer.endRDF(); } return tmpFile; }
Example #4
Source File: RDFXMLPrettyWriterTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void outOfSequenceItemsAreNotAbbreviated() throws RDFHandlerException, IOException { StringWriter writer = new StringWriter(); RDFWriter rdfWriter = rdfWriterFactory.getWriter(writer); rdfWriter.startRDF(); Resource res = vf.createIRI("http://example.com/#"); rdfWriter.handleStatement(vf.createStatement(res, RDF.TYPE, RDF.BAG)); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_0"), vf.createIRI("http://example.com/#0"))); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_2"), vf.createIRI("http://example.com/#2"))); rdfWriter.endRDF(); List<String> rdfLines = rdfOpenTags(writer.toString()); assertEquals(Arrays.asList("<rdf:RDF", "<rdf:Bag", "<rdf:_0", "<rdf:_2"), rdfLines); }
Example #5
Source File: RDFXMLWriterTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Write a statement with a literal that needs escaping as RDF/XML to a string * * @param useSingle use single quotes * @param withinText quotes to entity within text * @return RDF/XML output as string */ private String writeQuotable(boolean useSingle, boolean withinText) { Statement st = vf.createStatement(vf.createBNode(), DCTERMS.TITLE, vf.createLiteral("Single ' quote / Double \" quote")); StringWriter outputWriter = new StringWriter(); RDFWriter rdfWriter = rdfWriterFactory.getWriter(outputWriter); rdfWriter.getWriterConfig() .set(BasicWriterSettings.PRETTY_PRINT, false) .set(XMLWriterSettings.INCLUDE_XML_PI, true) .set(XMLWriterSettings.USE_SINGLE_QUOTES, useSingle) .set(XMLWriterSettings.QUOTES_TO_ENTITIES_IN_TEXT, withinText); rdfWriter.startRDF(); rdfWriter.handleStatement(st); rdfWriter.endRDF(); return outputWriter.toString(); }
Example #6
Source File: RDFXMLPrettyWriterBackgroundTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void sequenceItemsAreAbbreviated() throws RDFHandlerException, IOException { StringWriter writer = new StringWriter(); RDFWriter rdfWriter = rdfWriterFactory.getWriter(writer); rdfWriter.startRDF(); Resource res = vf.createIRI("http://example.com/#"); rdfWriter.handleStatement(vf.createStatement(res, RDF.TYPE, RDF.BAG)); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_1"), vf.createIRI("http://example.com/#1"))); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_2"), vf.createIRI("http://example.com/#2"))); rdfWriter.endRDF(); List<String> rdfLines = rdfOpenTags(writer.toString()); assertEquals(Arrays.asList("<rdf:RDF", "<rdf:Bag", "<rdf:li", "<rdf:li"), rdfLines); }
Example #7
Source File: RDFXMLPrettyWriterBackgroundTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void outOfSequenceItemsAreNotAbbreviated() throws RDFHandlerException, IOException { StringWriter writer = new StringWriter(); RDFWriter rdfWriter = rdfWriterFactory.getWriter(writer); rdfWriter.startRDF(); Resource res = vf.createIRI("http://example.com/#"); rdfWriter.handleStatement(vf.createStatement(res, RDF.TYPE, RDF.BAG)); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_0"), vf.createIRI("http://example.com/#0"))); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_2"), vf.createIRI("http://example.com/#2"))); rdfWriter.endRDF(); List<String> rdfLines = rdfOpenTags(writer.toString()); assertEquals(Arrays.asList("<rdf:RDF", "<rdf:Bag", "<rdf:_0", "<rdf:_2"), rdfLines); }
Example #8
Source File: QueryResultsOutputUtil.java From rya with Apache License 2.0 | 6 votes |
/** * Writes the results of a {@link QueryResultStream} to the output stream as NTriples until the * shutdown signal is set. * * @param out - The stream the NTriples data will be written to. (not null) * @param resultsStream - The results stream that will be polled for results to * write to {@code out}. (not null) * @param shutdownSignal - Setting this signal will cause the thread that * is processing this function to finish and leave. (not null) * @throws RDFHandlerException A problem was encountered while * writing the NTriples to the output stream. * @throws IllegalStateException The {@code resultsStream} is closed. * @throws RyaStreamsException Could not fetch the next set of results. */ public static void toNtriplesFile( final OutputStream out, final QueryResultStream<VisibilityStatement> resultsStream, final AtomicBoolean shutdownSignal) throws RDFHandlerException, IllegalStateException, RyaStreamsException { requireNonNull(out); requireNonNull(resultsStream); requireNonNull(shutdownSignal); final RDFWriter writer = Rio.createWriter(RDFFormat.NTRIPLES, out); writer.startRDF(); while(!shutdownSignal.get()) { final Iterable<VisibilityStatement> it = resultsStream.poll(1000); for(final VisibilityStatement result : it) { writer.handleStatement(result); } } writer.endRDF(); }
Example #9
Source File: RDFXMLPrettyWriterBackgroundTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void inSequenceItemsMixedWithOtherElementsAreAbbreviated() throws RDFHandlerException, IOException { StringWriter writer = new StringWriter(); RDFWriter rdfWriter = rdfWriterFactory.getWriter(writer); rdfWriter.startRDF(); Resource res = vf.createIRI("http://example.com/#"); rdfWriter.handleStatement(vf.createStatement(res, RDF.TYPE, RDF.BAG)); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_2"), vf.createIRI("http://example.com/#2"))); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_1"), vf.createIRI("http://example.com/#1"))); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_3"), vf.createIRI("http://example.com/#3"))); rdfWriter.handleStatement( vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_2"), vf.createIRI("http://example.com/#2"))); rdfWriter.endRDF(); List<String> rdfLines = rdfOpenTags(writer.toString()); assertEquals(Arrays.asList("<rdf:RDF", "<rdf:Bag", "<rdf:_2", "<rdf:li", "<rdf:_3", "<rdf:li"), rdfLines); }
Example #10
Source File: KnowledgeBaseServiceImpl.java From inception with Apache License 2.0 | 5 votes |
@Override public void exportData(KnowledgeBase kb, RDFFormat format, OutputStream os) { if (kb.getType() != RepositoryType.LOCAL) { log.info("Not exporting non-local knowledge base: [{}]", kb.getName()); return; } try (RepositoryConnection conn = getConnection(kb)) { RDFWriter rdfWriter = Rio.createWriter(format, os); conn.export(rdfWriter); } }
Example #11
Source File: Prefixes.java From amazon-neptune-tools with Apache License 2.0 | 5 votes |
public void parse(String s, RDFWriter writer) { int i = s.indexOf("#"); if (i > 0 && i < (s.length() - 1)) { String uri = s.substring(0, i + 1); if (!prefixes.containsKey(uri)) { String prefix = "s" + (prefixes.size() - offset); prefixes.put(uri, prefix); writer.handleNamespace(prefix, uri); } } }
Example #12
Source File: JSONLDWriterTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testRoundTripNamespaces() throws Exception { IRI uri1 = vf.createIRI(exNs, "uri1"); IRI uri2 = vf.createIRI(exNs, "uri2"); Literal plainLit = vf.createLiteral("plain", XMLSchema.STRING); Statement st1 = vf.createStatement(uri1, uri2, plainLit); ByteArrayOutputStream out = new ByteArrayOutputStream(); RDFWriter rdfWriter = rdfWriterFactory.getWriter(out); rdfWriter.getWriterConfig().set(JSONLDSettings.JSONLD_MODE, JSONLDMode.COMPACT); rdfWriter.startRDF(); rdfWriter.handleNamespace("ex", exNs); rdfWriter.handleStatement(st1); rdfWriter.endRDF(); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); RDFParser rdfParser = rdfParserFactory.getParser(); ParserConfig config = new ParserConfig(); config.set(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, true); config.set(BasicParserSettings.FAIL_ON_UNKNOWN_LANGUAGES, true); rdfParser.setParserConfig(config); rdfParser.setValueFactory(vf); Model model = new LinkedHashModel(); rdfParser.setRDFHandler(new StatementCollector(model)); rdfParser.parse(in, "foo:bar"); assertEquals("Unexpected number of statements, found " + model.size(), 1, model.size()); assertTrue("missing namespaced statement", model.contains(st1)); if (rdfParser.getRDFFormat().supportsNamespaces()) { assertTrue("Expected at least one namespace, found " + model.getNamespaces().size(), model.getNamespaces().size() >= 1); assertEquals(exNs, model.getNamespace("ex").get().getName()); } }
Example #13
Source File: QueryEvaluator.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Get a graph result (RIO) writer based upon the file name (extension), or return the console result writer when * path is null. * * @param path path or null * @param out output stream or null * @return result writer * @throws IllegalArgumentException */ private RDFWriter getRDFWriter(Path path, OutputStream out) throws IllegalArgumentException { RDFWriter w; if (path == null) { w = new ConsoleRDFWriter(consoleIO, getConsoleWidth()); } else { Optional<RDFFormat> fmt = Rio.getWriterFormatForFileName(path.toFile().toString()); if (!fmt.isPresent()) { throw new IllegalArgumentException("No suitable result writer found"); } w = Rio.createWriter(fmt.get(), out); } return w; }
Example #14
Source File: TupleAndGraphQueryEvaluator.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Evaluate SPARQL or SERQL graph query * * @param queryLn query language * @param queryString query string * @param writer RDFWriter to write the results to * @param namespaces namespaces to write to the RDFWriter * @throws UnsupportedQueryLanguageException * @throws MalformedQueryException * @throws QueryEvaluationException * @throws RepositoryException */ protected void evaluateGraphQuery(QueryLanguage queryLn, String queryString, RDFWriter writer, Collection<Namespace> namespaces) throws UnsupportedQueryLanguageException, MalformedQueryException, QueryEvaluationException, RepositoryException { Repository repository = state.getRepository(); consoleIO.writeln("Evaluating " + queryLn.getName() + " query..."); int resultCount = 0; long startTime = System.nanoTime(); try (RepositoryConnection con = repository.getConnection(); GraphQueryResult res = con.prepareGraphQuery(queryLn, queryString).evaluate()) { con.setParserConfig(nonVerifyingParserConfig); writer.startRDF(); namespaces.forEach(ns -> writer.handleNamespace(ns.getPrefix(), ns.getName())); while (res.hasNext()) { writer.handleStatement(res.next()); resultCount++; } writer.endRDF(); } long endTime = System.nanoTime(); consoleIO.writeln(resultCount + " results (" + (endTime - startTime) / 1_000_000 + " ms)"); }
Example #15
Source File: QueryResultIO.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Writes a graph query result document in a specific RDF format to an output stream. * * @param gqr The query result to write. * @param format The file format of the document to write. * @param out An OutputStream to write the document to. * @throws IOException If an I/O error occurred while writing the query result document to the * stream. * @throws RDFHandlerException If such an exception is thrown by the used RDF writer. * @throws QueryEvaluationException * @throws UnsupportedRDFormatException If an unsupported query result file format was specified. */ public static void writeGraph(GraphQueryResult gqr, RDFFormat format, OutputStream out) throws IOException, RDFHandlerException, UnsupportedRDFormatException, QueryEvaluationException { RDFWriter writer = Rio.createWriter(format, out); try { QueryResults.report(gqr, writer); } catch (RDFHandlerException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { throw e; } } }
Example #16
Source File: KnowledgeBaseServiceImplQualifierIntegrationTest.java From inception with Apache License 2.0 | 5 votes |
@Test public void upsertQualifier_withUnsavedQualifier_shouldCreateQualifier() { KBQualifier qualifier = testFixtures.buildQualifier(statement, property, "Test qualifier"); sut.upsertQualifier(kb, qualifier); sut.read(kb, conn -> { RDFWriter rdfWriter = Rio.createWriter(RDFFormat.TURTLE, System.out); conn.export(rdfWriter); System.out.println("------"); return null; }); List<KBStatement> statements = sut.listStatements(kb, conceptHandle, false); assertThat(qualifier.getStatement().getQualifiers()) .as("Check that KBStatement has updated correctly") .hasSize(1) .element(0) .hasFieldOrProperty("property") .hasFieldOrPropertyWithValue("value", "Test qualifier"); assertThat(statements.get(0).getQualifiers()) .as("Check that Knowledge Base has updated correctly") .hasSize(1) .element(0) .hasFieldOrProperty("property") .hasFieldOrPropertyWithValue("value", "Test qualifier"); }
Example #17
Source File: RepositoryModel.java From semweb4j with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void writeTo(OutputStream stream, Syntax syntax) throws // interface allows it IOException, ModelRuntimeException { RDFWriter rdfWriter = Rio.createWriter(getRDFFormat(syntax), stream); writeTo(rdfWriter); }
Example #18
Source File: RepositoryModel.java From semweb4j with BSD 2-Clause "Simplified" License | 5 votes |
public void writeTo(RDFWriter writer) throws ModelRuntimeException { assertModel(); try { this.connection.exportStatements(null, null, null, false, writer, this.rdf4jContext); } catch (RepositoryException | RDFHandlerException e) { throw new ModelRuntimeException(e); } }
Example #19
Source File: GraphQueryResultView.java From semagrow with Apache License 2.0 | 5 votes |
protected void renderInternal(Map model, HttpServletRequest request, HttpServletResponse response) throws IOException { RDFWriterFactory rdfWriterFactory = (RDFWriterFactory)model.get("factory"); RDFFormat rdfFormat = rdfWriterFactory.getRDFFormat(); response.setStatus(200); this.setContentType(response, rdfFormat); this.setContentDisposition(model, response, rdfFormat); boolean headersOnly = ((Boolean)model.get("headersOnly")).booleanValue(); if(!headersOnly) { ServletOutputStream out = response.getOutputStream(); try { RDFWriter e = rdfWriterFactory.getWriter(out); GraphQuery graphQuery = (GraphQuery)model.get("queryResult"); graphQuery.evaluate(e); } catch (QueryInterruptedException var15) { this.logger.error("Query interrupted", var15); response.sendError(503, "Query evaluation took too long"); } catch (QueryEvaluationException var16) { this.logger.error("Query evaluation error", var16); response.sendError(500, "Query evaluation error: " + var16.getMessage()); } catch (RDFHandlerException var17) { this.logger.error("Serialization error", var17); response.sendError(500, "Serialization error: " + var17.getMessage()); } finally { out.close(); } } this.logEndOfRequest(request); }
Example #20
Source File: NQuadsWriterFactory.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Returns a new instance of {@link NQuadsWriter}. */ @Override public RDFWriter getWriter(Writer writer) { return new NQuadsWriter(writer); }
Example #21
Source File: ArrangedWriterTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
private void write(Model model, OutputStream writer) { RDFWriter rdfWriter = writerFactory.getWriter(writer); // "pretty print" forces ArrangedWriter to handle namespaces rdfWriter.getWriterConfig().set(BasicWriterSettings.PRETTY_PRINT, true); Rio.write(model, rdfWriter); }
Example #22
Source File: BinaryRDFWriterFactory.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Returns a new instance of {@link BinaryRDFWriter}. */ @Override public RDFWriter getWriter(OutputStream out) { return new BinaryRDFWriter(out); }
Example #23
Source File: JSONLDWriterFactory.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public RDFWriter getWriter(Writer writer, String baseURI) { return new JSONLDWriter(writer, baseURI); }
Example #24
Source File: TurtleStarHandlingTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override protected RDFWriter createWriter(OutputStream output) { return new TurtleStarWriter(output); }
Example #25
Source File: NQuadsWriterFactory.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public RDFWriter getWriter(Writer writer, String baseURI) { return getWriter(writer); }
Example #26
Source File: NQuadsHandlingTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override protected RDFWriter createWriter(OutputStream output) { return new NQuadsWriter(output); }
Example #27
Source File: TriGStarWriterFactory.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Returns a new instance of {@link TriGStarWriter}. */ @Override public RDFWriter getWriter(OutputStream out) { return new TriGStarWriter(out); }
Example #28
Source File: BinaryRDFWriterFactory.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * throws UnsupportedOperationException */ @Override public RDFWriter getWriter(Writer writer) { throw new UnsupportedOperationException(); }
Example #29
Source File: TurtleStarWriterFactory.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public RDFWriter getWriter(Writer writer, String baseURI) throws URISyntaxException { return new ArrangedWriter(new TurtleStarWriter(writer, new ParsedIRI(baseURI))); }
Example #30
Source File: TriGStarWriterFactory.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Returns a new instance of {@link TriGStarWriter}. */ @Override public RDFWriter getWriter(Writer writer) { return new TriGStarWriter(writer); }