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 File: RDFQueryLogParser.java    From semagrow with 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 #2
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 #3
Source File: ImportIT.java    From mobi with 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 #4
Source File: SPARQLQueryBuilderGenericTest.java    From inception with 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 #5
Source File: SPARQLServiceEvaluationTest.java    From rdf4j with 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 #6
Source File: QueryResultsOutputUtil.java    From rya with 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 #7
Source File: SPARQLQueryTest.java    From rdf4j with 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 #8
Source File: DescriptionView.java    From timbuctoo with 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 #9
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 #10
Source File: SemagrowRepositoryResolver.java    From semagrow with 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 #11
Source File: Utils.java    From rdf4j with 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 #12
Source File: RDFXMLParserCustomTest.java    From rdf4j with 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 #13
Source File: RDFXMLParserCustomTest.java    From rdf4j with 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 #14
Source File: AddServlet.java    From rdf4j with 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 #15
Source File: AddServlet.java    From rdf4j with 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 #16
Source File: SpinSailWithoutRDFSInferencerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void assertStatements(String ttl)
		throws RDFParseException, RDFHandlerException, IOException, RepositoryException {
	StatementCollector expected = new StatementCollector();
	RDFParser parser = Rio.createParser(RDFFormat.TURTLE);
	parser.setRDFHandler(expected);
	URL url = getClass().getResource(BASE_DIR + ttl);
	try (InputStream rdfStream = url.openStream()) {
		parser.parse(rdfStream, url.toString());
	}

	for (Statement stmt : expected.getStatements()) {
		assertTrue("Expected statement: " + stmt, conn.hasStatement(stmt, true));
	}
}
 
Example #17
Source File: ExportBase.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
protected RDFFormat getFormat() throws IOException {
    if (formatParam != null && formats.containsKey(formatParam)) {
        return formats.get(formatParam);
    } else if (filepathParam != null) {
        return Rio.getParserFormatForFileName(filepathParam).orElse(RDFFormat.TRIG);
    } else {
        return RDFFormat.TRIG;
    }
}
 
Example #18
Source File: CustomTurtleParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSES2086PeriodEndingLocalNamesFailure1() throws Exception {
	try {
		Rio.parse(
				new StringReader(
						"@prefix : <http://example.org> .\n <urn:a> <http://www.example.net/test> :test. ."),
				"", RDFFormat.TURTLE);
		fail("Did not receive an exception");
	} catch (RDFParseException e) {
		System.out.println(e.getMessage());
		assertTrue(e.getMessage().contains("Object for statement missing"));
	}
}
 
Example #19
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with 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 #20
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 #21
Source File: GenerateFullAxioms.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	MemoryStore baseSail = new MemoryStore();
	DedupingInferencer deduper = new DedupingInferencer(baseSail);
	SchemaCachingRDFSInferencer rdfsInferencer = new SchemaCachingRDFSInferencer(deduper);
	SpinSail spinSail = new SpinSail(rdfsInferencer);
	Repository repo = new SailRepository(spinSail);
	repo.initialize();
	try (FileWriter writer = new FileWriter("spin-full.ttl")) {
		try (RepositoryConnection conn = repo.getConnection()) {
			conn.exportStatements(null, null, null, true, Rio.createWriter(RDFFormat.TURTLE, writer));
		}
	}
	repo.shutDown();
}
 
Example #22
Source File: CustomTurtleParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSES2086PeriodEndingLocalNamesFailure4() throws Exception {
	try {
		Rio.parse(new StringReader(
				"@prefix ns: <http://example.org/data/> . ns:1 a ns:uriWithDot. ; ns:title \"An example entity with uriWithDot as an object\" . "),
				"", RDFFormat.TURTLE);
		fail("Did not receive an exception");
	} catch (RDFParseException e) {
		System.out.println(e.getMessage());
		assertTrue(e.getMessage().contains("Expected an RDF value here, found ';'"));
	}
}
 
Example #23
Source File: RDFJSONParserCustomTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
	parser = Rio.createParser(RDFFormat.RDFJSON);
	errors = new ParseErrorCollector();
	model = new LinkedHashModel();
	parser.setParseErrorListener(errors);
	parser.setRDFHandler(new ContextStatementCollector(model, SimpleValueFactory.getInstance()));
}
 
Example #24
Source File: TriGParserCustomTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGraphLocalNameIntegerNotGraph() throws Exception {
	Model model = Rio.parse(
			new StringReader("@prefix ex: <urn:> .\n ex:1 { [] <http://www.example.net/test> \"Foo\" }"), "",
			RDFFormat.TRIG);

	assertEquals(1, model.size());
	assertNotNull(model.contexts().iterator().next());
	assertEquals("urn:1", model.contexts().iterator().next().stringValue());
	assertTrue(model.subjects().iterator().next() instanceof BNode);
	assertEquals("http://www.example.net/test", model.predicates().iterator().next().stringValue());
	assertEquals("Foo", model.objects().iterator().next().stringValue());
}
 
Example #25
Source File: RDFXMLParserCustomTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test with unrelated ParserConfig settings
 *
 * @throws Exception
 */
@Test
public void testEntityExpansionUnrelatedSettings() throws Exception {
	final Model aGraph = new LinkedHashModel();
	ParseErrorCollector errorCollector = new ParseErrorCollector();
	ParserConfig config = new ParserConfig();
	RDFParser aParser = Rio.createParser(RDFFormat.RDFXML)
			.setRDFHandler(new StatementCollector(aGraph))
			.setParserConfig(config)
			.setParseErrorListener(errorCollector);

	try {
		// this should trigger a SAX parse exception that will blow up at the
		// 64k entity limit rather than OOMing
		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 #26
Source File: VersionedRDFRecordServiceTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void exportSpecificBranch() throws Exception {
    Branch doNotWriteBranch = branchFactory.createNew(VALUE_FACTORY.createIRI("http://mobi.com/test/branches#branch2"));
    doNotWriteBranch.setHead(headCommit);
    doNotWriteBranch.setProperty(VALUE_FACTORY.createLiteral("Test Record"), VALUE_FACTORY.createIRI(_Thing.title_IRI));
    testRecord.addBranch(doNotWriteBranch);

    Set<Resource> branchesToExport = new HashSet<>();
    branchesToExport.add(branchIRI);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    BatchExporter exporter =  new BatchExporter(transformer, new BufferedGroupingRDFHandler(Rio.createWriter(RDFFormat.JSONLD, os)));
    RecordOperationConfig config = new OperationConfig();

    config.set(RecordExportSettings.BATCH_EXPORTER, exporter);
    config.set(VersionedRDFRecordExportSettings.BRANCHES_TO_EXPORT, branchesToExport);

    assertFalse(exporter.isActive());
    exporter.startRDF();
    assertTrue(exporter.isActive());
    recordService.export(testIRI, config, connection);
    exporter.endRDF();
    assertFalse(exporter.isActive());

    Model outputModel = Values.mobiModel(Rio.parse((IOUtils.toInputStream(os.toString())), "", RDFFormat.JSONLD));
    testRecord.removeBranch(doNotWriteBranch);
    assertTrue(outputModel.containsAll(testRecord.getModel()));
    assertTrue(outputModel.containsAll(branch.getModel()));
    assertFalse(outputModel.containsAll(doNotWriteBranch.getModel()));
    assertTrue(outputModel.containsAll(difference.getDeletions()));

    verify(utilsService).optObject(eq(testIRI), any(OrmFactory.class), eq(connection));
    verify(utilsService).getBranch(eq(testRecord), eq(branchIRI), any(OrmFactory.class), eq(connection));
    verify(utilsService).getHeadCommitIRI(eq(branch));
    verify(utilsService).getCommitChain(eq(commitIRI), eq(false), any(RepositoryConnection.class));
    verify(utilsService).getExpectedObject(eq(commitIRI), any(OrmFactory.class), eq(connection));
    verify(utilsService).getRevisionChanges(eq(commitIRI), eq(connection));
}
 
Example #27
Source File: QueryServlet.java    From rdf4j with 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);
	}
}
 
Example #28
Source File: QueryResultIO.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 #29
Source File: EtlIT.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void outputContentIsCorrect() throws Exception {
    org.eclipse.rdf4j.model.Model expected = Rio.parse(getBundleEntry(thisBundleContext, "/testOutput.ttl"), "", RDFFormat.TURTLE);
    org.eclipse.rdf4j.model.Model actual = Rio.parse(new FileInputStream(outputFile), "", RDFFormat.TURTLE);

    // TODO: I get around the UUID issue by setting the localname to values in the cells. We need to support IRI
    // isomorphism the same way bnode isomorphism is handled.
    assertTrue(Models.isomorphic(expected, actual));
}
 
Example #30
Source File: CustomTurtleParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSES1988BlankNodePeriodURI() throws Exception {
	Model model = Rio.parse(new StringReader("<urn:a> <urn:b> _:blank.<urn:c> <urn:d> <urn:e>."), "",
			RDFFormat.TURTLE);

	assertEquals(2, model.size());
}