org.eclipse.rdf4j.rio.RDFParser Java Examples

The following examples show how to use org.eclipse.rdf4j.rio.RDFParser. 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: 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 #2
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 #3
Source File: AbstractNTriplesParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUriWithEscapeCharactersShouldFailToParse() throws Exception {
	RDFParser ntriplesParser = createRDFParser();
	Model model = new LinkedHashModel();
	ntriplesParser.setRDFHandler(new StatementCollector(model));

	String nt = "<http://example/\\n> <http://example/p> <http://example/o> .";

	try {
		ntriplesParser.parse(new StringReader(nt), NTRIPLES_TEST_URL);
		fail("Should have failed to parse invalid N-Triples uri with space");
	} catch (RDFParseException ignored) {
	}

	assertEquals(0, model.size());
	assertEquals(0, model.subjects().size());
	assertEquals(0, model.predicates().size());
	assertEquals(0, model.objects().size());
}
 
Example #4
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 #5
Source File: AbstractCommandTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/***
 * Add a new repository to the manager.
 *
 * @param configStream input stream of the repository configuration
 * @return ID of the repository as string
 * @throws IOException
 * @throws RDF4JException
 */
protected String addRepository(InputStream configStream) throws IOException, RDF4JException {
	RDFParser rdfParser = Rio.createParser(RDFFormat.TURTLE, SimpleValueFactory.getInstance());

	Model graph = new LinkedHashModel();
	rdfParser.setRDFHandler(new StatementCollector(graph));
	rdfParser.parse(
			new StringReader(IOUtil.readString(new InputStreamReader(configStream, StandardCharsets.UTF_8))),
			RepositoryConfigSchema.NAMESPACE);
	configStream.close();

	Resource repositoryNode = Models.subject(graph.filter(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY))
			.orElseThrow(() -> new RepositoryConfigException("could not find subject resource"));

	RepositoryConfig repoConfig = RepositoryConfig.create(graph, repositoryNode);
	repoConfig.validate();
	manager.addRepositoryConfig(repoConfig);

	String repId = Models.objectLiteral(graph.filter(repositoryNode, RepositoryConfigSchema.REPOSITORYID, null))
			.orElseThrow(() -> new RepositoryConfigException("missing repository id"))
			.stringValue();

	return repId;
}
 
Example #6
Source File: EndpointFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Utility function to load federation members from a data configuration file.
 *
 * <p>
 * A data configuration file provides information about federation members in form of turtle. Currently the types
 * NativeStore, ResolvableEndpoint and SPARQLEndpoint are supported. For details please refer to the documentation
 * in {@link NativeRepositoryInformation}, {@link ResolvableRepositoryInformation} and
 * {@link SPARQLRepositoryInformation}.
 * </p>
 *
 * @param dataConfig
 *
 * @return a list of initialized endpoints, i.e. the federation members
 *
 * @throws IOException
 * @throws Exception
 */
public static List<Endpoint> loadFederationMembers(File dataConfig, File fedXBaseDir) throws FedXException {

	if (!dataConfig.exists()) {
		throw new FedXRuntimeException("File does not exist: " + dataConfig.getAbsolutePath());
	}

	Model graph = new TreeModel();
	RDFParser parser = Rio.createParser(RDFFormat.TURTLE);
	RDFHandler handler = new DefaultRDFHandler(graph);
	parser.setRDFHandler(handler);
	try (FileReader fr = new FileReader(dataConfig)) {
		parser.parse(fr, Vocabulary.FEDX.NAMESPACE);
	} catch (Exception e) {
		throw new FedXException("Unable to parse dataconfig " + dataConfig + ":" + e.getMessage());
	}

	return loadFederationMembers(graph, fedXBaseDir);
}
 
Example #7
Source File: FedXBaseTest.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
 */
protected Set<Statement> readExpectedGraphQueryResult(String resultFile) throws Exception {
	RDFFormat rdfFormat = Rio.getParserFormatForFileName(resultFile).get();

	if (rdfFormat != null) {
		RDFParser parser = Rio.createParser(rdfFormat);
		parser.setPreserveBNodeIDs(true);
		parser.setValueFactory(SimpleValueFactory.getInstance());

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

		InputStream in = SPARQLBaseTest.class.getResourceAsStream(resultFile);
		try {
			parser.parse(in, resultFile);
		} finally {
			in.close();
		}

		return result;
	} else {
		throw new RuntimeException("Unable to determine file type of results file");
	}
}
 
Example #8
Source File: HalyardExportTest.java    From Halyard with Apache License 2.0 6 votes vote down vote up
private static int getTriplesCount(String uri, String compression, RDFFormat format) throws Exception {
    InputStream in = FileSystem.get(URI.create(uri), HBaseServerTestInstance.getInstanceConfig()).open(new Path(uri));
    try {
        if (compression != null) {
            in = new CompressorStreamFactory().createCompressorInputStream(compression, in);
        }
        RDFParser parser = Rio.createParser(format);
        final AtomicInteger i = new AtomicInteger();
        parser.setRDFHandler(new AbstractRDFHandler(){
            @Override
            public void handleStatement(Statement st) throws RDFHandlerException {
                i.incrementAndGet();
            }
        });
        parser.parse(in, uri);
        return i.get();
    } finally {
        in.close();
    }
}
 
Example #9
Source File: RDFLoader.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Adds the data that can be read from the supplied InputStream or Reader to this repository.
 *
 * @param inputStreamOrReader An {@link InputStream} or {@link Reader} containing RDF data that must be added to the
 *                            repository.
 * @param baseURI             The base URI for the data.
 * @param dataFormat          The file format of the data.
 * @param rdfHandler          handles all data from all documents
 * @throws IOException
 * @throws UnsupportedRDFormatException
 * @throws RDFParseException
 * @throws RDFHandlerException
 */
private void loadInputStreamOrReader(Object inputStreamOrReader, String baseURI, RDFFormat dataFormat,
		RDFHandler rdfHandler) throws IOException, RDFParseException, RDFHandlerException {
	RDFParser rdfParser = Rio.createParser(dataFormat, vf);
	rdfParser.setParserConfig(config);
	rdfParser.setParseErrorListener(new ParseErrorLogger());

	rdfParser.setRDFHandler(rdfHandler);

	if (inputStreamOrReader instanceof InputStream) {
		rdfParser.parse((InputStream) inputStreamOrReader, baseURI);
	} else if (inputStreamOrReader instanceof Reader) {
		rdfParser.parse((Reader) inputStreamOrReader, baseURI);
	} else {
		throw new IllegalArgumentException(
				"Must be an InputStream or a Reader, is a: " + inputStreamOrReader.getClass());
	}
}
 
Example #10
Source File: AbstractNTriplesParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testExceptionHandlingWithoutStopAtFirstError2() throws Exception {
	String data = "invalid nt";

	RDFParser ntriplesParser = createRDFParser();
	ntriplesParser.getParserConfig().set(NTriplesParserSettings.FAIL_ON_NTRIPLES_INVALID_LINES, false);

	Model model = new LinkedHashModel();
	ntriplesParser.setRDFHandler(new StatementCollector(model));

	ntriplesParser.parse(new StringReader(data), NTRIPLES_TEST_URL);

	assertEquals(0, model.size());
	assertEquals(0, model.subjects().size());
	assertEquals(0, model.predicates().size());
	assertEquals(0, model.objects().size());
}
 
Example #11
Source File: ImportsResolverImpl.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Optional<Model> retrieveOntologyFromWeb(Resource resource) {
    long startTime = getStartTime();
    RDFParser[] parsers = {new RioFunctionalSyntaxParserFactory().getParser(),
            new RioManchesterSyntaxParserFactory().getParser(),
            new RioOWLXMLParserFactory().getParser()};
    Model model = mf.createModel();
    String urlStr = resource.stringValue();

    try {
        Optional<Model> modelOpt = getModel(urlStr, parsers);
        if (modelOpt.isPresent()) {
            model = modelOpt.get();
        }
    } catch (IOException | IllegalArgumentException e) {
        log.debug("Could not retrieve resource " + resource.stringValue() + " from web");
        model = mf.createModel();
    }
    logDebug("Retrieving " + resource + " from web", startTime);
    return model.size() > 0 ? Optional.of(model) : Optional.empty();
}
 
Example #12
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 on.
 *
 * @throws Exception
 */
@Test
public void testEntityExpansionSecureProcessing() 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, true)
			.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 #13
Source File: HalyardStatsTest.java    From Halyard with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatsTarget() throws Exception {
    final HBaseSail sail = new HBaseSail(HBaseServerTestInstance.getInstanceConfig(), "statsTable", 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", "statsTable", "-t", root.toURI().toURL().toString() + "stats{0}.trig", "-r", "100", "-g", "http://whatever/myStats"}));

    File stats = new File(root, "stats0.trig");
    assertTrue(stats.isFile());
    try (InputStream statsStream = new FileInputStream(stats)) {
        try (InputStream refStream = HalyardStatsTest.class.getResourceAsStream("testStatsTarget.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 #14
Source File: RyaAccumuloSailFactoryTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
    public void testCreateFromTemplateName() throws Exception {
        LocalRepositoryManager repoman = new LocalRepositoryManager(Files.createTempDir());
        repoman.initialize();

        try(InputStream templateStream = RepositoryConfig.class.getResourceAsStream("RyaAccumuloSail.ttl")) {
            String template = IOUtils.toString(templateStream);

            final ConfigTemplate configTemplate = new ConfigTemplate(template);
            final Map<String, String> valueMap = ImmutableMap.<String, String> builder()
                    .put("Repository ID", "RyaAccumuloSail")
                    .put("Repository title", "RyaAccumuloSail Store")
                    .put("Rya Accumulo user", "root")
                    .put("Rya Accumulo password", "")
                    .put("Rya Accumulo instance", "dev")
                    .put("Rya Accumulo zookeepers", "zoo1,zoo2,zoo3")
                    .put("Rya Accumulo is mock", "true")
                    .build();

            final String configString = configTemplate.render(valueMap);

//            final Repository systemRepo = this.state.getManager().getSystemRepository();
            final Model model = new LinkedHashModel();
            final RDFParser rdfParser = Rio.createParser(RDFFormat.TURTLE);
            rdfParser.setRDFHandler(new StatementCollector(model));
            rdfParser.parse(new StringReader(configString), RepositoryConfigSchema.NAMESPACE);
            final Resource repositoryNode = Models.subject(model.filter(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY)).get();
            final RepositoryConfig repConfig = RepositoryConfig.create(model, repositoryNode);
            repConfig.validate();


            repoman.addRepositoryConfig(repConfig);

            Repository r = repoman.getRepository("RyaAccumuloSail");
            r.initialize();

        }

    }
 
Example #15
Source File: AbstractNTriplesParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testEndOfLineCommentsWithSpaceAfter() throws Exception {
	RDFParser ntriplesParser = createRDFParser();
	Model model = new LinkedHashModel();
	ntriplesParser.setRDFHandler(new StatementCollector(model));
	ntriplesParser.parse(new StringReader(
			"<urn:test:subject> <urn:test:predicate> <urn:test:object> .# endoflinecomment\n<urn:test:subject> <urn:test:predicate> <urn:test:secondobject> . # endoflinecomment\n"),
			"http://example/");
	assertEquals(2, model.size());
}
 
Example #16
Source File: StatementsDeserializer.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public Set<Statement> deserialize(final String topic, final byte[] data) {
    if(data == null || data.length == 0) {
        // Return null because that is the contract of this method.
        return null;
    }

    try {
        final RDFParser parser = PARSER_FACTORY.getParser();
        final Set<Statement> statements = new HashSet<>();

        parser.setRDFHandler(new AbstractRDFHandler() {
            @Override
            public void handleStatement(final Statement statement) throws RDFHandlerException {
                log.debug("Statement: " + statement);
                statements.add( statement );
            }
        });

        parser.parse(new ByteArrayInputStream(data), null);
        return statements;

    } catch(final RDFParseException | RDFHandlerException | IOException e) {
        log.error("Could not deserialize a Set of VisibilityStatement objects using the RDF4J Rio Binary format.", e);
        return null;
    }
}
 
Example #17
Source File: AbstractNTriplesParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testEndOfLineCommentsNoSpace() throws Exception {
	RDFParser ntriplesParser = createRDFParser();
	Model model = new LinkedHashModel();
	ntriplesParser.setRDFHandler(new StatementCollector(model));
	ntriplesParser.parse(new StringReader(
			"<urn:test:subject> <urn:test:predicate> <urn:test:object> .#endoflinecomment\n<urn:test:subject> <urn:test:predicate> <urn:test:secondobject> . # endoflinecomment\n"),
			"http://example/");
	assertEquals(2, model.size());
}
 
Example #18
Source File: CreateServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
RepositoryConfig updateRepositoryConfig(final String configString) throws IOException, RDF4JException {
	final Model graph = new LinkedHashModel();
	final RDFParser rdfParser = Rio.createParser(RDFFormat.TURTLE, SimpleValueFactory.getInstance());
	rdfParser.setRDFHandler(new StatementCollector(graph));
	rdfParser.parse(new StringReader(configString), RepositoryConfigSchema.NAMESPACE);

	Resource res = Models.subject(graph.getStatements(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY))
			.orElseThrow(() -> new RepositoryException("could not find instance of Repository class in config"));
	final RepositoryConfig repConfig = RepositoryConfig.create(graph, res);
	repConfig.validate();
	manager.addRepositoryConfig(repConfig);
	return repConfig;
}
 
Example #19
Source File: NquadsUdParser.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public RDFParser setRDFHandler(RDFHandler handler) {
  if (handler instanceof TimRdfHandler) {
    // It might be nicer to override statement, to make it contain the action, but it takes to much effort for now.
    ((TimRdfHandler) handler).registerActionSupplier(() -> actions.pop());
  }
  return super.setRDFHandler(handler);
}
 
Example #20
Source File: SpinSailTest.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 #21
Source File: JSONParserTest.java    From Halyard with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodsThatDoNothing() {
    RDFParser p = new JSONParser();
    p.setVerifyData(true);
    p.setPreserveBNodeIDs(true);
    p.setStopAtFirstError(true);
    p.setDatatypeHandling(RDFParser.DatatypeHandling.NORMALIZE);
    p.setParseErrorListener(null);
    p.setParseLocationListener(null);
}
 
Example #22
Source File: BackgroundGraphResult.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public BackgroundGraphResult(QueueCursor<Statement> queue, RDFParser parser, InputStream in, Charset charset,
		String baseURI) {
	super(queue);
	this.queue = queue;
	this.parser = parser;
	this.in = in;
	this.charset = charset;
	this.baseURI = baseURI;
}
 
Example #23
Source File: AbstractNTriplesParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testEndOfLineCommentsWithSpaceBoth() throws Exception {
	RDFParser ntriplesParser = createRDFParser();
	Model model = new LinkedHashModel();
	ntriplesParser.setRDFHandler(new StatementCollector(model));
	ntriplesParser.parse(new StringReader(
			"<urn:test:subject> <urn:test:predicate> <urn:test:object> . # endoflinecomment\n<urn:test:subject> <urn:test:predicate> <urn:test:secondobject> . # endoflinecomment\n"),
			"http://example/");
	assertEquals(2, model.size());
}
 
Example #24
Source File: AbstractNTriplesParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testEndOfLineEmptyCommentWithSpaceAfter() throws Exception {
	RDFParser ntriplesParser = createRDFParser();
	Model model = new LinkedHashModel();
	ntriplesParser.setRDFHandler(new StatementCollector(model));
	ntriplesParser.parse(new StringReader("<urn:test:subject> <urn:test:predicate> <urn:test:object> .# \n"),
			"http://example/");
	assertEquals(1, model.size());
	assertEquals(Collections.singleton("urn:test:object"), Models.objectStrings(model));
}
 
Example #25
Source File: AbstractNTriplesParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test(expected = RDFParseException.class)
public void testBlankNodeIdentifiersWithOtherCharactersAsFirstCharacter() throws Exception {
	// The characters -, U+00B7, U+0300 to U+036F and U+203F to U+2040 are permitted anywhere except the first
	// character.
	List<Character> charactersList = new ArrayList<>();
	charactersList.add('-');
	charactersList.add('\u00B7');
	charactersList.add('\u0300');
	charactersList.add('\u036F');
	charactersList.add('\u0301');
	charactersList.add('\u203F');

	for (Character character : charactersList) {
		RDFParser ntriplesParser = new NTriplesParser();
		Model model = new LinkedHashModel();
		ntriplesParser.setRDFHandler(new StatementCollector(model));

		try {
			ntriplesParser.parse(
					new StringReader("<urn:test:subject> <urn:test:predicate> _:" + character + "1 . "),
					NTRIPLES_TEST_URL);
		} catch (RDFParseException e) {
			assertEquals(0, model.size());
			assertEquals(0, model.subjects().size());
			assertEquals(0, model.predicates().size());
			assertEquals(0, model.objects().size());
			throw e;
		}
		fail("Should have failed to parse invalid N-Triples bnode with '" + character
				+ "' at the begining of the bnode label");
	}
}
 
Example #26
Source File: AbstractNQuadsParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * The N-Quads parser must be able to parse the N-Triples test file without error.
 */
public void testNTriplesFile() throws Exception {
	RDFParser nquadsParser = createRDFParser();
	nquadsParser.setRDFHandler(new AbstractRDFHandler() {
	});

	try (InputStream in = AbstractNQuadsParserUnitTest.class.getResourceAsStream(NTRIPLES_TEST_FILE)) {
		nquadsParser.parse(in, NTRIPLES_TEST_URL);
	} catch (RDFParseException e) {
		fail("NQuadsParser failed to parse N-Triples test document: " + e.getMessage());
	}
}
 
Example #27
Source File: AbstractNTriplesParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testEndOfLineCommentNoSpace() throws Exception {
	RDFParser ntriplesParser = createRDFParser();
	Model model = new LinkedHashModel();
	ntriplesParser.setRDFHandler(new StatementCollector(model));
	ntriplesParser.parse(
			new StringReader("<urn:test:subject> <urn:test:predicate> <urn:test:object> .#endoflinecomment\n"),
			"http://example/");
	assertEquals(1, model.size());
	assertEquals(Collections.singleton("urn:test:object"), Models.objectStrings(model));
}
 
Example #28
Source File: AbstractNTriplesParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testEndOfLineCommentsWithSpaceBefore() throws Exception {
	RDFParser ntriplesParser = createRDFParser();
	Model model = new LinkedHashModel();
	ntriplesParser.setRDFHandler(new StatementCollector(model));
	ntriplesParser.parse(new StringReader(
			"<urn:test:subject> <urn:test:predicate> <urn:test:object> . #endoflinecomment\n<urn:test:subject> <urn:test:predicate> <urn:test:secondobject> . # endoflinecomment\n"),
			"http://example/");
	assertEquals(2, model.size());
}
 
Example #29
Source File: AbstractNTriplesParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testEndOfLineEmptyCommentNoSpace() throws Exception {
	RDFParser ntriplesParser = createRDFParser();
	Model model = new LinkedHashModel();
	ntriplesParser.setRDFHandler(new StatementCollector(model));
	ntriplesParser.parse(new StringReader("<urn:test:subject> <urn:test:predicate> <urn:test:object> .#\n"),
			"http://example/");
	assertEquals(1, model.size());
	assertEquals(Collections.singleton("urn:test:object"), Models.objectStrings(model));
}
 
Example #30
Source File: SpinRendererTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSpinRenderer() throws IOException, RDF4JException {
	StatementCollector expected = new StatementCollector();
	RDFParser parser = Rio.createParser(RDFFormat.TURTLE);
	parser.setRDFHandler(expected);
	try (InputStream rdfStream = testURL.openStream()) {
		parser.parse(rdfStream, testURL.toString());
	}

	// get query from sp:text
	String query = null;
	for (Statement stmt : expected.getStatements()) {
		if (SP.TEXT_PROPERTY.equals(stmt.getPredicate())) {
			query = stmt.getObject().stringValue();
			break;
		}
	}
	assertNotNull(query);

	ParsedOperation parsedOp = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, query, testURL.toString());

	StatementCollector actual = new StatementCollector();
	renderer.render(parsedOp, actual);

	Object operation = (parsedOp instanceof ParsedQuery) ? ((ParsedQuery) parsedOp).getTupleExpr()
			: ((ParsedUpdate) parsedOp).getUpdateExprs();
	assertTrue("Operation was\n" + operation + "\nExpected\n" + toRDF(expected) + "\nbut was\n" + toRDF(actual),
			Models.isomorphic(actual.getStatements(), expected.getStatements()));
}