org.eclipse.rdf4j.rio.Rio Java Examples

The following examples show how to use org.eclipse.rdf4j.rio.Rio. 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 Project: inception   Author: inception-project   File: SPARQLQueryBuilderGenericTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("resource")
private void importData(Repository aRepo, String aUrl) throws IOException
{
    try (InputStream aIS = openAsStream(aUrl)) {
        InputStream is = new BufferedInputStream(aIS);
        try {
            // Stream is expected to be closed by caller of importData
            is = new CompressorStreamFactory().createCompressorInputStream(is);
        }
        catch (CompressorException e) {
            // Probably not compressed then or unknown format - just try as is.
        }

        // Detect the file format
        RDFFormat format = Rio.getParserFormatForFileName(aUrl).orElse(RDFFormat.RDFXML);
        
        try (RepositoryConnection conn = aRepo.getConnection()) {
            // If the RDF file contains relative URLs, then they probably start with a hash.
            // To avoid having two hashes here, we drop the hash from the base prefix configured
            // by the user.
            String prefix = StringUtils.removeEnd(kb.getBasePrefix(), "#");
            conn.add(is, prefix, format);
        }
    }
}
 
Example #2
Source Project: rdf4j   Author: eclipse   File: SPARQLServiceEvaluationTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read the expected graph query result from the specified resource
 *
 * @param resultFile
 * @return
 * @throws Exception
 */
private Set<Statement> readExpectedGraphQueryResult(String resultFile) throws Exception {
	RDFFormat rdfFormat = Rio.getParserFormatForFileName(resultFile).orElseThrow(Rio.unsupportedFormat(resultFile));

	RDFParser parser = Rio.createParser(rdfFormat);
	parser.setDatatypeHandling(DatatypeHandling.IGNORE);
	parser.setPreserveBNodeIDs(true);
	parser.setValueFactory(SimpleValueFactory.getInstance());

	Set<Statement> result = new LinkedHashSet<>();
	parser.setRDFHandler(new StatementCollector(result));

	InputStream in = SPARQLServiceEvaluationTest.class.getResourceAsStream(resultFile);
	try {
		parser.parse(in, null); // TODO check
	} finally {
		in.close();
	}

	return result;
}
 
Example #3
Source Project: rya   Author: apache   File: QueryResultsOutputUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #4
Source Project: timbuctoo   Author: HuygensING   File: DescriptionView.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void init(Result<Description> descriptionResult, Interpreter interpreter) {
  if (descriptionResult.getContent().isPresent()) {
    Description description = descriptionResult.getContent().get();
    String mimeType = description.getDescribedByLink().getType().orElse(null);
    Optional<RDFFormat> maybeFormat = Rio.getParserFormatForMIMEType(mimeType);
    if (!maybeFormat.isPresent()) {
      String filename = descriptionResult.getUri().toString();
      maybeFormat = Rio.getParserFormatForFileName(filename);
    }
    if (maybeFormat.isPresent()) {
      createDescriptionNode(description, maybeFormat.get(), interpreter);
    } else {
      rawContent = description.getRawContent();
    }
  }
}
 
Example #5
Source Project: rdf4j   Author: eclipse   File: SPARQLQueryTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected final Set<Statement> readExpectedGraphQueryResult() throws Exception {
	RDFFormat rdfFormat = Rio.getParserFormatForFileName(resultFileURL)
			.orElseThrow(Rio.unsupportedFormat(resultFileURL));

	RDFParser parser = Rio.createParser(rdfFormat);
	parser.setDatatypeHandling(DatatypeHandling.IGNORE);
	parser.setPreserveBNodeIDs(true);
	parser.setValueFactory(dataRep.getValueFactory());

	Set<Statement> result = new LinkedHashSet<>();
	parser.setRDFHandler(new StatementCollector(result));

	InputStream in = new URL(resultFileURL).openStream();
	try {
		parser.parse(in, resultFileURL);
	} finally {
		in.close();
	}

	return result;
}
 
Example #6
Source Project: semagrow   Author: semagrow   File: RDFQueryLogParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void parseQueryLog(InputStream in) throws IOException, QueryLogException {
    if (handler == null)
        throw new QueryLogException("No query log handler defined");

    try {
        model = Rio.parse(in, "", RDFFormat.NTRIPLES);
    } catch (Exception e) {
        throw new QueryLogException(e);
    }

    Model queryRecords = model.filter(null, RDF.TYPE, QFR.QUERYRECORD);

    for (Resource qr : queryRecords.subjects()) {
        QueryLogRecord record = parseQueryRecord(qr,model);
        handler.handleQueryRecord(record);
    }
}
 
Example #7
Source Project: rdf4j   Author: eclipse   File: AddServlet.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void add(InputStream stream, String baseURI, String contentType, String contentFileName,
		Resource... context) throws BadRequestException, RepositoryException, IOException {
	if (contentType == null) {
		throw new BadRequestException("No Content-Type provided");
	}

	RDFFormat format = null;
	if ("autodetect".equals(contentType)) {
		format = Rio.getParserFormatForFileName(contentFileName)
				.orElseThrow(() -> new BadRequestException(
						"Could not automatically determine Content-Type for content: " + contentFileName));
	} else {
		format = Rio.getParserFormatForMIMEType(contentType)
				.orElseThrow(() -> new BadRequestException("Unknown Content-Type: " + contentType));
	}

	try (RepositoryConnection con = repository.getConnection()) {
		con.add(stream, baseURI, format, context);
	} catch (RDFParseException | IllegalArgumentException exc) {
		throw new BadRequestException(exc.getMessage(), exc);
	}
}
 
Example #8
Source Project: rdf4j   Author: eclipse   File: AddServlet.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void add(URL url, String baseURI, String contentType, Resource... context)
		throws BadRequestException, RepositoryException, IOException {
	if (contentType == null) {
		throw new BadRequestException("No Content-Type provided");
	}

	RDFFormat format = null;
	if ("autodetect".equals(contentType)) {
		format = Rio.getParserFormatForFileName(url.getFile())
				.orElseThrow(() -> new BadRequestException(
						"Could not automatically determine Content-Type for content: " + url.getFile()));
	} else {
		format = Rio.getParserFormatForMIMEType(contentType)
				.orElseThrow(() -> new BadRequestException("Unknown Content-Type: " + contentType));
	}

	try {
		try (RepositoryConnection con = repository.getConnection()) {
			con.add(url, baseURI, format, context);
		}
	} catch (RDFParseException | MalformedURLException | IllegalArgumentException exc) {
		throw new BadRequestException(exc.getMessage(), exc);
	}
}
 
Example #9
Source Project: semagrow   Author: semagrow   File: SemagrowRepositoryResolver.java    License: Apache License 2.0 6 votes vote down vote up
private Model parseConfig(File file) throws SailConfigException, IOException
{
    RDFFormat format = Rio.getParserFormatForFileName(file.getAbsolutePath()).get();
    if (format==null)
        throw new SailConfigException("Unsupported file format: " + file.getAbsolutePath());
    RDFParser parser = Rio.createParser(format);
    Model model = new LinkedHashModel();
    parser.setRDFHandler(new StatementCollector(model));
    InputStream stream = new FileInputStream(file);

    try {
        parser.parse(stream, file.getAbsolutePath());
    } catch (Exception e) {
        throw new SailConfigException("Error parsing file!");
    }

    stream.close();
    return model;
}
 
Example #10
Source Project: rdf4j   Author: eclipse   File: SpinRendererTest.java    License: 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 #11
Source Project: rdf4j   Author: eclipse   File: PropertyShape.java    License: 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 #12
Source Project: mobi   Author: inovexcorp   File: ImportIT.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Before
public synchronized void setup() throws Exception {
    if (setupComplete) return;

    String dataFile = "testData.trig";
    Files.copy(getBundleEntry(thisBundleContext, "/" + dataFile), Paths.get(dataFile));

    waitForService("(&(objectClass=com.mobi.etl.api.delimited.RDFImportService))", 10000L);
    waitForService("(&(objectClass=com.mobi.ontology.orm.impl.ThingFactory))", 10000L);
    waitForService("(&(objectClass=com.mobi.rdf.orm.conversion.ValueConverterRegistry))", 10000L);

    data = Values.mobiModel(Rio.parse(new FileInputStream(new File(dataFile)), "", RDFFormat.TRIG));

    manager = getOsgiService(DatasetManager.class);
    userFactory = getOsgiService(UserFactory.class);
    vf = getOsgiService(ValueFactory.class);
    DatasetRecordConfig config = new DatasetRecordConfig.DatasetRecordBuilder("Test Dataset",
            Collections.singleton(userFactory.createNew(vf.createIRI("http://mobi.com/users/admin"))), "system").build();
    record = manager.createDataset(config);

    executeCommand(String.format("mobi:import -d=%s %s", record.getResource().stringValue(), dataFile));

    setupComplete = true;
}
 
Example #13
Source Project: rdf4j   Author: eclipse   File: Utils.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void loadShapeData(ShaclSail sail, String resourceName) throws IOException {
	sail.disableValidation();
	Model shapes;
	try (InputStream shapesData = Utils.class.getClassLoader().getResourceAsStream(resourceName)) {
		shapes = Rio.parse(shapesData, "", RDFFormat.TURTLE, RDF4J.SHACL_SHAPE_GRAPH);
	}
	try (SailConnection conn = sail.getConnection()) {
		conn.begin(IsolationLevels.NONE);
		for (Statement st : shapes) {
			conn.addStatement(st.getSubject(), st.getPredicate(), st.getObject(), RDF4J.SHACL_SHAPE_GRAPH);
		}
		conn.commit();
	}
	sail.enableValidation();

}
 
Example #14
Source Project: rdf4j   Author: eclipse   File: RDFXMLParserCustomTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testParseCollection() throws Exception {
	// Example from:
	// http://www.w3.org/TR/rdf-syntax-grammar/#section-Syntax-parsetype-Collection
	StringBuilder string = new StringBuilder();
	string.append("<?xml version=\"1.0\"?>\n");
	string.append("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" ");
	string.append(" xmlns:ex=\"http://example.org/stuff/1.0/\"> \n");
	string.append("  <rdf:Description rdf:about=\"http://example.org/basket\"> \n");
	string.append("    <ex:hasFruit rdf:parseType=\"Collection\">\n");
	string.append("      <rdf:Description rdf:about=\"http://example.org/banana\"/>\n");
	string.append("      <rdf:Description rdf:about=\"http://example.org/apple\"/>\n");
	string.append("      <rdf:Description rdf:about=\"http://example.org/pear\"/>\n");
	string.append("    </ex:hasFruit>\n");
	string.append("  </rdf:Description>\n");
	string.append("</rdf:RDF>");

	Model parse = Rio.parse(new StringReader(string.toString()), "", RDFFormat.RDFXML);
	Rio.write(parse, System.out, RDFFormat.NTRIPLES);
	assertEquals(7, parse.size());
	assertEquals(3, parse.filter(null, RDF.FIRST, null).size());
	assertEquals(3, parse.filter(null, RDF.REST, null).size());
	assertEquals(1, parse.filter(null, null, RDF.NIL).size());
}
 
Example #15
Source Project: rdf4j   Author: eclipse   File: RDFXMLParserCustomTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test with Secure processing setting off.
 * <p>
 * IMPORTANT: Only turn this on to verify it is still working, as there is no way to safely perform this test.
 * <p>
 * WARNING: This test will cause an OutOfMemoryException when it eventually fails, as it will eventually fail.
 *
 * @throws Exception
 */
@Ignore
@Test(timeout = 10000)
public void testEntityExpansionNoSecureProcessing() throws Exception {
	final Model aGraph = new LinkedHashModel();
	ParseErrorCollector errorCollector = new ParseErrorCollector();
	RDFParser aParser = Rio.createParser(RDFFormat.RDFXML)
			.setRDFHandler(new StatementCollector(aGraph))
			.set(XMLParserSettings.SECURE_PROCESSING, false)
			.setParseErrorListener(errorCollector);

	try {
		// IMPORTANT: This will not use the entity limit
		aParser.parse(
				this.getClass().getResourceAsStream("/testcases/rdfxml/openrdf/bad-entity-expansion-limit.rdf"),
				"http://example.org");
		fail("Parser did not throw an exception");
	} catch (RDFParseException e) {
		// assertTrue(e.getMessage().contains(
		// "The parser has encountered more than \"64,000\" entity expansions in this document; this is the limit
		// imposed by the"));
	}
	assertEquals(0, errorCollector.getWarnings().size());
	assertEquals(0, errorCollector.getErrors().size());
	assertEquals(1, errorCollector.getFatalErrors().size());
}
 
Example #16
Source Project: inception   Author: inception-project   File: KnowledgeBaseServiceImplQualifierIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@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 Project: mobi   Author: inovexcorp   File: RecordExportServiceImpl.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void export(RecordExportConfig config) throws IOException {
    BatchExporter writer = new BatchExporter(transformer, new BufferedGroupingRDFHandler(
            Rio.createWriter(config.getFormat(), config.getOutput())));
    writer.setLogger(LOG);
    writer.setPrintToSystem(true);

    com.mobi.rdf.api.Resource localCatalog = configProvider.getLocalCatalogIRI();

    Set<com.mobi.rdf.api.Resource> records;
    if (config.getRecords() == null) {
        records = catalogManager.getRecordIds(localCatalog);
    } else {
        records = config.getRecords().stream()
                .map(recordString -> vf.createIRI(recordString))
                .collect(Collectors.toSet());
    }

    writer.startRDF();
    records.forEach(resource -> {
        // Write Record
        Record record = catalogManager.getRecord(localCatalog, resource, recordFactory)
                .orElseThrow(() -> new IllegalStateException("Could not retrieve record " + resource));
        record.getModel().forEach(writer::handleStatement);

        // Write Versioned Data
        IRI typeIRI = vf.createIRI(com.mobi.ontologies.rdfs.Resource.type_IRI);
        IRI versionedRDFRecordType = vf.createIRI(VersionedRDFRecord.TYPE);
        if (record.getProperties(typeIRI).contains(versionedRDFRecordType)) {
            exportVersionedRDFData(resource, writer);
        }
    });
    writer.endRDF();
}
 
Example #18
Source Project: rdf4j   Author: eclipse   File: JSONLDParserCustomTest.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
	parser = Rio.createParser(RDFFormat.JSONLD);
	errors = new ParseErrorCollector();
	model = new LinkedHashModel();
	parser.setParseErrorListener(errors);
	parser.setRDFHandler(new ContextStatementCollector(model, F));
}
 
Example #19
Source Project: rdf4j   Author: eclipse   File: CustomTurtleParserTest.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSES2165LiteralSpaceDatatypeNewline() throws Exception {
	Model model = Rio.parse(new StringReader("<urn:a> <urn:b> \"testliteral\"^^\n<urn:datatype> ."), "",
			RDFFormat.TURTLE);

	assertEquals(1, model.size());
	assertTrue(model.contains(vf.createIRI("urn:a"), vf.createIRI("urn:b"),
			vf.createLiteral("testliteral", vf.createIRI("urn:datatype"))));
}
 
Example #20
Source Project: rdf4j   Author: eclipse   File: SPARQLQueryTest.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void upload(IRI graphURI, Resource context) throws Exception {
	RepositoryConnection con = dataRep.getConnection();

	try {
		con.begin();
		RDFFormat rdfFormat = Rio.getParserFormatForFileName(graphURI.toString()).orElse(RDFFormat.TURTLE);
		RDFParser rdfParser = Rio.createParser(rdfFormat, dataRep.getValueFactory());
		rdfParser.setVerifyData(false);
		rdfParser.setDatatypeHandling(DatatypeHandling.IGNORE);
		// rdfParser.setPreserveBNodeIDs(true);

		RDFInserter rdfInserter = new RDFInserter(con);
		rdfInserter.enforceContext(context);
		rdfParser.setRDFHandler(rdfInserter);

		URL graphURL = new URL(graphURI.toString());
		InputStream in = graphURL.openStream();
		try {
			rdfParser.parse(in, graphURI.toString());
		} finally {
			in.close();
		}

		con.commit();
	} catch (Exception e) {
		if (con.isActive()) {
			con.rollback();
		}
		throw e;
	} finally {
		con.close();
	}
}
 
Example #21
Source Project: rdf4j   Author: eclipse   File: ArrangedWriterTest.java    License: 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 #22
Source Project: rdf4j   Author: eclipse   File: Transaction.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Adds RDF data from an {@link InputStream} to the transaction.
 *
 * @param inputStream
 * @param baseURI
 * @param format
 * @param contexts
 * @throws ExecutionException
 * @throws InterruptedException
 */
void add(InputStream inputStream, String baseURI, RDFFormat format, boolean preserveBNodes, Resource... contexts)
		throws InterruptedException, ExecutionException {
	Future<Boolean> result = submit(() -> {
		logger.debug("executing add operation");
		try {
			if (preserveBNodes) {
				// create a reconfigured parser + inserter instead of
				// relying on standard
				// repositoryconn add method.
				RDFParser parser = Rio.createParser(format);
				parser.getParserConfig().set(BasicParserSettings.PRESERVE_BNODE_IDS, true);
				RDFInserter inserter = new RDFInserter(txnConnection);
				inserter.setPreserveBNodeIDs(true);
				if (contexts.length > 0) {
					inserter.enforceContext(contexts);
				}
				parser.setRDFHandler(inserter);
				parser.parse(inputStream, baseURI);
			} else {
				txnConnection.add(inputStream, baseURI, format, contexts);
			}
			return true;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	});
	getFromFuture(result);
}
 
Example #23
Source Project: mobi   Author: inovexcorp   File: RestUtils.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Converts a {@link Model} into a string containing RDF in the specified RDFFormat.
 *
 * @param model       A {@link Model} of RDF to convert.
 * @param format      The RDFFormat the RDF should be serialized into.
 * @param transformer The SesameTransformer for model conversions.
 * @return A String of the serialized RDF from the Model.
 */
public static String modelToString(Model model, RDFFormat format, SesameTransformer transformer) {
    long start = System.currentTimeMillis();
    try {
        StringWriter sw = new StringWriter();
        Rio.write(new StatementIterable(model, transformer), sw, format);
        return sw.toString();
    } finally {
        LOG.trace("modelToString took {}ms", System.currentTimeMillis() - start);
    }
}
 
Example #24
Source Project: rdf4j   Author: eclipse   File: CustomTurtleParserTest.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSES2013BlankNodeSemiColonBNodeA() throws Exception {
	Model model = Rio.parse(new StringReader("<urn:a> a _:c2;a <urn:b> ."), "", RDFFormat.TURTLE);

	assertEquals(2, model.size());
	assertTrue(model.contains(vf.createURI("urn:a"), RDF.TYPE, vf.createURI("urn:b")));
}
 
Example #25
Source Project: mobi   Author: inovexcorp   File: SimpleOntology.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private OutputStream getOntologyOutputStream(boolean skolemize, boolean prettyPrint, RDFFormat format, OutputStream outputStream) {
    long startTime = getStartTime();
    try (DatasetConnection conn = getDatasetConnection()) {
        RepositoryResult<Statement> statements = conn.getStatements(null, null, null,
                conn.getSystemDefaultNamedGraph());

        RDFHandler rdfWriter;
        if (prettyPrint) {
            rdfWriter = new BufferedGroupingRDFHandler(Rio.createWriter(format, outputStream));
        } else {
            rdfWriter = Rio.createWriter(format, outputStream);
        }

        RemoveContextHandler removeContextSH = new RemoveContextHandler(vf);
        if (skolemize) {
            SkolemizeHandler skolemizeSH = new SkolemizeHandler(bNodeService);
            com.mobi.persistence.utils.rio.Rio.write(statements, rdfWriter, transformer, skolemizeSH, removeContextSH);
        } else {
            com.mobi.persistence.utils.rio.Rio.write(statements, rdfWriter, transformer, removeContextSH);
        }

        undoApplyDifferenceIfPresent(conn);
    } catch (RDFHandlerException e) {
        throw new MobiOntologyException("Error while writing Ontology.");
    }
    logTrace("getOntologyOutputStream(" + format.getName() + ", outputStream)", startTime);
    return outputStream;
}
 
Example #26
Source Project: mobi   Author: inovexcorp   File: Query.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private void executeGraphQuery(Repository repository, String queryString) {
    try (RepositoryConnection conn = repository.getConnection()) {
        GraphQuery query = conn.prepareGraphQuery(queryString);
        GraphQueryResult result = query.evaluate();

        OutputStream out = System.out;
        RDFFormat format = getFormat();

        RDFHandler rdfWriter = new BufferedGroupingRDFHandler(Rio.createWriter(format, out));
        Rio.write(new StatementIterable(result, transformer), rdfWriter);
    }
}
 
Example #27
Source Project: rdf4j   Author: eclipse   File: SparqlTest.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public final void testOutputFileConstructWorkdir() throws IOException {
	setWorkingDir(cmd);

	File f = LOCATION.newFile("out.ttl");

	cmd.executeQuery("sparql OUTFILE=\"out.ttl\" construct { ?s ?p ?o } where { ?s ?p ?o }", "sparql");
	verify(mockConsoleIO, never()).writeError(anyString());

	assertTrue("File does not exist", f.exists());
	assertTrue("Empty file", f.length() > 0);

	Model m = Rio.parse(new FileReader(f), "", RDFFormat.TURTLE);
	assertTrue("Empty model", m.size() > 0);
}
 
Example #28
Source Project: mobi   Author: inovexcorp   File: SimpleOntology.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public OutputStream asTurtle(OutputStream outputStream) throws MobiOntologyException {
    try {
        RDFHandler rdfWriter = new BufferedGroupingRDFHandler(Rio.createWriter(RDFFormat.TURTLE, outputStream));
        org.eclipse.rdf4j.model.Model sesameModel = asSesameModel();
        Rio.write(sesameModel, rdfWriter);
    } catch (RDFHandlerException e) {
        throw new MobiOntologyException("Error while writing Ontology.");
    }
    return outputStream;
}
 
Example #29
Source Project: rya   Author: apache   File: RdfCloudTripleStoreConnectionTest.java    License: Apache License 2.0 5 votes vote down vote up
private static String getSparqlUpdate() throws Exception {
    InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("namedgraphs.trig");
    assertNotNull(stream);

    Model m = Rio.parse(stream, "", RDFFormat.TRIG);

    StringBuffer updateStr = new StringBuffer();
    updateStr.append("INSERT DATA {\n");
    for (Statement s : m){
        if (s.getContext() != null) {
            updateStr.append("graph ");
            updateStr.append(escape(s.getContext()));
            updateStr.append("{ ");
        }

        updateStr.append(escape(s.getSubject()));
        updateStr.append(" ");
        updateStr.append(escape(s.getPredicate()));
        updateStr.append(" ");
        updateStr.append(escape(s.getObject()));
        if (s.getContext() != null){
            updateStr.append("}");
        }
        updateStr.append(" . \n");
    }
    updateStr.append("}");
    return updateStr.toString();
}
 
Example #30
Source Project: rdf4j   Author: eclipse   File: QueryServlet.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void setContentType(final WorkbenchRequest req, final HttpServletResponse resp) {
	String result = "application/xml";
	String ext = "xml";
	if (req.isParameterPresent(ACCEPT)) {
		final String accept = req.getParameter(ACCEPT);
		final Optional<RDFFormat> format = Rio.getWriterFormatForMIMEType(accept);
		if (format.isPresent()) {
			result = format.get().getDefaultMIMEType();
			ext = format.get().getDefaultFileExtension();
		} else {
			final Optional<QueryResultFormat> tupleFormat = QueryResultIO.getWriterFormatForMIMEType(accept);

			if (tupleFormat.isPresent()) {
				result = tupleFormat.get().getDefaultMIMEType();
				ext = tupleFormat.get().getDefaultFileExtension();
			} else {
				final Optional<QueryResultFormat> booleanFormat = QueryResultIO
						.getBooleanWriterFormatForMIMEType(accept);

				if (booleanFormat.isPresent()) {
					result = booleanFormat.get().getDefaultMIMEType();
					ext = booleanFormat.get().getDefaultFileExtension();
				}
			}
		}
	}

	resp.setContentType(result);
	if (!result.equals("application/xml")) {
		final String attachment = "attachment; filename=query." + ext;
		resp.setHeader("Content-disposition", attachment);
	}
}