org.eclipse.rdf4j.rio.UnsupportedRDFormatException Java Examples

The following examples show how to use org.eclipse.rdf4j.rio.UnsupportedRDFormatException. 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: RDFLoader.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Parses RDF data from the specified file to the given RDFHandler.
 *
 * @param file       A file containing RDF data.
 * @param baseURI    The base URI to resolve any relative URIs that are in the data against. This defaults to the
 *                   value of {@link java.io.File#toURI() file.toURI()} if the value is set to <tt>null</tt>.
 * @param dataFormat The serialization format of the data.
 * @param rdfHandler Receives RDF parser events.
 * @throws IOException                  If an I/O error occurred while reading from the file.
 * @throws UnsupportedRDFormatException If no parser is available for the specified RDF format.
 * @throws RDFParseException            If an error was found while parsing the RDF data.
 * @throws RDFHandlerException          If thrown by the RDFHandler
 */
public void load(File file, String baseURI, RDFFormat dataFormat, RDFHandler rdfHandler)
		throws IOException, RDFParseException, RDFHandlerException {
	if (baseURI == null) {
		// default baseURI to file
		baseURI = file.toURI().toString();
	}
	if (dataFormat == null) {
		dataFormat = Rio.getParserFormatForFileName(file.getName())
				.orElseThrow(() -> new UnsupportedRDFormatException(
						"Could not find RDF format for file: " + file.getName()));
	}

	try (InputStream in = new FileInputStream(file);) {
		load(in, baseURI, dataFormat, rdfHandler);
	}
}
 
Example #2
Source File: TupleQueryResultTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void addData() throws IOException, UnsupportedRDFormatException, RDFParseException, RepositoryException {
	InputStream defaultGraph = TupleQueryResultTest.class.getResourceAsStream("/testcases/default-graph-1.ttl");
	try {
		con.add(defaultGraph, "", RDFFormat.TURTLE);
	} finally {
		defaultGraph.close();
	}
}
 
Example #3
Source File: KafkaLoadStatementsIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnsupportedRDFormatException.class)
public void test_invalidFile() throws Exception {
    try(final Producer<?, VisibilityStatement> producer =
            KafkaTestUtil.makeProducer(rule, StringSerializer.class, VisibilityStatementSerializer.class)) {
        final KafkaLoadStatements command = new KafkaLoadStatements(rule.getKafkaTopicName(), producer);
        command.fromFile(INVALID, "a|b|c");
    }
}
 
Example #4
Source File: TestGenerate.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testSourceGenerate() throws RDFParseException, RDFHandlerException, UnsupportedRDFormatException, OntologyToJavaException, IOException {
    SourceGenerator.toSource(
            GraphReadingUtility.readOntology(new File("src/test/resources/mapping.trig"),
                    "http://mobi.com/ontologies/delimited"),
            "test", "target/generated-sources", new ArrayList<>());
}
 
Example #5
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 #6
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 File file, final String baseUri)
        throws RDFParseException, RDFHandlerException, UnsupportedRDFormatException, IOException {
    try (final InputStream is = new FileInputStream(file)) {
        final Optional<RDFFormat> format = Rio.getParserFormatForFileName(file.getName());
        if (format.isPresent()) {
            LOG.info("Reading file '" + file.getAbsolutePath() + "' assumed format: " + format.get());
            return readOntology(format.get(), is, baseUri);
        } else {
            throw new IOException("Could not identify format of file containing ontology: " + file.getName());
        }
    }
}
 
Example #7
Source File: OrmGenerationMojo.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Model readOntology(final FileObject fileObject, final String baseUri)
        throws RDFParseException, RDFHandlerException, UnsupportedRDFormatException, IOException {
    try (final InputStream is = fileObject.getContent().getInputStream()) {
        final Optional<RDFFormat> format = Rio.getParserFormatForFileName(fileObject.getName().getBaseName());
        if (format.isPresent()) {
            return GraphReadingUtility.readOntology(format.get(), is, baseUri);
        } else {
            throw new IOException("Could not identify format of file containing ontology: " + fileObject.getName());
        }
    }
}
 
Example #8
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 #9
Source File: Utils.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void loadShapeData(SailRepository repo, URL resourceName)
		throws RDF4JException, UnsupportedRDFormatException, IOException {
	((ShaclSail) repo.getSail()).disableValidation();

	try (RepositoryConnection conn = repo.getConnection()) {
		conn.begin();
		conn.add(resourceName, resourceName.toString(), RDFFormat.TURTLE, RDF4J.SHACL_SHAPE_GRAPH);

		conn.commit();
	}
	((ShaclSail) repo.getSail()).enableValidation();

}
 
Example #10
Source File: ConfigController.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private ModelAndView handleUpdate(HttpServletRequest request, HttpServletResponse response)
		throws RDFParseException, UnsupportedRDFormatException, IOException, HTTPException {
	String repId = RepositoryInterceptor.getRepositoryID(request);
	Model model = Rio.parse(request.getInputStream(), "",
			Rio.getParserFormatForMIMEType(request.getContentType())
					.orElseThrow(() -> new HTTPException(HttpStatus.SC_BAD_REQUEST,
							"unrecognized content type " + request.getContentType())));
	RepositoryConfig config = RepositoryConfigUtil.getRepositoryConfig(model, repId);
	repositoryManager.addRepositoryConfig(config);
	return new ModelAndView(EmptySuccessView.getInstance());

}
 
Example #11
Source File: GraphQueryResultTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void addData() throws IOException, UnsupportedRDFormatException, RDFParseException, RepositoryException {
	InputStream defaultGraph = GraphQueryResultTest.class.getResourceAsStream("/testcases/graph3.ttl");
	try {
		con.add(defaultGraph, "", RDFFormat.TURTLE);
	} finally {
		defaultGraph.close();
	}
}
 
Example #12
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected HttpResponse execute(HttpUriRequest method) throws IOException, RDF4JException {
	boolean consume = true;
	if (params != null) {
		method.setParams(params);
	}
	HttpResponse response = httpClient.execute(method, httpContext);

	try {
		int httpCode = response.getStatusLine().getStatusCode();
		if (httpCode >= 200 && httpCode < 300 || httpCode == HttpURLConnection.HTTP_NOT_FOUND) {
			consume = false;
			return response; // everything OK, control flow can continue
		} else {
			switch (httpCode) {
			case HttpURLConnection.HTTP_UNAUTHORIZED: // 401
				throw new UnauthorizedException();
			case HttpURLConnection.HTTP_UNAVAILABLE: // 503
				throw new QueryInterruptedException();
			default:
				ErrorInfo errInfo = getErrorInfo(response);
				// Throw appropriate exception
				if (errInfo.getErrorType() == ErrorType.MALFORMED_DATA) {
					throw new RDFParseException(errInfo.getErrorMessage());
				} else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_FILE_FORMAT) {
					throw new UnsupportedRDFormatException(errInfo.getErrorMessage());
				} else if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) {
					throw new MalformedQueryException(errInfo.getErrorMessage());
				} else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) {
					throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage());
				} else if (contentTypeIs(response, "application/shacl-validation-report")) {
					RDFFormat format = getContentTypeSerialisation(response);
					throw new RepositoryException(new RemoteShaclValidationException(
							new StringReader(errInfo.toString()), "", format));

				} else if (errInfo.toString().length() > 0) {
					throw new RepositoryException(errInfo.toString());
				} else {
					throw new RepositoryException(response.getStatusLine().getReasonPhrase());
				}
			}
		}
	} finally {
		if (consume) {
			EntityUtils.consumeQuietly(response.getEntity());
		}
	}
}
 
Example #13
Source File: ReduceNumberOfPlansTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testRemovingPredicate() throws RDF4JException, UnsupportedRDFormatException, IOException {
	ShaclSail shaclSail = new ShaclSail(new MemoryStore());
	shaclSail.init();
	Utils.loadShapeData(shaclSail, "reduceNumberOfPlansTest/shacl.ttl");

	try (ShaclSailConnection connection = (ShaclSailConnection) shaclSail.getConnection()) {

		connection.begin();

		IRI person1 = Utils.Ex.createIri();

		ValueFactory vf = shaclSail.getValueFactory();
		connection.addStatement(person1, RDF.TYPE, Utils.Ex.Person);
		connection.addStatement(person1, Utils.Ex.ssn, vf.createLiteral("a"));
		connection.addStatement(person1, Utils.Ex.ssn, vf.createLiteral("b"));
		connection.addStatement(person1, Utils.Ex.name, vf.createLiteral("c"));
		connection.commit();

		connection.begin();

		connection.removeStatements(person1, Utils.Ex.ssn, vf.createLiteral("b"));

		refreshAddedRemovedStatements(connection);
		try (ConnectionsGroup connectionsGroup = connection.getConnectionsGroup()) {

			List<PlanNode> collect1 = shaclSail.getNodeShapes()
					.stream()
					.flatMap(shape -> shape.generatePlans(connectionsGroup, shape, false, false))
					.collect(Collectors.toList());
			assertEquals(1, collect1.size());

		}

		connection.removeStatements(person1, Utils.Ex.ssn, vf.createLiteral("a"));

		refreshAddedRemovedStatements(connection);
		try (ConnectionsGroup connectionsGroup = connection.getConnectionsGroup()) {

			List<PlanNode> collect2 = shaclSail.getNodeShapes()
					.stream()
					.flatMap(shape -> shape.generatePlans(connectionsGroup, shape, false, false))
					.collect(Collectors.toList());
			assertEquals(1, collect2.size());
		}
		connection.removeStatements(person1, Utils.Ex.name, vf.createLiteral("c"));
		refreshAddedRemovedStatements(connection);
		try (ConnectionsGroup connectionsGroup = connection.getConnectionsGroup()) {

			List<PlanNode> collect3 = shaclSail.getNodeShapes()
					.stream()
					.flatMap(shape -> shape.generatePlans(connectionsGroup, shape, false, false))
					.collect(Collectors.toList());
			assertEquals(2, collect3.size());
		}
		connection.rollback();

	}

}
 
Example #14
Source File: OrmGenerationMojo.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
private Model readOntology(final String fileLocation, final String baseUri)
        throws RDFParseException, RDFHandlerException, UnsupportedRDFormatException, IOException {
    return readOntology(fileSystemManager.resolveFile(fileLocation), baseUri);
}
 
Example #15
Source File: ReduceNumberOfPlansTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testAddingTypeStatement() throws RDFParseException, UnsupportedRDFormatException, IOException {
	ShaclSail shaclSail = new ShaclSail(new MemoryStore());
	shaclSail.init();
	Utils.loadShapeData(shaclSail, "reduceNumberOfPlansTest/shacl.ttl");

	try (ShaclSailConnection connection = (ShaclSailConnection) shaclSail.getConnection()) {
		connection.begin();

		refreshAddedRemovedStatements(connection);
		try (ConnectionsGroup connectionsGroup = connection.getConnectionsGroup()) {

			List<PlanNode> collect = shaclSail.getNodeShapes()
					.stream()
					.flatMap(shape -> shape.generatePlans(connectionsGroup, shape, false, false))
					.collect(Collectors.toList());

			assertEquals(0, collect.size());
		}
		IRI person1 = Utils.Ex.createIri();
		connection.addStatement(person1, RDF.TYPE, Utils.Ex.Person);
		refreshAddedRemovedStatements(connection);
		try (ConnectionsGroup connectionsGroup = connection.getConnectionsGroup()) {

			List<PlanNode> collect2 = shaclSail.getNodeShapes()
					.stream()
					.flatMap(shape -> shape.generatePlans(connectionsGroup, shape, false, false))
					.collect(Collectors.toList());
			assertEquals(2, collect2.size());

		}
		ValueFactory vf = shaclSail.getValueFactory();
		connection.addStatement(person1, Utils.Ex.ssn, vf.createLiteral("a"));
		connection.addStatement(person1, Utils.Ex.ssn, vf.createLiteral("b"));
		connection.addStatement(person1, Utils.Ex.name, vf.createLiteral("c"));

		connection.commit();

	}

}
 
Example #16
Source File: KafkaLoadStatements.java    From rya with Apache License 2.0 4 votes vote down vote up
@Override
public void fromFile(final Path statementsPath, final String visibilities) throws RyaStreamsException {
    requireNonNull(statementsPath);
    requireNonNull(visibilities);

    if(!statementsPath.toFile().exists()) {
        throw new RyaStreamsException("Could not load statements at path '" + statementsPath + "' because that " +
                "does not exist. Make sure you've entered the correct path.");
    }

    // Create an RDF Parser whose format is derived from the statementPath's file extension.
    final String filename = statementsPath.getFileName().toString();
    final RDFFormat format = RdfFormatUtils.forFileName(filename);
    if (format == null) {
        throw new UnsupportedRDFormatException("Unknown RDF format for the file: " + filename);
    }
    final RDFParser parser = Rio.createParser(format);

    // Set a handler that writes the statements to the specified kafka topic.
    parser.setRDFHandler(new AbstractRDFHandler() {
        @Override
        public void startRDF() throws RDFHandlerException {
            log.trace("Starting loading statements.");
        }

        @Override
        public void handleStatement(final Statement stmnt) throws RDFHandlerException {
            final VisibilityStatement visiStatement = new VisibilityStatement(stmnt, visibilities);
            producer.send(new ProducerRecord<>(topic, visiStatement));
        }

        @Override
        public void endRDF() throws RDFHandlerException {
            producer.flush();
            log.trace("Done.");
        }
    });

    // Do the parse and load.
    try {
        parser.parse(Files.newInputStream(statementsPath), "");
    } catch (RDFParseException | RDFHandlerException | IOException e) {
        throw new RyaStreamsException("Could not load the RDF file's Statements into Rya Streams.", e);
    }
}
 
Example #17
Source File: RdfWriter.java    From Wikidata-Toolkit with Apache License 2.0 4 votes vote down vote up
public RdfWriter(RDFFormat format, OutputStream output) throws UnsupportedRDFormatException {
	this(Rio.createWriter(format, output));
}
 
Example #18
Source File: AbstractCommandTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Load triples or quads from a resource file into the repository
 *
 * @param repId repository ID
 * @param data  URL of the resource
 * @param file  name of the file
 * @throws IOException
 * @throws UnsupportedRDFormatException
 */
protected void loadData(String repId, URL data, String file) throws IOException, UnsupportedRDFormatException {
	RDFFormat fmt = Rio.getParserFormatForFileName(file)
			.orElseThrow(() -> new UnsupportedRDFormatException("No parser for " + file));

	try (RepositoryConnection connection = manager.getRepository(repId).getConnection()) {
		connection.add(data, null, fmt);
	}
}
 
Example #19
Source File: QueryResults.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Parses an RDF document and returns it as a GraphQueryResult object, with parsing done on a separate thread in the
 * background.<br>
 * IMPORTANT: As this method will spawn a new thread in the background, it is vitally important that the resulting
 * GraphQueryResult be closed consistently when it is no longer required, to prevent resource leaks.
 *
 * @param in      The {@link InputStream} containing the RDF document.
 * @param baseURI The base URI for the RDF document.
 * @param format  The {@link RDFFormat} of the RDF document.
 * @return A {@link GraphQueryResult} that parses in the background, and must be closed to prevent resource leaks.
 */
public static GraphQueryResult parseGraphBackground(InputStream in, String baseURI, RDFFormat format)
		throws UnsupportedRDFormatException {
	return parseGraphBackground(in, baseURI, Rio.createParser(format));
}