org.eclipse.rdf4j.rio.helpers.BasicWriterSettings Java Examples

The following examples show how to use org.eclipse.rdf4j.rio.helpers.BasicWriterSettings. 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: JSONParserParseTest.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Test
public void testParse() throws Exception {
    Model transformedModel = new LinkedHashModel();
    RDFParser parser = new JSONParser();
    parser.setValueFactory(SimpleValueFactory.getInstance());
    parser.set(JSONParser.GENERATE_ONTOLOGY, true);
    parser.setRDFHandler(new ContextStatementCollector(transformedModel, SimpleValueFactory.getInstance()));
    parser.parse(JSONParserParseTest.class.getResourceAsStream(parameter + ".json"), "http://testParse/"+parameter + "/");

    WriterConfig wc = new WriterConfig();
    wc.set(BasicWriterSettings.PRETTY_PRINT, true);
    System.out.println("-------------- " + parameter + " ------------------");
    Rio.write(transformedModel, System.out, RDFFormat.TURTLE, wc);

    Model expectedModel = Rio.parse(JSONParserParseTest.class.getResourceAsStream(parameter + ".ttl"), "http://testParse/" + parameter + "/", RDFFormat.TURTLE);

    JSONParserParseTest.assertEquals(expectedModel, transformedModel);
}
 
Example #2
Source File: SpinRendererTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static String toRDF(StatementCollector stmts) throws RDFHandlerException {
	WriterConfig config = new WriterConfig();
	config.set(BasicWriterSettings.PRETTY_PRINT, false);
	StringBuilderWriter writer = new StringBuilderWriter();
	final RDFWriter rdfWriter = Rio.createWriter(RDFFormat.TURTLE, writer);
	rdfWriter.setWriterConfig(config);

	rdfWriter.startRDF();
	for (Map.Entry<String, String> entry : stmts.getNamespaces().entrySet()) {
		rdfWriter.handleNamespace(entry.getKey(), entry.getValue());
	}
	for (final Statement st : stmts.getStatements()) {
		rdfWriter.handleStatement(st);
	}
	rdfWriter.endRDF();

	writer.close();
	return writer.toString();
}
 
Example #3
Source File: PropertyShape.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
String describe(SailRepositoryConnection connection, Resource resource) {
	GraphQuery graphQuery = connection.prepareGraphQuery("describe ?a where {BIND(?resource as ?a)}");
	graphQuery.setBinding("resource", resource);

	try (Stream<Statement> stream = graphQuery.evaluate().stream()) {

		LinkedHashModel statements = stream.collect(Collectors.toCollection(LinkedHashModel::new));
		statements.setNamespace(SHACL.PREFIX, SHACL.NAMESPACE);

		WriterConfig config = new WriterConfig();
		config.set(BasicWriterSettings.PRETTY_PRINT, true);
		config.set(BasicWriterSettings.INLINE_BLANK_NODES, true);

		StringWriter stringWriter = new StringWriter();

		Rio.write(statements, stringWriter, RDFFormat.TURTLE, config);

		return stringWriter.toString();
	}
}
 
Example #4
Source File: RDFXMLWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #5
Source File: AbstractNQuadsWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testBlankNodeContextAddXSDString() throws RDFHandlerException {
	Statement s1 = vf.createStatement(vf.createIRI("http://test.example.org/test/subject/1"),
			vf.createIRI("http://other.example.com/test/predicate/1"), vf.createLiteral("test literal"),
			vf.createBNode());

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	writer = rdfWriterFactory.getWriter(baos);
	writer.getWriterConfig().set(BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL, false);
	writer.startRDF();
	writer.handleStatement(s1);
	writer.endRDF();

	String content = baos.toString();
	String[] lines = content.split("\n");
	Assert.assertEquals("Unexpected number of lines.", 1, lines.length);
	Assert.assertTrue(lines[0].startsWith(
			"<http://test.example.org/test/subject/1> <http://other.example.com/test/predicate/1> \"test literal\"^^<http://www.w3.org/2001/XMLSchema#string> _:"));
}
 
Example #6
Source File: AbstractNQuadsWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testNoContextAddXSDString() throws RDFHandlerException {
	Statement s1 = vf.createStatement(vf.createIRI("http://test.example.org/test/subject/1"),
			vf.createIRI("http://other.example.com/test/predicate/1"), vf.createLiteral("test literal"));

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	writer = rdfWriterFactory.getWriter(baos);
	writer.getWriterConfig().set(BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL, false);
	writer.startRDF();
	writer.handleStatement(s1);
	writer.endRDF();

	String content = baos.toString();
	String[] lines = content.split("\n");
	Assert.assertEquals("Unexpected number of lines.", 1, lines.length);
	Assert.assertEquals(
			"<http://test.example.org/test/subject/1> <http://other.example.com/test/predicate/1> \"test literal\"^^<http://www.w3.org/2001/XMLSchema#string> .",
			lines[0]);
}
 
Example #7
Source File: TurtleWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void consumeStatement(Statement st) throws RDFHandlerException {
	try {
		Resource subj = st.getSubject();
		IRI pred = st.getPredicate();
		inlineBNodes = getWriterConfig().get(BasicWriterSettings.INLINE_BLANK_NODES);
		if (inlineBNodes && (pred.equals(RDF.FIRST) || pred.equals(RDF.REST))) {
			handleList(st);
		} else if (inlineBNodes && !subj.equals(lastWrittenSubject) && stack.contains(subj)) {
			handleInlineNode(st);
		} else {
			closeHangingResource();
			handleStatementInternal(st, false, inlineBNodes, inlineBNodes);
		}
	} catch (IOException e) {
		throw new RDFHandlerException(e);
	}
}
 
Example #8
Source File: Verify.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Write SHACL validation report to a file. File extension is used to select the serialization format, TTL is used
 * as default.
 *
 * @param model      report
 * @param reportFile file name
 */
private void writeReport(Model model, String reportFile) {
	WriterConfig cfg = new WriterConfig();
	cfg.set(BasicWriterSettings.PRETTY_PRINT, true);
	cfg.set(BasicWriterSettings.INLINE_BLANK_NODES, true);

	RDFFormat format = Rio.getParserFormatForFileName(reportFile).orElse(RDFFormat.TURTLE);

	try (Writer w = Files.newBufferedWriter(Paths.get(reportFile))) {
		Rio.write(model, w, format, cfg);
	} catch (IOException ex) {
		writeError("Could not write report to " + reportFile, ex);
	}
}
 
Example #9
Source File: QueryResultsOutputUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the results of a {@link QueryResultStream} to the output stream as JSON until the
 * shutdown signal is set.
 *
 * @param out - The stream the JSON will be written to. (not null)
 * @param query - The parsed SPARQL Query whose results are being output. This
 *   object is used to figure out which bindings may appear. (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 TupleQueryResultHandlerException A problem was encountered while
 *   writing the JSON to the output stream.
 * @throws IllegalStateException The {@code resultsStream} is closed.
 * @throws RyaStreamsException Could not fetch the next set of results.
 */
public static void toBindingSetJSONFile(
        final OutputStream out,
        final TupleExpr query,
        final QueryResultStream<VisibilityBindingSet> resultsStream,
        final AtomicBoolean shutdownSignal) throws TupleQueryResultHandlerException, IllegalStateException, RyaStreamsException {
    requireNonNull(out);
    requireNonNull(query);
    requireNonNull(resultsStream);
    requireNonNull(shutdownSignal);

    // Create a writer that does not pretty print.
    final SPARQLResultsJSONWriter writer = new SPARQLResultsJSONWriter(out);
    final WriterConfig config = writer.getWriterConfig();
    config.set(BasicWriterSettings.PRETTY_PRINT, false);

    // Start the JSON and enumerate the possible binding names.
    writer.startQueryResult( Lists.newArrayList(query.getBindingNames()) );

    while(!shutdownSignal.get()) {
        for(final VisibilityBindingSet result : resultsStream.poll(1000)) {
            writer.handleSolution(result);
        }
    }

    writer.endQueryResult();
}
 
Example #10
Source File: NTriplesWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public final Collection<RioSetting<?>> getSupportedSettings() {
	Set<RioSetting<?>> result = new HashSet<>(super.getSupportedSettings());

	result.add(BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL);
	result.add(NTriplesWriterSettings.ESCAPE_UNICODE);

	return result;
}
 
Example #11
Source File: ArrangedWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testWriteRepeatedInlineBlankNode() {
	Model model = new ModelBuilder().subject(exNs + "subject")
			.add(vf.createIRI(exNs, "rel1"), bnode1)
			.add(vf.createIRI(exNs, "rel2"), bnode1)
			.add(vf.createIRI(exNs, "rel3"), bnode2)
			.subject(bnode1)
			.add(RDFS.LABEL, "the bnode1")
			.subject(bnode2)
			.add(RDFS.LABEL, "the bnode2")
			.build();

	model.setNamespace(RDFS.NS);
	model.setNamespace("ex", exNs);

	StringWriter stringWriter = new StringWriter();
	BufferedWriter writer = new BufferedWriter(stringWriter);
	WriterConfig config = new WriterConfig();
	config.set(BasicWriterSettings.INLINE_BLANK_NODES, true);
	Rio.write(model, writer, RDFFormat.TURTLE, config);

	String sep = System.lineSeparator();
	String expectedResult = "@prefix ex: <http://example.org/> ." + sep +
			"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> ." + sep +
			"@prefix xsd: <http://www.w3.org/2001/XMLSchema#> ." + sep + sep +
			"ex:subject ex:rel1 _:bnode1 ." + sep + sep +
			"_:bnode1 rdfs:label \"the bnode1\" ." + sep + sep +
			"ex:subject ex:rel2 _:bnode1;" + sep +
			"  ex:rel3 [" + sep +
			"      rdfs:label \"the bnode2\"" + sep +
			"    ] ." + sep;

	assertEquals(expectedResult, stringWriter.toString());
}
 
Example #12
Source File: ArrangedWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void startRDF() throws RDFHandlerException {
	super.startRDF();
	if (getWriterConfig().get(BasicWriterSettings.INLINE_BLANK_NODES)) {
		targetQueueSize = -1;
		repeatBlankNodes = true;
	} else if (getWriterConfig().get(BasicWriterSettings.PRETTY_PRINT)) {
		targetQueueSize = DEFAULT_QUEUE_SIZE;
	}
	delegate.startRDF();
}
 
Example #13
Source File: TurtleWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void startRDF() throws RDFHandlerException {
	super.startRDF();

	try {
		xsdStringToPlainLiteral = getWriterConfig().get(BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL);
		prettyPrint = getWriterConfig().get(BasicWriterSettings.PRETTY_PRINT);
		inlineBNodes = getWriterConfig().get(BasicWriterSettings.INLINE_BLANK_NODES);
		if (prettyPrint) {
			writer.setIndentationString("  ");
		} else {
			writer.setIndentationString("");
		}
		if (baseIRI != null && getWriterConfig().get(BasicWriterSettings.BASE_DIRECTIVE)) {
			writeBase(baseIRI.toString());
		}

		// Write namespace declarations
		for (Map.Entry<String, String> entry : namespaceTable.entrySet()) {
			String name = entry.getKey();
			String prefix = entry.getValue();

			writeNamespace(prefix, name);
		}

		if (!namespaceTable.isEmpty()) {
			writer.writeEOL();
		}
	} catch (IOException e) {
		throw new RDFHandlerException(e);
	}
}
 
Example #14
Source File: RDFWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testRDFStarConversion() throws IOException {
	Model model = new LinkedHashModel();
	model.add(vf.createStatement(triple3, uri1, triple6, uri4));
	model.add(vf.createStatement(uri1, uri2, uri3, uri5));

	ByteArrayOutputStream outputWriter = new ByteArrayOutputStream();
	RDFWriter rdfWriter = rdfWriterFactory.getWriter(outputWriter);
	setupWriterConfig(rdfWriter.getWriterConfig());
	rdfWriter.getWriterConfig().set(BasicWriterSettings.CONVERT_RDF_STAR_TO_REIFICATION, true);
	rdfWriter.startRDF();
	model.forEach(rdfWriter::handleStatement);
	rdfWriter.endRDF();

	ByteArrayInputStream inputReader = new ByteArrayInputStream(outputWriter.toByteArray());
	RDFParser rdfParser = rdfParserFactory.getParser();
	setupParserConfig(rdfParser.getParserConfig().set(BasicParserSettings.VERIFY_URI_SYNTAX, false));
	Model parsedOutput = new LinkedHashModel();
	rdfParser.setRDFHandler(new StatementCollector(parsedOutput));
	rdfParser.parse(inputReader, "");

	// 1 non-RDF* statement
	// 1 RDF* statement whose conversion yields 20 additional statements:
	// 4 for triple3
	// 4 for triple6
	// 4 for triple2 (contained in triple6)
	// 4 for triple5 (contained in triple6)
	// 4 for triple1 (contained in triple5)
	assertEquals(22, parsedOutput.size());
}
 
Example #15
Source File: RDFJSONWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void modelToRdfJsonInternal(final Model graph, final WriterConfig writerConfig,
		final JsonGenerator jg) throws IOException, JsonGenerationException {
	if (writerConfig.get(BasicWriterSettings.PRETTY_PRINT)) {
		// SES-2011: Always use \n for consistency
		Indenter indenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE;
		// By default Jackson does not pretty print, so enable this unless
		// PRETTY_PRINT setting is disabled
		DefaultPrettyPrinter pp = new DefaultPrettyPrinter().withArrayIndenter(indenter)
				.withObjectIndenter(indenter);
		jg.setPrettyPrinter(pp);
	}
	jg.writeStartObject();
	for (final Resource nextSubject : graph.subjects()) {
		jg.writeObjectFieldStart(RDFJSONWriter.resourceToString(nextSubject));
		for (final IRI nextPredicate : graph.filter(nextSubject, null, null).predicates()) {
			jg.writeArrayFieldStart(nextPredicate.stringValue());
			for (final Value nextObject : graph.filter(nextSubject, nextPredicate, null).objects()) {
				// contexts are optional, so this may return empty in some
				// scenarios depending on the interpretation of the way contexts
				// work
				final Set<Resource> contexts = graph.filter(nextSubject, nextPredicate, nextObject).contexts();

				RDFJSONWriter.writeObject(nextObject, contexts, jg);
			}
			jg.writeEndArray();
		}
		jg.writeEndObject();
	}
	jg.writeEndObject();
}
 
Example #16
Source File: AbstractSPARQLJSONWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public final Collection<RioSetting<?>> getSupportedSettings() {
	Set<RioSetting<?>> result = new HashSet<>(super.getSupportedSettings());

	result.add(BasicQueryWriterSettings.JSONP_CALLBACK);
	result.add(BasicWriterSettings.PRETTY_PRINT);
	result.add(BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL);

	return result;
}
 
Example #17
Source File: TripleStoreRDF4J.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private void write(Model model, OutputStream out) {
    try (PrintStream pout = new PrintStream(out)) {
        RDFWriter writer = new PowsyblWriter(pout);
        writer.getWriterConfig().set(BasicWriterSettings.PRETTY_PRINT, true);
        if (writeBySubject) {
            writeBySubject(model, writer);
        } else {
            Rio.write(model, writer);
        }
    }
}
 
Example #18
Source File: AbstractShaclTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void printCurrentState(SailRepository shaclRepository) {
	if (!fullLogging) {
		return;
	}

	try (SailRepositoryConnection connection = shaclRepository.getConnection()) {

		if (connection.isEmpty()) {
			System.out.println("### CURRENT REPOSITORY STATE ###");
			System.out.println("   EMPTY!");
			System.out.println("################################################\n");
		} else {

			try (Stream<Statement> stream = connection.getStatements(null, null, null, false).stream()) {
				LinkedHashModel model = stream.collect(Collectors.toCollection(LinkedHashModel::new));
				model.setNamespace("ex", "http://example.com/ns#");
				model.setNamespace(FOAF.PREFIX, FOAF.NAMESPACE);
				model.setNamespace(XMLSchema.PREFIX, XMLSchema.NAMESPACE);
				model.setNamespace(RDF.PREFIX, RDF.NAMESPACE);
				model.setNamespace(RDFS.PREFIX, RDFS.NAMESPACE);

				WriterConfig writerConfig = new WriterConfig();
				writerConfig.set(BasicWriterSettings.PRETTY_PRINT, true);
				writerConfig.set(BasicWriterSettings.INLINE_BLANK_NODES, true);
				System.out.println("### CURRENT REPOSITORY STATE ###");
				Rio.write(model, System.out, RDFFormat.TURTLE, writerConfig);
				System.out.println("################################################\n");

			}
		}

	}
}
 
Example #19
Source File: AbstractShaclTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void printResults(ValidationReport report) {
	if (!fullLogging) {
		return;
	}
	System.out.println("\n############################################");
	System.out.println("\tValidation Report\n");
	Model validationReport = report.asModel();

	WriterConfig writerConfig = new WriterConfig();
	writerConfig.set(BasicWriterSettings.PRETTY_PRINT, true);
	writerConfig.set(BasicWriterSettings.INLINE_BLANK_NODES, true);

	Rio.write(validationReport, System.out, RDFFormat.TURTLE, writerConfig);
	System.out.println("\n############################################");
}
 
Example #20
Source File: AbstractQueryResultWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void startQueryResult(List<String> bindingNames) throws TupleQueryResultHandlerException {
	// Formats without native RDF* support obey the ENCODE_RDF_STAR setting and may encode RDF* triples to IRIs
	encodeRDFStar = this instanceof TupleQueryResultWriter
			&& !((TupleQueryResultWriter) this).getTupleQueryResultFormat().supportsRDFStar()
			&& getWriterConfig().get(BasicWriterSettings.ENCODE_RDF_STAR);
}
 
Example #21
Source File: RDFJSONWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Collection<RioSetting<?>> getSupportedSettings() {
	final Set<RioSetting<?>> results = new HashSet<>(super.getSupportedSettings());

	results.add(BasicWriterSettings.PRETTY_PRINT);

	return results;
}
 
Example #22
Source File: AbstractSPARQLXMLWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void startDocument() throws QueryResultHandlerException {
	if (!documentOpen) {
		documentOpen = true;
		headerOpen = false;
		headerComplete = false;
		tupleVariablesFound = false;

		try {
			xmlWriter.setPrettyPrint(getWriterConfig().get(BasicWriterSettings.PRETTY_PRINT));

			if (getWriterConfig().get(XMLWriterSettings.INCLUDE_XML_PI)) {
				xmlWriter.startDocument();
			}

			xmlWriter.setAttribute("xmlns", NAMESPACE);

			if (getWriterConfig().get(BasicQueryWriterSettings.ADD_SESAME_QNAME)) {
				xmlWriter.setAttribute("xmlns:q", SESAMEQNAME.NAMESPACE);
			}

			for (String nextPrefix : namespaceTable.keySet()) {
				this.log.debug("Adding custom prefix for <{}> to map to <{}>", nextPrefix,
						namespaceTable.get(nextPrefix));
				xmlWriter.setAttribute("xmlns:" + namespaceTable.get(nextPrefix), nextPrefix);
			}
		} catch (IOException e) {
			throw new QueryResultHandlerException(e);
		}
	}
}
 
Example #23
Source File: AbstractSPARQLXMLWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public final Collection<RioSetting<?>> getSupportedSettings() {
	Set<RioSetting<?>> result = new HashSet<>(super.getSupportedSettings());

	result.add(BasicWriterSettings.PRETTY_PRINT);
	result.add(BasicQueryWriterSettings.ADD_SESAME_QNAME);
	result.add(BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL);

	return result;
}
 
Example #24
Source File: AbstractSPARQLJSONWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void startDocument() throws QueryResultHandlerException {
	if (!documentOpen) {
		documentOpen = true;
		headerOpen = false;
		headerComplete = false;
		tupleVariablesFound = false;
		firstTupleWritten = false;
		linksFound = false;

		if (getWriterConfig().get(BasicWriterSettings.PRETTY_PRINT)) {
			// SES-2011: Always use \n for consistency
			Indenter indenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE;
			// By default Jackson does not pretty print, so enable this unless
			// PRETTY_PRINT setting is disabled
			DefaultPrettyPrinter pp = new DefaultPrettyPrinter().withArrayIndenter(indenter)
					.withObjectIndenter(indenter);
			jg.setPrettyPrinter(pp);
		}

		try {
			if (getWriterConfig().isSet(BasicQueryWriterSettings.JSONP_CALLBACK)) {
				// SES-1019 : Write the callbackfunction name as a wrapper for
				// the results here
				String callbackName = getWriterConfig().get(BasicQueryWriterSettings.JSONP_CALLBACK);
				jg.writeRaw(callbackName);
				jg.writeRaw("(");
			}
			jg.writeStartObject();
		} catch (IOException e) {
			throw new QueryResultHandlerException(e);
		}
	}
}
 
Example #25
Source File: TriGWriterBackgroundTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void setupWriterConfig(WriterConfig config) {
	config.set(BasicWriterSettings.PRETTY_PRINT, false);
}
 
Example #26
Source File: AbstractServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Gets a {@link TupleResultBuilder} based on the Accept header, and sets the result content type to the best
 * available match for that, returning a builder that can be used to write out the results.
 *
 * @param req          the current HTTP request
 * @param resp         the current HTTP response
 * @param outputStream TODO
 * @return a builder that can be used to write out the results
 * @throws IOException
 * @throws UnsupportedQueryResultFormatException
 */
protected TupleResultBuilder getTupleResultBuilder(HttpServletRequest req, HttpServletResponse resp,
		OutputStream outputStream) throws UnsupportedQueryResultFormatException, IOException {
	String contentType = null;
	QueryResultWriter resultWriter = checkJSONP(req, outputStream);

	if (resultWriter != null) {
		// explicitly set the content type to "application/javascript"
		// to fit JSONP best practices
		contentType = APPLICATION_JAVASCRIPT;
	} else {
		// If the JSON-P check above failed, use the normal methods to
		// determine output format
		resultWriter = getResultWriter(req, resp, resp.getOutputStream());
		contentType = resultWriter.getQueryResultFormat().getDefaultMIMEType();
	}

	// HACK: In order to make XSLT stylesheet driven user interface work,
	// browser user agents must receive application/xml if they are going to
	// actually get application/sparql-results+xml
	// NOTE: This will test against both BooleanQueryResultsFormat and
	// TupleQueryResultsFormat
	if (contentType.equals(APPLICATION_SPARQL_RESULTS_XML)) {
		String uaHeader = req.getHeader(USER_AGENT);
		String acceptHeader = req.getHeader(ACCEPT);

		if (acceptHeader != null && acceptHeader.contains(APPLICATION_SPARQL_RESULTS_XML)) {
			// Do nothing, leave the contentType as
			// application/sparql-results+xml
		}
		// Switch back to application/xml for user agents who claim to be
		// Mozilla compatible
		else if (uaHeader != null && uaHeader.contains(MOZILLA)) {
			contentType = APPLICATION_XML;
		}
		// Switch back to application/xml for user agents who accept either
		// application/xml or text/html
		else if (acceptHeader != null
				&& (acceptHeader.contains(APPLICATION_XML) || acceptHeader.contains(TEXT_HTML))) {
			contentType = APPLICATION_XML;
		}
	}

	// Setup qname support for result writers who declare that they support it
	if (resultWriter.getSupportedSettings().contains(BasicQueryWriterSettings.ADD_SESAME_QNAME)) {
		resultWriter.getWriterConfig().set(BasicQueryWriterSettings.ADD_SESAME_QNAME, true);
	}

	resp.setContentType(contentType);

	// TODO: Make the following two settings configurable

	// Convert xsd:string back to plain literals where this behaviour is
	// supported
	if (resultWriter.getSupportedSettings().contains(BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL)) {
		resultWriter.getWriterConfig().set(BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL, true);
	}

	// Convert rdf:langString back to language literals where this behaviour
	// is supported
	if (resultWriter.getSupportedSettings().contains(BasicWriterSettings.RDF_LANGSTRING_TO_LANG_LITERAL)) {
		resultWriter.getWriterConfig().set(BasicWriterSettings.RDF_LANGSTRING_TO_LANG_LITERAL, true);
	}

	return new TupleResultBuilder(resultWriter, SimpleValueFactory.getInstance());
}
 
Example #27
Source File: ValidationReportTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void nestedLogicalOrSupport() throws IOException {

	SailRepository shaclSail = Utils.getInitializedShaclRepository("test-cases/or/datatype/shacl.ttl", false);

	try (SailRepositoryConnection connection = shaclSail.getConnection()) {

		connection.begin();
		connection.prepareUpdate(IOUtils.toString(ValidationReportTest.class.getClassLoader()
				.getResourceAsStream("test-cases/or/datatype/invalid/case1/query1.rq"), StandardCharsets.UTF_8))
				.execute();
		connection.commit();
		fail();

	} catch (RepositoryException e) {
		ShaclSailValidationException cause = (ShaclSailValidationException) e.getCause();
		Model actual = cause.validationReportAsModel();

		actual.setNamespace(RDF.PREFIX, RDF.NAMESPACE);
		actual.setNamespace(RDFS.PREFIX, RDFS.NAMESPACE);
		actual.setNamespace("ex", "http://example.com/ns#");

		WriterConfig writerConfig = new WriterConfig();
		writerConfig.set(BasicWriterSettings.INLINE_BLANK_NODES, true);
		writerConfig.set(BasicWriterSettings.PRETTY_PRINT, true);

		Rio.write(actual, System.out, RDFFormat.TURTLE, writerConfig);

		Model expected = Rio.parse(new StringReader(""
				+ "@prefix ex: <http://example.com/ns#> .\n"
				+ "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n"
				+ "@prefix sh: <http://www.w3.org/ns/shacl#> .\n" + "\n"
				+ "[] a sh:ValidationReport;\n" +
				"  sh:conforms false;\n" +
				"  sh:result [ a sh:ValidationResult;\n" +
				"      sh:detail [ a sh:ValidationResult;\n" +
				"          sh:detail [ a sh:ValidationResult;\n" +
				"              sh:focusNode ex:validPerson1;\n" +
				"              sh:resultPath ex:age;\n" +
				"              sh:sourceConstraintComponent sh:DatatypeConstraintComponent;\n" +
				"              sh:sourceShape ex:personShapeAgeLong\n" +
				"            ];\n" +
				"          sh:focusNode ex:validPerson1;\n" +
				"          sh:resultPath ex:age;\n" +
				"          sh:sourceConstraintComponent sh:DatatypeConstraintComponent;\n" +
				"          sh:sourceShape ex:personShapeAgeInteger\n" +
				"        ];\n" +
				"      sh:focusNode ex:validPerson1;\n" +
				"      sh:resultPath ex:age;\n" +
				"      sh:sourceConstraintComponent sh:OrConstraintComponent;\n" +
				"      sh:sourceShape ex:personShapeOr\n" +
				"    ] ." + ""), "", RDFFormat.TURTLE);

		assertTrue(Models.isomorphic(expected, actual));

	}
}
 
Example #28
Source File: NTriplesWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void startRDF() throws RDFHandlerException {
	super.startRDF();
	xsdStringToPlainLiteral = getWriterConfig().get(BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL);
	escapeUnicode = getWriterConfig().get(NTriplesWriterSettings.ESCAPE_UNICODE);
}
 
Example #29
Source File: JSONLDWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void endRDF() throws RDFHandlerException {
	checkWritingStarted();
	final JSONLDInternalRDFParser serialiser = new JSONLDInternalRDFParser();
	try {
		Object output = JsonLdProcessor.fromRDF(model, serialiser);

		final JSONLDMode mode = getWriterConfig().get(JSONLDSettings.JSONLD_MODE);

		final JsonLdOptions opts = new JsonLdOptions();
		// opts.addBlankNodeIDs =
		// getWriterConfig().get(BasicParserSettings.PRESERVE_BNODE_IDS);
		WriterConfig writerConfig = getWriterConfig();
		opts.setCompactArrays(writerConfig.get(JSONLDSettings.COMPACT_ARRAYS));
		opts.setProduceGeneralizedRdf(writerConfig.get(JSONLDSettings.PRODUCE_GENERALIZED_RDF));
		opts.setUseRdfType(writerConfig.get(JSONLDSettings.USE_RDF_TYPE));
		opts.setUseNativeTypes(writerConfig.get(JSONLDSettings.USE_NATIVE_TYPES));
		// opts.optimize = getWriterConfig().get(JSONLDSettings.OPTIMIZE);

		if (writerConfig.get(JSONLDSettings.HIERARCHICAL_VIEW)) {
			output = JSONLDHierarchicalProcessor.fromJsonLdObject(output);
		}

		if (baseURI != null && writerConfig.get(BasicWriterSettings.BASE_DIRECTIVE)) {
			opts.setBase(baseURI);
		}
		if (mode == JSONLDMode.EXPAND) {
			output = JsonLdProcessor.expand(output, opts);
		}
		// TODO: Implement inframe in JSONLDSettings
		final Object inframe = null;
		if (mode == JSONLDMode.FLATTEN) {
			output = JsonLdProcessor.flatten(output, inframe, opts);
		}
		if (mode == JSONLDMode.COMPACT) {
			final Map<String, Object> ctx = new LinkedHashMap<>();
			addPrefixes(ctx, model.getNamespaces());
			final Map<String, Object> localCtx = new HashMap<>();
			localCtx.put(JsonLdConsts.CONTEXT, ctx);

			output = JsonLdProcessor.compact(output, localCtx, opts);
		}
		if (writerConfig.get(BasicWriterSettings.PRETTY_PRINT)) {
			JsonUtils.writePrettyPrint(writer, output);
		} else {
			JsonUtils.write(writer, output);
		}

	} catch (JsonLdError | IOException e) {
		throw new RDFHandlerException("Could not render JSONLD", e);
	}
}
 
Example #30
Source File: RDFXMLWriterBackgroundTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void setupWriterConfig(WriterConfig config) {
	config.set(BasicWriterSettings.PRETTY_PRINT, false);
}