Java源码示例:org.eclipse.rdf4j.rio.RDFHandlerException
示例1
@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();
}
示例2
@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);
}
}
示例3
@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);
}
}
示例4
@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);
}
});
}
示例5
/** 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);
}
示例6
@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);
}
}
}
示例7
/**
* 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);
}
示例8
@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);
}
示例9
@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();
}
示例10
@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);
}
示例11
@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);
}
}
示例12
/**
* 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;
}
}
示例13
/**
* 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();
}
示例14
/**
* 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);
}
}
示例15
/**
* 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);
}
示例16
@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);
}
示例17
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);
}
示例18
private void interrupt() {
isInterrupted = true;
if (!isEnded()) {
try {
// we call endRDF() in case impls have resources to close
endRDF();
} catch (RDFHandlerException e) {
logger.warn("Failed to end RDF", e);
}
}
}
示例19
protected void reportStatement(Resource subj, IRI pred, Value obj) throws RDFParseException, RDFHandlerException {
if (subj != null && pred != null && obj != null) {
Statement st = createStatement(subj, pred, obj);
if (rdfHandler != null) {
rdfHandler.handleStatement(st);
}
}
}
示例20
@Override
public void meet(Not node) throws RDFHandlerException {
if (node.getArg() instanceof Exists) {
super.meet(node);
} else {
Resource currentSubj = subject;
flushPendingStatement();
handler.handleStatement(valueFactory.createStatement(subject, RDF.TYPE, SP.NOT));
predicate = SP.ARG1_PROPERTY;
node.getArg().visit(this);
subject = currentSubj;
predicate = null;
}
}
示例21
private void readNamespaceDecl() throws IOException, RDFHandlerException {
String prefix = readString();
String namespace = readString();
if (rdfHandler != null) {
rdfHandler.handleNamespace(prefix, namespace);
}
}
示例22
@Override
public void handleNamespace(String prefix, String uri) throws RDFHandlerException {
checkWritingStarted();
try {
out.writeByte(NAMESPACE_DECL);
writeString(prefix);
writeString(uri);
} catch (IOException e) {
throw new RDFHandlerException(e);
}
}
示例23
@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;
}
示例24
@Override
public void endRDF() throws RDFHandlerException {
checkWritingStarted();
try {
closePreviousStatement();
writer.flush();
} catch (IOException e) {
throw new RDFHandlerException(e);
}
}
示例25
protected void parseObjectList() throws IOException, RDFParseException, RDFHandlerException {
parseObject();
while (skipWSC() == ',') {
readCodePoint();
skipWSC();
parseObject();
}
}
示例26
@Override
public void handleStatement(Statement st) throws RDFHandlerException {
Resource subject = SESAME.WILDCARD.equals(st.getSubject()) ? null : st.getSubject();
IRI predicate = SESAME.WILDCARD.equals(st.getPredicate()) ? null : st.getPredicate();
Value object = SESAME.WILDCARD.equals(st.getObject()) ? null : st.getObject();
// use the RepositoryConnection.clear operation if we're removing
// all statements
final boolean clearAllTriples = subject == null && predicate == null && object == null;
try {
Resource context = st.getContext();
if (context != null) {
if (clearAllTriples) {
conn.clear(context);
} else {
conn.remove(subject, predicate, object, context);
}
} else {
if (clearAllTriples) {
conn.clear();
} else {
conn.remove(subject, predicate, object);
}
}
} catch (RepositoryException e) {
throw new RDFHandlerException(e);
}
}
示例27
@Override
public void endRDF() throws RDFHandlerException {
synchronized (bufferLock) {
processBuffer();
}
super.endRDF();
}
示例28
@Override
public void handleComment(String comment) throws RDFHandlerException {
checkWritingStarted();
try {
xmlWriter.comment(comment);
} catch (IOException e) {
throw new RDFHandlerException(e);
}
}
示例29
@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()));
}
}
示例30
@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);
}
}