org.eclipse.rdf4j.rio.RDFFormat Java Examples

The following examples show how to use org.eclipse.rdf4j.rio.RDFFormat. 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: Transaction.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @param contentType
 * @param inputStream
 * @param baseURI
 * @throws ExecutionException
 * @throws InterruptedException
 */
void delete(RDFFormat contentType, InputStream inputStream, String baseURI)
		throws InterruptedException, ExecutionException {
	Future<Boolean> result = submit(() -> {
		logger.debug("executing delete operation");
		RDFParser parser = Rio.createParser(contentType, txnConnection.getValueFactory());

		parser.setRDFHandler(new WildcardRDFRemover(txnConnection));
		parser.getParserConfig().set(BasicParserSettings.PRESERVE_BNODE_IDS, true);
		try {
			parser.parse(inputStream, baseURI);
			return true;
		} catch (IOException e) {
			logger.error("error during txn delete operation", e);
			throw new RuntimeException(e);
		}
	});
	getFromFuture(result);
}
 
Example #2
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 #3
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 #4
Source File: HTTPRepositoryConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void add(InputStream in, String baseURI, RDFFormat dataFormat, Resource... contexts)
		throws IOException, RDFParseException, RepositoryException {
	if (this.getRepository().useCompatibleMode()) {

		dataFormat = getBackwardCompatibleFormat(dataFormat);

		if (!isActive()) {
			// Send bytes directly to the server
			client.upload(in, baseURI, dataFormat, false, false, contexts);
		} else {
			// Parse files locally
			super.add(in, baseURI, dataFormat, contexts);

		}
		return;
	}

	flushTransactionState(Action.ADD);
	// Send bytes directly to the server
	client.upload(in, baseURI, dataFormat, false, false, contexts);
}
 
Example #5
Source File: TestFunctionCore.java    From rmlmapper-java with MIT License 6 votes vote down vote up
Executor doPreloadMapping(String mapPath, String outPath) throws Exception {
        Map<String, Class> libraryMap = new HashMap<>();
        libraryMap.put("IDLabFunctions", IDLabTestFunctions.class);
        libraryMap.put("io.fno.grel.ArrayFunctions", io.fno.grel.ArrayFunctions.class);
        libraryMap.put("io.fno.grel.BooleanFunctions", io.fno.grel.BooleanFunctions.class);
        libraryMap.put("io.fno.grel.ControlsFunctions", io.fno.grel.ControlsFunctions.class);
        libraryMap.put("io.fno.grel.StringFunctions", io.fno.grel.StringFunctions.class);

        // Read function description files.
        RDF4JStore functionDescriptionTriples = new RDF4JStore();
        functionDescriptionTriples.read(Utils.getInputStreamFromFile(Utils.getFile("functions_idlab.ttl")), null, RDFFormat.TURTLE);
        functionDescriptionTriples.read(Utils.getInputStreamFromFile(Utils.getFile("rml-fno-test-cases/functions_test.ttl")), null, RDFFormat.TURTLE);
        functionDescriptionTriples.read(Utils.getInputStreamFromFile(Utils.getFile("functions_grel.ttl")), null, RDFFormat.TURTLE);
        functionDescriptionTriples.read(Utils.getInputStreamFromFile(Utils.getFile("grel_java_mapping.ttl")), null, RDFFormat.TURTLE);
//            File myFile = Utils.getFile("rml-fno-test-cases/functions_test.ttl");
        FunctionLoader functionLoader = new FunctionLoader(functionDescriptionTriples, libraryMap);
        Executor executor = this.createExecutor(mapPath, functionLoader);
        doMapping(executor, outPath);
        return executor;
    }
 
Example #6
Source File: ReasoningUpdateBenchmark.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public void forwardChainingSchemaCachingRDFSInferencer() throws IOException {
	SailRepository sail = new SailRepository(new SchemaCachingRDFSInferencer(new MemoryStore()));

	try (SailRepositoryConnection connection = sail.getConnection()) {
		connection.begin();
		connection.add(resourceAsStream("schema.ttl"), "", RDFFormat.TURTLE, schemaGraph);
		connection.commit();

		addAllDataMultipleTransactions(connection);

	}

	checkSize(sail);
}
 
Example #7
Source File: SimpleRecordServiceTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void exportUsingBatchExporterTest() throws Exception {
    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);

    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));
    assertEquals(testRecord.getModel(), outputModel);

    verify(utilsService).optObject(eq(testIRI), any(OrmFactory.class), eq(connection));
}
 
Example #8
Source File: TargetNodeMinCountEdgeCaseTests.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testMinCountWithValidInitialDataset2() throws Throwable {

	SailRepository sailRepository = new SailRepository(new ShaclSail(new MemoryStore()));

	try (SailRepositoryConnection connection = sailRepository.getConnection()) {
		connection.begin();
		connection.add(validPerson1, ssn, value1);
		connection.add(validPerson1, ssn, value2);

		connection.commit();

		connection.begin();
		connection.add(new StringReader(shaclShapes), "", RDFFormat.TURTLE, RDF4J.SHACL_SHAPE_GRAPH);
		connection.add(validPerson2, ssn, value1);
		connection.add(validPerson2, ssn, value2);
		connection.commit();
	} catch (Exception e) {
		throw e.getCause();
	}

}
 
Example #9
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 #10
Source File: RDFImportServiceImpl.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
private void importInputStream(RepositoryConnection conn, ImportServiceConfig config, @Nonnull InputStream stream,
                               @Nonnull RDFFormat format) throws IOException {
    RDFParser parser = Rio.createParser(format);
    ParserConfig parserConfig = new ParserConfig();
    if (config.getContinueOnError()) {
        parserConfig.addNonFatalError(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES);
        parserConfig.addNonFatalError(BasicParserSettings.FAIL_ON_UNKNOWN_LANGUAGES);
        parserConfig.addNonFatalError(BasicParserSettings.NORMALIZE_DATATYPE_VALUES);
    }
    parserConfig.addNonFatalError(BasicParserSettings.VERIFY_URI_SYNTAX);
    parser.setParserConfig(parserConfig);
    BatchInserter inserter = new BatchInserter(conn, transformer, config.getBatchSize());
    if (config.getLogOutput()) {
        inserter.setLogger(LOGGER);
    }
    if (config.getPrintOutput()) {
        inserter.setPrintToSystem(true);
    }
    parser.setRDFHandler(inserter);
    parser.parse(stream, "");
}
 
Example #11
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testPropertyPathNegationInversion() throws Exception {
	String data = "@prefix : <http://example.org/>.\n"
			+ ":Mary :parentOf :Jim.\n"
			+ ":Jim :knows :Jane.\n"
			+ ":Jane :worksFor :IBM.";

	conn.add(new StringReader(data), "", RDFFormat.TURTLE);
	String query1 = "prefix : <http://example.org/> ASK WHERE { :IBM ^(:|!:) :Jane } ";

	assertTrue(conn.prepareBooleanQuery(query1).evaluate());

	String query2 = "prefix : <http://example.org/> ASK WHERE { :IBM ^(:|!:) ?a } ";
	assertTrue(conn.prepareBooleanQuery(query2).evaluate());

	String query3 = "prefix : <http://example.org/> ASK WHERE { :IBM (^(:|!:))* :Mary } ";
	assertTrue(conn.prepareBooleanQuery(query3).evaluate());

}
 
Example #12
Source File: ConfigViewTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testRender() throws Exception {

	ConfigView configView = ConfigView.getInstance();

	Model configData = new LinkedHashModelFactory().createEmptyModel();
	configData.add(RDF.ALT, RDF.TYPE, RDFS.CLASS);

	Map<Object, Object> map = new LinkedHashMap<>();
	map.put(ConfigView.HEADERS_ONLY, false);
	map.put(ConfigView.CONFIG_DATA_KEY, configData);
	map.put(ConfigView.FORMAT_KEY, RDFFormat.NTRIPLES);

	final MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod(HttpMethod.GET.name());
	request.addHeader("Accept", RDFFormat.NTRIPLES.getDefaultMIMEType());

	MockHttpServletResponse response = new MockHttpServletResponse();

	configView.render(map, request, response);

	String ntriplesData = response.getContentAsString();
	Model renderedData = Rio.parse(new StringReader(ntriplesData), "", RDFFormat.NTRIPLES);
	assertThat(renderedData).isNotEmpty();
}
 
Example #13
Source File: TestProxyRepositoryFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public final void testGetRepository() throws RDF4JException, IOException {
	Model graph = Rio.parse(this.getClass().getResourceAsStream("/proxy.ttl"), RepositoryConfigSchema.NAMESPACE,
			RDFFormat.TURTLE);
	RepositoryConfig config = RepositoryConfig.create(graph,
			Models.subject(graph.getStatements(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY))
					.orElseThrow(() -> new RepositoryConfigException("missing Repository instance in config")));
	config.validate();
	assertThat(config.getID()).isEqualTo("proxy");
	assertThat(config.getTitle()).isEqualTo("Test Proxy for 'memory'");
	RepositoryImplConfig implConfig = config.getRepositoryImplConfig();
	assertThat(implConfig.getType()).isEqualTo("openrdf:ProxyRepository");
	assertThat(implConfig).isInstanceOf(ProxyRepositoryConfig.class);
	assertThat(((ProxyRepositoryConfig) implConfig).getProxiedRepositoryID()).isEqualTo("memory");

	// Factory just needs a resolver instance to proceed with construction.
	// It doesn't actually invoke the resolver until the repository is
	// accessed. Normally LocalRepositoryManager is the caller of
	// getRepository(), and will have called this setter itself.
	ProxyRepository repository = (ProxyRepository) factory.getRepository(implConfig);
	repository.setRepositoryResolver(mock(RepositoryResolver.class));
	assertThat(repository).isInstanceOf(ProxyRepository.class);
}
 
Example #14
Source File: TriGParserTestCase.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public TestSuite createTestSuite() throws Exception {
	// Create test suite
	TestSuite suite = new TestSuite(TriGParserTestCase.class.getName());

	// Add the manifest for W3C test cases to a repository and query it
	Repository w3cRepository = new SailRepository(new MemoryStore());
	w3cRepository.initialize();
	RepositoryConnection w3cCon = w3cRepository.getConnection();

	InputStream inputStream = this.getClass().getResourceAsStream(TEST_W3C_MANIFEST_URL);
	w3cCon.add(inputStream, TEST_W3C_MANIFEST_URI_BASE, RDFFormat.TURTLE);

	parsePositiveTriGSyntaxTests(suite, TEST_W3C_FILE_BASE_PATH, TESTS_W3C_BASE_URL, TEST_W3C_TEST_URI_BASE,
			w3cCon);
	parseNegativeTriGSyntaxTests(suite, TEST_W3C_FILE_BASE_PATH, TESTS_W3C_BASE_URL, TEST_W3C_TEST_URI_BASE,
			w3cCon);
	parsePositiveTriGEvalTests(suite, TEST_W3C_FILE_BASE_PATH, TESTS_W3C_BASE_URL, TEST_W3C_TEST_URI_BASE, w3cCon);
	parseNegativeTriGEvalTests(suite, TEST_W3C_FILE_BASE_PATH, TESTS_W3C_BASE_URL, TEST_W3C_TEST_URI_BASE, w3cCon);

	w3cCon.close();
	w3cRepository.shutDown();

	return suite;
}
 
Example #15
Source File: SimpleOntology.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public OutputStream asRdfXml(OutputStream outputStream) throws MobiOntologyException {
    try {
        RDFHandler rdfWriter = new BufferedGroupingRDFHandler(Rio.createWriter(RDFFormat.RDFXML, 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 #16
Source File: RdfSerializationExample.java    From Wikidata-Toolkit-Examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {

		// Define where log messages go
		ExampleHelpers.configureLogging();

		// Print information about this program
		printDocumentation();

		// Initialize sites; only needed to link to Wikipedia pages in RDF
		DumpProcessingController dumpProcessingController = new DumpProcessingController(
				"wikidatawiki");
		dumpProcessingController.setOfflineMode(ExampleHelpers.OFFLINE_MODE);
		Sites sites = dumpProcessingController.getSitesInformation();

		// Prepare a compressed output stream to write the data to
		// (admittedly, this is slightly over-optimized for an example)
		OutputStream bufferedFileOutputStream = new BufferedOutputStream(
				ExampleHelpers
						.openExampleFileOuputStream("wikidata-simple-statements.nt.gz"),
				1024 * 1024 * 5);
		GzipParameters gzipParameters = new GzipParameters();
		gzipParameters.setCompressionLevel(7);
		OutputStream compressorOutputStream = new GzipCompressorOutputStream(
				bufferedFileOutputStream, gzipParameters);
		OutputStream exportOutputStream = asynchronousOutputStream(compressorOutputStream);

		// Create a serializer processor
		RdfSerializer serializer = new RdfSerializer(RDFFormat.NTRIPLES,
				exportOutputStream, sites,
				PropertyRegister.getWikidataPropertyRegister());
		// Serialize simple statements (and nothing else) for all items
		serializer.setTasks(RdfSerializer.TASK_ITEMS
				| RdfSerializer.TASK_SIMPLE_STATEMENTS);

		// Run serialization
		serializer.open();
		ExampleHelpers.processEntitiesFromWikidataDump(serializer);
		serializer.close();
	}
 
Example #17
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSES2147PropertyPathsWithIdenticalSubsPreds() throws Exception {

	StringBuilder data = new StringBuilder();
	data.append("<urn:s1> <urn:p> <urn:s2> .\n");
	data.append("<urn:s2> <urn:p> <urn:s3> .\n");
	data.append("<urn:s3> <urn:q> <urn:s4> .\n");
	data.append("<urn:s1> <urn:p> <urn:s5> .\n");
	data.append("<urn:s5> <urn:q> <urn:s6> .\n");

	conn.begin();
	conn.add(new StringReader(data.toString()), "", RDFFormat.NTRIPLES);
	conn.commit();

	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("SELECT ?x \n");
	query.append("WHERE { ?x <urn:p>*/<urn:q> <urn:s4> . \n");
	query.append("        ?x <urn:p>*/<urn:q> <urn:s6> . \n");
	query.append("} \n");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());

	try (TupleQueryResult result = tq.evaluate();) {

		assertNotNull(result);
		assertTrue(result.hasNext());

		Value x = result.next().getValue("x");
		assertNotNull(x);
		assertTrue(x instanceof IRI);
		assertEquals("urn:s1", x.stringValue());
	} catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
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 testSES2013BlankNodeSemiColonBNodeSpaceURI() throws Exception {
	Model model = Rio.parse(new StringReader("<urn:a> a _:c2; <urn:b> <urn:c> ."), "", RDFFormat.TURTLE);

	assertEquals(2, model.size());
	assertTrue(model.contains(vf.createIRI("urn:a"), vf.createIRI("urn:b"), vf.createIRI("urn:c")));
}
 
Example #19
Source File: ContextAwareConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void add(Reader reader, String baseURI, RDFFormat dataFormat, Resource... contexts)
		throws IOException, RDFParseException, RepositoryException {
	if (baseURI == null) {
		baseURI = getBaseURI();
	}
	if (isNilContext(contexts) && !dataFormat.supportsContexts()) {
		super.add(reader, baseURI, dataFormat, getAddContexts());
	} else {
		super.add(reader, baseURI, dataFormat, contexts);
	}
}
 
Example #20
Source File: RdfControllerAccumuloTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    this.mockMvc = standaloneSetup(controller).build();
    try {
        RepositoryConnection con = repository.getConnection();
        con.add(getClass().getResourceAsStream("/test.nt"), "", RDFFormat.NTRIPLES);
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: CustomTurtleParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSES2165LiteralSpaceDatatypeCarriageReturn() throws Exception {
	Model model = Rio.parse(new StringReader("<urn:a> <urn:b> \"testliteral\"^^\r<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 #22
Source File: HalyardStatsTest.java    From Halyard with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatsTargetPartial() throws Exception {
    final HBaseSail sail = new HBaseSail(HBaseServerTestInstance.getInstanceConfig(), "statsTable3", true, -1, true, 0, null, null);
    sail.initialize();
    try (InputStream ref = HalyardStatsTest.class.getResourceAsStream("testData.trig")) {
        RDFParser p = Rio.createParser(RDFFormat.TRIG);
        p.setPreserveBNodeIDs(true);
        p.setRDFHandler(new AbstractRDFHandler() {
            @Override
            public void handleStatement(Statement st) throws RDFHandlerException {
                sail.addStatement(st.getSubject(), st.getPredicate(), st.getObject(), st.getContext());
            }
        }).parse(ref, "");
    }
    sail.commit();
    sail.close();

    File root = File.createTempFile("test_stats", "");
    root.delete();
    root.mkdirs();

    assertEquals(0, ToolRunner.run(HBaseServerTestInstance.getInstanceConfig(), new HalyardStats(),
            new String[]{"-s", "statsTable3", "-t", root.toURI().toURL().toString() + "stats{0}.trig", "-r", "100", "-g", "http://whatever/myStats", "-c", "http://whatever/graph0"}));

    File stats = new File(root, "stats0.trig");
    assertTrue(stats.isFile());
    try (InputStream statsStream = new FileInputStream(stats)) {
        try (InputStream refStream = HalyardStatsTest.class.getResourceAsStream("testStatsTargetPartial.trig")) {
            Model statsM = Rio.parse(statsStream, "", RDFFormat.TRIG, new ParserConfig().set(BasicParserSettings.PRESERVE_BNODE_IDS, true), SimpleValueFactory.getInstance(), new ParseErrorLogger());
            Model refM = Rio.parse(refStream, "", RDFFormat.TRIG, new ParserConfig().set(BasicParserSettings.PRESERVE_BNODE_IDS, true), SimpleValueFactory.getInstance(), new ParseErrorLogger(), SimpleValueFactory.getInstance().createIRI("http://whatever/myStats"));
            assertEqualModels(refM, statsM);
        }
    }
}
 
Example #23
Source File: TriGParserCustomTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testBadPname02() throws Exception {
	try {
		Rio.parse(new StringReader("@prefix : <http://example/> . {:a%2 :p :o .}"), "", RDFFormat.TRIG);
		fail("Did not receive expected exception");
	} catch (RDFParseException e) {

	}
}
 
Example #24
Source File: Utils.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static SailRepository getSailRepository(URL resourceName) {
	SailRepository sailRepository = new SailRepository(new MemoryStore());
	sailRepository.initialize();
	try (SailRepositoryConnection connection = sailRepository.getConnection()) {
		connection.add(resourceName, resourceName.toString(), RDFFormat.TURTLE);
	} catch (IOException | NullPointerException e) {
		System.out.println("Error reading: " + resourceName);
		throw new RuntimeException(e);
	}
	return sailRepository;
}
 
Example #25
Source File: NoReificationTest.java    From inception with Apache License 2.0 5 votes vote down vote up
@Test
public void thatItemCanBeObtainedAsStatements() throws Exception
{
    importDataFromString(RDFFormat.TURTLE, TURTLE_PREFIX,
            DATA_LABELS_AND_DESCRIPTIONS_WITH_LANGUAGE);
   
    List<KBStatement> result = listStatements(rdf4jLocalRepo,
            new KBHandle("http://example.org/#green-goblin"));
    
    assertThat(result)
            .extracting(stmt -> stmt.getInstance().getIdentifier())
            .allMatch(id -> id.equals("http://example.org/#green-goblin"));
    assertThat(result).hasSize(7);
}
 
Example #26
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 #27
Source File: IsomorphicTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Model getModel(String name) {
	try {
		try (InputStream resourceAsStream = IsomorphicTest.class.getClassLoader()
				.getResourceAsStream("benchmark/" + name)) {
			return Rio.parse(resourceAsStream, "http://example.com/", RDFFormat.TURTLE);
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #28
Source File: RdfFormatUtils.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to determine the appropriate RDF file format based on the extension
 * of a file name. The supplied fallback format will be returned when the
 * file name extension was not recognized.
 * @param fileName A file name.
 * @return An {@link RDFFormat} that matches the file name extension, or the
 * fallback format if the extension was not recognized.
 */
public static RDFFormat forFileName(final String fileName, final RDFFormat fallback) {
    final Optional<RDFFormat> match = FileFormat.matchFileName(fileName, RDF_FORMATS);
    if (match.isPresent()) {
        return match.get();
    } else {
        return fallback;
    }
}
 
Example #29
Source File: GraphReadingUtility.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Model readOntology(final RDFFormat format, final InputStream is, final String baseURI)
        throws RDFParseException, RDFHandlerException, UnsupportedRDFormatException, IOException {
    final StatementCollector collector = new StatementCollector();
    final RDFParser parser = Rio.createParser(format);
    parser.setRDFHandler(collector);
    parser.parse(is, baseURI);
    return new LinkedHashModel(collector.getStatements());
}
 
Example #30
Source File: ExportTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public final void testExportAll() throws RepositoryException, IOException {
	File nq = LOCATION.newFile("all.nq");
	cmd.execute("export", nq.getAbsolutePath());
	Model exp = Rio.parse(Files.newReader(nq, StandardCharsets.UTF_8), "http://example.com", RDFFormat.NQUADS);

	assertTrue("File is empty", nq.length() > 0);
	assertEquals("Number of contexts incorrect", 3, exp.contexts().size());

	nq.delete();
}