org.eclipse.rdf4j.rio.RDFHandlerException Java Examples

The following examples show how to use org.eclipse.rdf4j.rio.RDFHandlerException. 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: RDFXMLPrettyWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void outOfSequenceItemsAreNotAbbreviated() throws RDFHandlerException, IOException {
	StringWriter writer = new StringWriter();
	RDFWriter rdfWriter = rdfWriterFactory.getWriter(writer);

	rdfWriter.startRDF();

	Resource res = vf.createIRI("http://example.com/#");

	rdfWriter.handleStatement(vf.createStatement(res, RDF.TYPE, RDF.BAG));

	rdfWriter.handleStatement(
			vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_0"), vf.createIRI("http://example.com/#0")));
	rdfWriter.handleStatement(
			vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_2"), vf.createIRI("http://example.com/#2")));
	rdfWriter.endRDF();

	List<String> rdfLines = rdfOpenTags(writer.toString());

	assertEquals(Arrays.asList("<rdf:RDF", "<rdf:Bag", "<rdf:_0", "<rdf:_2"), rdfLines);
}
 
Example #2
Source File: RDFXMLPrettyWriterTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void sequenceItemsAreAbbreviated() throws RDFHandlerException, IOException {
	StringWriter writer = new StringWriter();
	RDFWriter rdfWriter = rdfWriterFactory.getWriter(writer);

	rdfWriter.startRDF();

	Resource res = vf.createIRI("http://example.com/#");

	rdfWriter.handleStatement(vf.createStatement(res, RDF.TYPE, RDF.BAG));

	rdfWriter.handleStatement(
			vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_1"), vf.createIRI("http://example.com/#1")));
	rdfWriter.handleStatement(
			vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_2"), vf.createIRI("http://example.com/#2")));
	rdfWriter.endRDF();

	List<String> rdfLines = rdfOpenTags(writer.toString());

	assertEquals(Arrays.asList("<rdf:RDF", "<rdf:Bag", "<rdf:li", "<rdf:li"), rdfLines);
}
 
Example #3
Source File: RDFXMLParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Parses the data from the supplied Reader, using the supplied baseURI to resolve any relative URI references.
 *
 * @param reader  The Reader from which to read the data, must not be <tt>null</tt>.
 * @param baseURI The URI associated with the data in the InputStream, must not be <tt>null</tt>.
 * @throws IOException              If an I/O error occurred while data was read from the InputStream.
 * @throws RDFParseException        If the parser has found an unrecoverable parse error.
 * @throws RDFHandlerException      If the configured statement handler has encountered an unrecoverable error.
 * @throws IllegalArgumentException If the supplied reader or base URI is <tt>null</tt>.
 */
@Override
public synchronized void parse(Reader reader, String baseURI)
		throws IOException, RDFParseException, RDFHandlerException {
	if (reader == null) {
		throw new IllegalArgumentException("Reader cannot be 'null'");
	}
	if (baseURI == null) {
		throw new IllegalArgumentException("Base URI cannot be 'null'");
	}

	InputSource inputSource = new InputSource(reader);
	inputSource.setSystemId(baseURI);

	parse(inputSource);
}
 
Example #4
Source File: TurtleWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void consumeStatement(Statement st) throws RDFHandlerException {
	try {
		Resource subj = st.getSubject();
		IRI pred = st.getPredicate();
		inlineBNodes = getWriterConfig().get(BasicWriterSettings.INLINE_BLANK_NODES);
		if (inlineBNodes && (pred.equals(RDF.FIRST) || pred.equals(RDF.REST))) {
			handleList(st);
		} else if (inlineBNodes && !subj.equals(lastWrittenSubject) && stack.contains(subj)) {
			handleInlineNode(st);
		} else {
			closeHangingResource();
			handleStatementInternal(st, false, inlineBNodes, inlineBNodes);
		}
	} catch (IOException e) {
		throw new RDFHandlerException(e);
	}
}
 
Example #5
Source File: NTriplesParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Implementation of the <tt>parse(InputStream, String)</tt> method defined in the RDFParser interface.
 *
 * @param in      The InputStream from which to read the data, must not be <tt>null</tt>. The InputStream is
 *                supposed to contain 7-bit US-ASCII characters, as per the N-Triples specification.
 * @param baseURI The URI associated with the data in the InputStream, must not be <tt>null</tt>.
 * @throws IOException              If an I/O error occurred while data was read from the InputStream.
 * @throws RDFParseException        If the parser has found an unrecoverable parse error.
 * @throws RDFHandlerException      If the configured statement handler encountered an unrecoverable error.
 * @throws IllegalArgumentException If the supplied input stream or base URI is <tt>null</tt>.
 */
@Override
public synchronized void parse(InputStream in, String baseURI)
		throws IOException, RDFParseException, RDFHandlerException {
	if (in == null) {
		throw new IllegalArgumentException("Input stream can not be 'null'");
	}
	// Note: baseURI will be checked in parse(Reader, String)

	try {
		parse(new InputStreamReader(new BOMInputStream(in, false), StandardCharsets.UTF_8), baseURI);
	} catch (UnsupportedEncodingException e) {
		// Every platform should support the UTF-8 encoding...
		throw new RuntimeException(e);
	}
}
 
Example #6
Source File: CbSailProducer.java    From rya with Apache License 2.0 6 votes vote down vote up
protected void sparqlQuery(final Exchange exchange, final Collection<String> queries) throws RepositoryException, MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException, RDFHandlerException {

        final List list = new ArrayList();
        for (final String query : queries) {

//            Long startTime = exchange.getIn().getHeader(START_TIME_QUERY_PROP, Long.class);
//            Long ttl = exchange.getIn().getHeader(TTL_QUERY_PROP, Long.class);
            final String auth = exchange.getIn().getHeader(CONF_QUERY_AUTH, String.class);
            final Boolean infer = exchange.getIn().getHeader(CONF_INFER, Boolean.class);

            final Object output = performSelect(query, auth, infer);
            if (queries.size() == 1) {
                exchange.getOut().setBody(output);
                return;
            } else {
                list.add(output);
            }

        }
        exchange.getOut().setBody(list);
    }
 
Example #7
Source File: TurtleWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void handleComment(String comment) throws RDFHandlerException {
	checkWritingStarted();
	try {
		closePreviousStatement();

		if (comment.indexOf('\r') != -1 || comment.indexOf('\n') != -1) {
			// Comment is not allowed to contain newlines or line feeds.
			// Split comment in individual lines and write comment lines
			// for each of them.
			StringTokenizer st = new StringTokenizer(comment, "\r\n");
			while (st.hasMoreTokens()) {
				writeCommentLine(st.nextToken());
			}
		} else {
			writeCommentLine(comment);
		}
	} catch (IOException e) {
		throw new RDFHandlerException(e);
	}
}
 
Example #8
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 #9
Source File: RepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testInsertDelete() throws RDF4JException {
	final Statement stmt = vf.createStatement(vf.createIRI(URN_TEST_S1), vf.createIRI(URN_TEST_P1),
			vf.createIRI(URN_TEST_O1));
	testCon.begin();
	testCon.prepareUpdate(QueryLanguage.SPARQL,
			"INSERT DATA {<" + URN_TEST_S1 + "> <" + URN_TEST_P1 + "> <" + URN_TEST_O1 + ">}").execute();
	testCon.prepareUpdate(QueryLanguage.SPARQL,
			"DELETE DATA {<" + URN_TEST_S1 + "> <" + URN_TEST_P1 + "> <" + URN_TEST_O1 + ">}").execute();
	testCon.commit();

	testCon.exportStatements(null, null, null, false, new AbstractRDFHandler() {

		@Override
		public void handleStatement(Statement st) throws RDFHandlerException {
			assertThat(st).isNotEqualTo(stmt);
		}
	});
}
 
Example #10
Source File: TurtleParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Parse an object
 *
 * @throws IOException
 * @throws RDFParseException
 * @throws RDFHandlerException
 */
protected void parseObject() throws IOException, RDFParseException, RDFHandlerException {
	int c = peekCodePoint();

	switch (c) {
	case '(':
		object = parseCollection();
		break;
	case '[':
		object = parseImplicitBlank();
		break;
	default:
		object = parseValue();
		reportStatement(subject, predicate, object);
		break;
	}
}
 
Example #11
Source File: BinaryRDFWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Writes the first statement from the statement queue */
private void writeStatement() throws RDFHandlerException, IOException {
	Statement st = statementQueue.remove();
	int subjId = getValueId(st.getSubject());
	int predId = getValueId(st.getPredicate());
	int objId = getValueId(st.getObject());
	int contextId = getValueId(st.getContext());

	decValueFreq(st.getSubject());
	decValueFreq(st.getPredicate());
	decValueFreq(st.getObject());
	decValueFreq(st.getContext());

	out.writeByte(STATEMENT);
	writeValueOrId(st.getSubject(), subjId);
	writeValueOrId(st.getPredicate(), predId);
	writeValueOrId(st.getObject(), objId);
	writeValueOrId(st.getContext(), contextId);
}
 
Example #12
Source File: BatchExporter.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void handleStatement(Statement statement) throws RDFHandlerException {
    delegate.handleStatement(transformer.sesameStatement(statement));
    count++;
    if (count % batchSize == 0) {
        try {
            if (logger != null) {
                logger.debug(batchSize + " statements exported...");
            }
            if (printToSystem) {
                System.out.println(batchSize + " statements exported...");
            }
        } catch (RepositoryException e) {
            throw new RDFHandlerException(e);
        }
    }
}
 
Example #13
Source File: AbstractRdfConverter.java    From Wikidata-Toolkit with Apache License 2.0 6 votes vote down vote up
/**
 * Writes all namespace declarations used in the dump, for example {@code wikibase:} or {@code schema:}.
 */
public void writeNamespaceDeclarations() throws RDFHandlerException {
	this.rdfWriter.writeNamespaceDeclaration("wd",
			this.propertyRegister.getUriPrefix());
	this.rdfWriter
			.writeNamespaceDeclaration("wikibase", Vocabulary.PREFIX_WBONTO);
	this.rdfWriter.writeNamespaceDeclaration("rdf", Vocabulary.PREFIX_RDF);
	this.rdfWriter
			.writeNamespaceDeclaration("rdfs", Vocabulary.PREFIX_RDFS);
	this.rdfWriter.writeNamespaceDeclaration("owl", Vocabulary.PREFIX_OWL);
	this.rdfWriter.writeNamespaceDeclaration("xsd", Vocabulary.PREFIX_XSD);
	this.rdfWriter.writeNamespaceDeclaration("schema",
			Vocabulary.PREFIX_SCHEMA);
	this.rdfWriter
			.writeNamespaceDeclaration("skos", Vocabulary.PREFIX_SKOS);
	this.rdfWriter
			.writeNamespaceDeclaration("prov", Vocabulary.PREFIX_PROV);
}
 
Example #14
Source File: DAWGTestResultSetWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void startQueryResult(List<String> bindingNames) throws TupleQueryResultHandlerException {
	try {
		rdfHandler.startRDF();

		resultSetNode = vf.createBNode();
		bnodeMap.clear();

		reportStatement(resultSetNode, RDF.TYPE, RESULTSET);

		for (String bindingName : bindingNames) {
			Literal bindingNameLit = vf.createLiteral(bindingName);
			reportStatement(resultSetNode, RESULTVARIABLE, bindingNameLit);
		}
	} catch (RDFHandlerException e) {
		throw new TupleQueryResultHandlerException(e);
	}
}
 
Example #15
Source File: TextOutputExample.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
protected void map(Text key, RyaStatementWritable value, Context context) throws IOException, InterruptedException {
    // receives a RyaStatementWritable; convert to a Statement
    RyaStatement rstmt = value.getRyaStatement();
    Statement st = RyaToRdfConversions.convertStatement(rstmt);
    logger.info("Mapper receives: " + rstmt);
    // then convert to an RDF string
    StringWriter writer = new StringWriter();
    try {
        RDFWriter rdfWriter = Rio.createWriter(rdfFormat, writer);
        rdfWriter.startRDF();
        rdfWriter.handleStatement(st);
        rdfWriter.endRDF();
    } catch (RDFHandlerException e) {
        throw new IOException("Error writing RDF data", e);
    }
    // Write the string to the output
    String line = writer.toString().trim();
    logger.info("Serialized to RDF: " + line);
    textOut.set(line);
    context.write(NullWritable.get(), textOut);
}
 
Example #16
Source File: CombineContextsRdfInserter.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void endRDF()
        throws RDFHandlerException {
    for (Map.Entry<String, String> entry : namespaceMap.entrySet()) {
        String prefix = entry.getKey();
        String name = entry.getValue();

        try {
            if (con.getNamespace(prefix) == null) {
                con.setNamespace(prefix, name);
            }
        } catch (RepositoryException e) {
            throw new RDFHandlerException(e);
        }
    }

    namespaceMap.clear();
    bNodesMap.clear();
}
 
Example #17
Source File: EnhancedTurtleWriter.java    From amazon-neptune-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void handleStatement(Statement statement) throws RDFHandlerException {

    prefixes.parse(statement.getSubject().stringValue(), this);
    prefixes.parse(statement.getPredicate().toString(), this);
    prefixes.parse(statement.getObject().stringValue(), this);

    Resource context = statement.getContext();
    if (context != null){
        prefixes.parse(context.stringValue(), this);
    }

    writer.startCommit();
    super.handleStatement(statement);
    writer.endCommit();

    status.update();
}
 
Example #18
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(Filter node) throws RDFHandlerException {
	node.getArg().visit(this);
	if (group != null) {
		Resource havingList = valueFactory.createBNode();
		handler.handleStatement(valueFactory.createStatement(subject, SP.HAVING_PROPERTY, havingList));
		ListContext havingCtx = newList(havingList);
		listEntry();
		node.getCondition().visit(SpinVisitor.this);
		endList(havingCtx);
	}
}
 
Example #19
Source File: RDFLoader.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void loadZip(InputStream in, String baseURI, RDFFormat dataFormat, RDFHandler rdfHandler)
		throws IOException, RDFParseException, RDFHandlerException {

	try (ZipInputStream zipIn = new ZipInputStream(in);) {
		for (ZipEntry entry = zipIn.getNextEntry(); entry != null; entry = zipIn.getNextEntry()) {
			if (entry.isDirectory()) {
				continue;
			}

			try {
				RDFFormat format = Rio.getParserFormatForFileName(entry.getName()).orElse(dataFormat);

				// Prevent parser (Xerces) from closing the input stream
				UncloseableInputStream wrapper = new UncloseableInputStream(zipIn);
				load(wrapper, baseURI, format, rdfHandler);

			} catch (RDFParseException e) {
				String msg = e.getMessage() + " in " + entry.getName();
				RDFParseException pe = new RDFParseException(msg, e.getLineNumber(), e.getColumnNumber());
				pe.initCause(e);
				throw pe;
			} finally {
				zipIn.closeEntry();
			}
		} // end for
	}
}
 
Example #20
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(Compare node) throws RDFHandlerException {
	Resource currentSubj = subject;
	flushPendingStatement();
	handler.handleStatement(valueFactory.createStatement(subject, RDF.TYPE, toValue(node.getOperator())));
	predicate = SP.ARG1_PROPERTY;
	node.getLeftArg().visit(this);
	predicate = SP.ARG2_PROPERTY;
	node.getRightArg().visit(this);
	subject = currentSubj;
	predicate = null;
}
 
Example #21
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(Coalesce node) throws RDFHandlerException {
	Resource currentSubj = subject;
	flushPendingStatement();
	handler.handleStatement(valueFactory.createStatement(subject, RDF.TYPE, SP.COALESCE));
	List<ValueExpr> args = node.getArguments();
	for (int i = 0; i < args.size(); i++) {
		predicate = toArgProperty(i + 1);
		args.get(i).visit(this);
	}
	subject = currentSubj;
	predicate = null;
}
 
Example #22
Source File: RdfConverter.java    From Wikidata-Toolkit with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTermTriples(Resource subject, TermKind kind, Collection<MonolingualTextValue> terms) throws RDFHandlerException {
    switch (kind) {
        case LABEL:
            if (!hasTask(RdfSerializer.TASK_LABELS)) return;
            break;
        case DESCRIPTION:
            if (!hasTask(RdfSerializer.TASK_DESCRIPTIONS)) return;
            break;
        case ALIAS:
            if (!hasTask(RdfSerializer.TASK_ALIASES)) return;
            break;
    }
    super.writeTermTriples(subject, kind, terms);
}
 
Example #23
Source File: AbstractNQuadsParserUnitTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testStatementWithInvalidLiteralContentAndIgnoreValidation()
		throws RDFHandlerException, IOException, RDFParseException {
	// Note: Float declare as int.
	final ByteArrayInputStream bais = new ByteArrayInputStream(
			("<http://dbpedia.org/resource/Camillo_Benso,_conte_di_Cavour> "
					+ "<http://dbpedia.org/property/mandatofine> "
					+ "\"1380.0\"^^<http://www.w3.org/2001/XMLSchema#int> "
					+ "<http://it.wikipedia.org/wiki/Camillo_Benso,_conte_di_Cavour#absolute-line=20> .")
							.getBytes());
	parser.getParserConfig().set(BasicParserSettings.VERIFY_DATATYPE_VALUES, false);
	parser.getParserConfig().set(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, false);
	parser.parse(bais, "http://base-uri");
}
 
Example #24
Source File: SPARQLGraphQuery.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void evaluate(RDFHandler handler) throws QueryEvaluationException, RDFHandlerException {

	SPARQLProtocolSession client = getHttpClient();
	try {
		client.sendGraphQuery(queryLanguage, getQueryString(), baseURI, dataset, getIncludeInferred(),
				getMaxExecutionTime(), handler, getBindingsArray());
	} catch (IOException | RepositoryException | MalformedQueryException e) {
		throw new QueryEvaluationException(e.getMessage(), e);
	}
}
 
Example #25
Source File: TriGStarParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Value parseValue() throws IOException, RDFParseException, RDFHandlerException {
	if (peekIsTripleValue()) {
		return parseTripleValue();
	}

	return super.parseValue();
}
 
Example #26
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(Create node) throws RDFHandlerException {
	if (node.isSilent()) {
		handler.handleStatement(valueFactory.createStatement(subject, SP.SILENT_PROPERTY, BooleanLiteral.TRUE));
	}

	if (node.getGraph() != null) {
		handler.handleStatement(
				valueFactory.createStatement(subject, SP.GRAPH_IRI_PROPERTY, node.getGraph().getValue()));
	}
}
 
Example #27
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(Slice node) throws RDFHandlerException {
	node.getArg().visit(this);
	if (node.hasLimit()) {
		handler.handleStatement(valueFactory.createStatement(subject, SP.LIMIT_PROPERTY,
				valueFactory.createLiteral(Long.toString(node.getLimit()), XMLSchema.INTEGER)));
	}
	if (node.hasOffset()) {
		handler.handleStatement(valueFactory.createStatement(subject, SP.OFFSET_PROPERTY,
				valueFactory.createLiteral(Long.toString(node.getOffset()), XMLSchema.INTEGER)));
	}
}
 
Example #28
Source File: TriXWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void handleComment(String comment) throws RDFHandlerException {
	checkWritingStarted();
	try {
		xmlWriter.comment(comment);
	} catch (IOException e) {
		throw new RDFHandlerException(e);
	}
}
 
Example #29
Source File: BufferedGroupingRDFHandler.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void endRDF() throws RDFHandlerException {
	synchronized (bufferLock) {
		processBuffer();
	}
	super.endRDF();
}
 
Example #30
Source File: BufferedGroupingRDFHandler.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void handleStatement(Statement st) throws RDFHandlerException {
	synchronized (bufferLock) {
		bufferedStatements.add(st);
		contexts.add(st.getContext());

		if (bufferedStatements.size() >= this.bufferSize) {
			processBuffer();
		}
	}
}