org.eclipse.rdf4j.rio.RDFParserRegistry Java Examples

The following examples show how to use org.eclipse.rdf4j.rio.RDFParserRegistry. 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: HalyardBulkLoad.java    From Halyard with Apache License 2.0 6 votes vote down vote up
private static String listRDF() {
    StringBuilder sb = new StringBuilder();
    for (RDFFormat fmt : RDFParserRegistry.getInstance().getKeys()) {
        sb.append("* ").append(fmt.getName()).append(" (");
        boolean first = true;
        for (String ext : fmt.getFileExtensions()) {
            if (first) {
                first = false;
            } else {
                sb.append(", ");
            }
            sb.append('.').append(ext);
        }
        sb.append(")\n");
    }
    return sb.toString();
}
 
Example #2
Source File: SemagrowSailFactory.java    From semagrow with Apache License 2.0 6 votes vote down vote up
public void initializeMetadata(Repository metadata, String filename)
        throws RepositoryException, IOException, RDFParseException
{
    RepositoryConnection conn = null;

    try {
        File file = new File(filename);
        metadata.initialize();
        conn = metadata.getConnection();
        RDFFormat fileFormat = RDFFormat.matchFileName(file.getAbsolutePath(), RDFParserRegistry.getInstance().getKeys()).orElse(RDFFormat.NTRIPLES);
        conn.add(file, file.toURI().toString(), fileFormat);
    } finally {
        if (conn != null)
            conn.close();
    }
}
 
Example #3
Source File: Rdf4jRdfParserTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void supportsNQuadsUdDeletions() throws Exception {
  RDFParserRegistry.getInstance().add(new NquadsUdParserFactory());
  RdfProcessor rdfProcessor = mock(RdfProcessor.class);
  StringReader reader =
    new StringReader("-<http://example.org/subject1> <http://pred> \"12\"^^<http://number> <http://some_graph> .");
  Rdf4jRdfParser instance = new Rdf4jRdfParser();

  instance.importRdf(rdfPatchLog(reader, File.createTempFile("test", "rdf")), "", "", rdfProcessor);

  verify(rdfProcessor).onQuad(
    DELETE,
    "http://example.org/subject1",
    "http://pred",
    "12",
    "http://number",
    null,
    "http://some_graph"
  );
}
 
Example #4
Source File: Rdf4jRdfParserTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void handlesBlankNodeSubjectProperly() throws Exception {
  RDFParserRegistry.getInstance().add(new NquadsUdParserFactory());
  RdfProcessor rdfProcessor = mock(RdfProcessor.class);
  StringReader reader =
    new StringReader("+_:alice <http://pred> \"12\"^^<http://number> <http://some_graph> .");
  Rdf4jRdfParser instance = new Rdf4jRdfParser();

  File tempFile = File.createTempFile("test", "rdf");
  instance.importRdf(rdfPatchLog(reader, tempFile),
      "http://example.org/", "http://example.com/test.rdf", rdfProcessor);

  verify(rdfProcessor).onQuad(
    ADD,
    "http://example.org/.well-known/genid/" + DigestUtils.md5Hex(tempFile.getName()) + "_alice",
    "http://pred",
    "12",
    "http://number",
    null,
    "http://some_graph"
  );
}
 
Example #5
Source File: Rdf4jRdfParserTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void handlesBlankNodeObjectProperly() throws Exception {
  RDFParserRegistry.getInstance().add(new NquadsUdParserFactory());
  RdfProcessor rdfProcessor = mock(RdfProcessor.class);
  StringReader reader =
    new StringReader("+_:alice <http://pred> _:bob <http://some_graph> .");
  Rdf4jRdfParser instance = new Rdf4jRdfParser();

  File tempFile = File.createTempFile("test", "rdf");
  instance.importRdf(rdfPatchLog(reader, tempFile),
      "http://example.org/", "http://example.com/test.rdf", rdfProcessor);

  verify(rdfProcessor).onQuad(
    ADD,
    "http://example.org/.well-known/genid/" + DigestUtils.md5Hex(tempFile.getName()) + "_alice",
    "http://pred",
    "http://example.org/.well-known/genid/" + DigestUtils.md5Hex(tempFile.getName()) + "_bob",
    null,
    null,
    "http://some_graph"
  );
}
 
Example #6
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static RDFFormat getContentTypeSerialisation(HttpResponse response) {
	Header[] headers = response.getHeaders("Content-Type");

	Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys();
	if (rdfFormats.isEmpty()) {
		throw new RepositoryException("No tuple RDF parsers have been registered");
	}

	for (Header header : headers) {
		for (HeaderElement element : header.getElements()) {
			// SHACL Validation report Content-Type gets transformed from:
			// application/shacl-validation-report+n-quads => application/n-quads
			// application/shacl-validation-report+ld+json => application/ld+json
			// text/shacl-validation-report+turtle => text/turtle

			String[] split = element.getName().split("\\+");
			StringBuilder serialisation = new StringBuilder(element.getName().split("/")[0] + "/");
			for (int i = 1; i < split.length; i++) {
				serialisation.append(split[i]);
				if (i + 1 < split.length) {
					serialisation.append("+");
				}
			}

			logger.debug("SHACL validation report is serialised as: " + serialisation.toString());

			Optional<RDFFormat> rdfFormat = RDFFormat.matchMIMEType(serialisation.toString(), rdfFormats);

			if (rdfFormat.isPresent()) {
				return rdfFormat.get();
			}
		}
	}

	throw new RepositoryException("Unsupported content-type for SHACL Validation Report: "
			+ Arrays.toString(response.getHeaders("Content-Type")));

}
 
Example #7
Source File: SimpleOntology.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void initialize(OntologyManager ontologyManager, SesameTransformer transformer, BNodeService bNodeService,
                        RepositoryManager repoManager, boolean resolveImports, ForkJoinPool threadPool) {
    this.threadPool = threadPool;
    this.ontologyManager = ontologyManager;
    this.transformer = transformer;
    this.bNodeService = bNodeService;
    this.repoManager = repoManager;
    this.owlManager = OWLManager.createOWLOntologyManager();
    owlManager.addMissingImportListener((MissingImportListener) arg0 -> {
        missingImports.add(SimpleOntologyValues.mobiIRI(arg0.getImportedOntologyURI()));
        LOG.warn("Missing import {} ", arg0.getImportedOntologyURI());
    });
    owlManager.setOntologyLoaderConfiguration(config);
    OWLOntologyWriterConfiguration writerConfig = new OWLOntologyWriterConfiguration()
            .withRemapAllAnonymousIndividualsIds(false)
            .withSaveIdsForAllAnonymousIndividuals(true);
    owlManager.setOntologyWriterConfiguration(writerConfig);
    owlManager.setOntologyConfigurator(owlManager.getOntologyConfigurator()
            .withRemapAllAnonymousIndividualsIds(false)
            .withSaveIdsForAllAnonymousIndividuals(true));
    if (resolveImports) {
        owlManager.getIRIMappers().add(new MobiOntologyIRIMapper(ontologyManager));
        OWLOntologyFactory originalFactory = owlManager.getOntologyFactories().iterator().next();
        owlManager.getOntologyFactories().add(new MobiOntologyFactory(ontologyManager, originalFactory,
                transformer));
    } else {
        owlManager.setIRIMappers(Collections.singleton(new NoImportLoader()));
    }

    RDFParserRegistry parserRegistry = RDFParserRegistry.getInstance();
    Set<RioAbstractParserFactory> owlParsers = new HashSet<>(Arrays.asList(new RioOWLXMLParserFactory(),
            new RioManchesterSyntaxParserFactory(), new RioFunctionalSyntaxParserFactory()));
    owlParsers.forEach(parserRegistry::add);
}
 
Example #8
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Parse the response in a background thread. HTTP connections are dealt with in the {@link BackgroundGraphResult}
 * or (in the error-case) in this method.
 */
protected GraphQueryResult getRDFBackground(HttpUriRequest method, boolean requireContext)
		throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException,
		UnauthorizedException, QueryInterruptedException {

	boolean submitted = false;

	// Specify which formats we support using Accept headers
	Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys();
	if (rdfFormats.isEmpty()) {
		throw new RepositoryException("No tuple RDF parsers have been registered");
	}

	GraphQueryResult gRes = null;
	// send the tuple query
	HttpResponse response = sendGraphQueryViaHttp(method, requireContext, rdfFormats);
	try {

		// if we get here, HTTP code is 200
		String mimeType = getResponseMIMEType(response);
		RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats)
				.orElseThrow(() -> new RepositoryException(
						"Server responded with an unsupported file format: " + mimeType));
		RDFParser parser = Rio.createParser(format, getValueFactory());
		parser.setParserConfig(getParserConfig());
		parser.setParseErrorListener(new ParseErrorLogger());

		Charset charset = null;

		// SES-1793 : Do not attempt to check for a charset if the format is
		// defined not to have a charset
		// This prevents errors caused by people erroneously attaching a
		// charset to a binary formatted document
		HttpEntity entity = response.getEntity();
		if (format.hasCharset() && entity != null && entity.getContentType() != null) {
			// TODO copied from SPARQLGraphQuery repository, is this
			// required?
			try {
				charset = ContentType.parse(entity.getContentType().getValue()).getCharset();
			} catch (IllegalCharsetNameException e) {
				// work around for Joseki-3.2
				// Content-Type: application/rdf+xml;
				// charset=application/rdf+xml
			}
			if (charset == null) {
				charset = UTF8;
			}
		}

		if (entity == null) {
			throw new RepositoryException("Server response was empty.");
		}

		String baseURI = method.getURI().toASCIIString();
		gRes = background.parse(parser, entity.getContent(), charset, baseURI);
		submitted = true;
		return gRes;
	} finally {
		if (!submitted) {
			EntityUtils.consumeQuietly(response.getEntity());
		}
	}

}
 
Example #9
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Parse the response in this thread using the provided {@link RDFHandler}. All HTTP connections are closed and
 * released in this method
 */
protected void getRDF(HttpUriRequest method, RDFHandler handler, boolean requireContext)
		throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException,
		UnauthorizedException, QueryInterruptedException {
	// Specify which formats we support using Accept headers
	Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys();
	if (rdfFormats.isEmpty()) {
		throw new RepositoryException("No tuple RDF parsers have been registered");
	}

	// send the tuple query
	HttpResponse response = sendGraphQueryViaHttp(method, requireContext, rdfFormats);
	try {

		String mimeType = getResponseMIMEType(response);
		try {
			RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats)
					.orElseThrow(() -> new RepositoryException(
							"Server responded with an unsupported file format: " + mimeType));
			// Check if we can pass through to the output stream directly
			if (handler instanceof RDFWriter) {
				RDFWriter rdfWriter = (RDFWriter) handler;
				if (rdfWriter.getRDFFormat().equals(format)) {
					OutputStream out = rdfWriter.getOutputStream().orElse(null);
					if (out != null) {
						InputStream in = response.getEntity().getContent();
						IOUtils.copy(in, out);
						return;
					}
				}
			}

			// we need to parse the result and re-serialize.
			RDFParser parser = Rio.createParser(format, getValueFactory());
			parser.setParserConfig(getParserConfig());
			parser.setParseErrorListener(new ParseErrorLogger());
			parser.setRDFHandler(handler);
			parser.parse(response.getEntity().getContent(), method.getURI().toASCIIString());
		} catch (RDFParseException e) {
			throw new RepositoryException("Malformed query result from server", e);
		}
	} finally {
		EntityUtils.consumeQuietly(response.getEntity());
	}
}
 
Example #10
Source File: Rdf4jIoFactory.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
public Rdf4jIoFactory() {
  RDFParserRegistry.getInstance().add(new NquadsUdParserFactory());
}