Java Code Examples for org.openrdf.rio.RDFHandlerException

The following examples show how to use org.openrdf.rio.RDFHandlerException. These examples are extracted from open source projects. 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 Project: anthelion   Source File: FilterableTripleHandler.java    License: Apache License 2.0 6 votes vote down vote up
public void handleStatement(Resource subject, URI predicate, Value object, Resource... contexts)
		throws RDFHandlerException {
	if (!started) {
		throw new IllegalStateException("Cannot handle statement without start parsing first.");
	}

	try {
		printResource(subject);
		printSpace();
		printURI(predicate);
		printSpace();
		printObject(object);
		printSpace();

		for (int i = 0; i < contexts.length; i++) {
			printResource(contexts[i]);
			printSpace();
		}

		printCloseStatement();
	} catch (IOException ioe) {
		throw new RDFHandlerException("An error occurred while printing statement.", ioe);
	}
}
 
Example 2
Source Project: attic-polygene-java   Source File: EntitySerializerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEntitySerializer()
    throws RDFHandlerException
{
    EntityReference entityReference = EntityReference.parseEntityReference( "test2" );
    Usecase usecase = UsecaseBuilder.newUsecase( "Test" );
    Instant currentTime = SystemTime.now();
    EntityStoreUnitOfWork unitOfWork = entityStore.newUnitOfWork( module, usecase, currentTime );
    EntityState entityState = unitOfWork.entityStateOf( module, entityReference );

    Iterable<Statement> graph = serializer.serialize( entityState );

    String[] prefixes = new String[]{ "rdf", "dc", " vc" };
    String[] namespaces = new String[]{ Rdfs.RDF, DcRdf.NAMESPACE, "http://www.w3.org/2001/vcard-rdf/3.0#" };

    new RdfXmlSerializer().serialize( graph, new PrintWriter( System.out ), prefixes, namespaces );
}
 
Example 3
Source Project: database   Source File: SailGraphLoader.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void addStatement(final Statement stmt, final Resource[] c)
        throws RDFHandlerException {

    try {

        cxn.addStatement(//
                stmt.getSubject(), //
                stmt.getPredicate(), //
                stmt.getObject(), //
                c);

        if (c == null || c.length == 0)
            ntriples++;
        else
            ntriples += c.length;

    } catch (SailException e) {

        throw new RDFHandlerException(e);

    }

}
 
Example 4
@Override
            public void handleStatement(final Statement stmt)
                    throws RDFHandlerException {

                final Resource s = stmt.getSubject();
                final URI p = stmt.getPredicate();
                final Value o = stmt.getObject();
                final Resource c = stmt.getContext() == null ? this.context
                        : stmt.getContext();

//                if (log.isDebugEnabled())
//                    log.debug("<" + s + "," + p + "," + o + "," + c + ">");

                buffer.add(s, p, o, c, StatementEnum.Explicit);

                n++;

            }
 
Example 5
/**
 * Helper method for handleAdd.
 */
private void addToGraphstore(
		RepositoryConnection conn,
		InputStream in,
		String base,
		RDFFormat format,
		Resource dctx,
		boolean chunked) throws IOException, RDFParseException,
		RDFHandlerException, RepositoryException {
	if (chunked) {
		RDFParser parser = getRDFParser(format);
		parser.setRDFHandler(
				new ChunkedCommitHandler(conn, chunksize, dctx));
		parser.parse(in, base);
	} else {
		if (dctx != null) {
			conn.add(in, base, format, dctx);
		} else {
			conn.add(in, base, format);
		}
	}
}
 
Example 6
private void testStandaloneParser(RDFParser parser, String resourceName) throws IOException,
		RDFParseException, RDFHandlerException {
	bNodeFound = false;
	parser.setRDFHandler(new RDFHandlerBase(){
		@Override
		public void handleStatement(Statement st)
				throws RDFHandlerException {
			if (st.getSubject() instanceof BNode) {
				bNodeFound = true;
			}
			super.handleStatement(st);
		}
	});
	try (InputStream is = getClass().getClassLoader().getResourceAsStream(resourceName)) {
		parser.parse(is, "");
	}
	assertTrue(bNodeFound);
}
 
Example 7
public void testNTriplesFile()
	throws Exception
{
	RDFParser turtleParser = createRDFParser();
	turtleParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE);
	turtleParser.setRDFHandler(new RDFHandlerBase() {
		public void handleStatement(Statement st)
				throws RDFHandlerException {
			if (log.isInfoEnabled())
				log.info("Statement: " + st);
		}
	});

	// Note: This is a local copy.
	InputStream in = BigdataNTriplesParser.class.getResourceAsStream(NTRIPLES_TEST_FILE);
	try {
		turtleParser.parse(in, NTRIPLES_TEST_URL);
	}
	catch (RDFParseException e) {
		fail("Failed to parse N-Triples test document: " + e.getMessage());
	}
	finally {
		in.close();
	}
}
 
Example 8
public void testNTriplesFileWithSIDS() throws Exception {
	RDFParser turtleParser = createRDFParser();
	turtleParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE);
	turtleParser.setRDFHandler(new RDFHandlerBase() {
		public void handleStatement(final Statement st)
				throws RDFHandlerException {
			if (log.isInfoEnabled())
				log.info("Statement: " + st);
		}
	});

	final String fileUrl = BigdataNTriplesParser.class.getResource(
			NTRIPLES_TEST_FILE_WITH_SIDS).toExternalForm();

	// Note: This is a local copy.
	InputStream in = BigdataNTriplesParser.class
			.getResourceAsStream(NTRIPLES_TEST_FILE_WITH_SIDS);
	try {
		turtleParser.parse(in, fileUrl);
	} catch (RDFParseException e) {
		fail("Failed to parse N-Triples test document: " + e.getMessage(), e);
	} finally {
		in.close();
	}
}
 
Example 9
public void testNTriplesFileWithReification() throws Exception {
	RDFParser turtleParser = createRDFParser();
	turtleParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE);
	turtleParser.setRDFHandler(new RDFHandlerBase() {
		public void handleStatement(final Statement st)
				throws RDFHandlerException {
			if (log.isInfoEnabled())
				log.info("Statement: " + st);
		}
	});

	final String fileUrl = BigdataNTriplesParser.class.getResource(
			NTRIPLES_TEST_FILE_WITH_REIFICATION).toExternalForm();

	// Note: This is a local copy.
	InputStream in = BigdataNTriplesParser.class
			.getResourceAsStream(NTRIPLES_TEST_FILE_WITH_REIFICATION);
	try {
		turtleParser.parse(in, fileUrl);
	} catch (RDFParseException e) {
		fail("Failed to parse N-Triples test document: " + e.getMessage(), e);
	} finally {
		in.close();
	}
}
 
Example 10
@Test
public void testAddRemove()
	throws Exception
{
	URI FOAF_PERSON = vf.createURI("http://xmlns.com/foaf/0.1/Person");
	final Statement stmt = vf.createStatement(bob, name, nameBob);

	testCon.add(bob, RDF.TYPE, FOAF_PERSON);

	testCon.begin();
	testCon.add(stmt);
	testCon.remove(stmt);
	testCon.commit();

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

		@Override
		public void handleStatement(Statement st)
			throws RDFHandlerException
		{
			assertThat(st, is(not(equalTo(stmt))));
		}
	});
}
 
Example 11
Source Project: GeoTriples   Source File: RML_Converter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert a Spark Partition into triples.
 *
 * @param partition_iter: an iterator of rows. The rows must follow the predefined headers.
 * @return a String of triples
 */
public Iterator<String> convertPartition(Iterator<Row> partition_iter){

    List<String> partitionTriples = new ArrayList<>();
    partition_iter.forEachRemaining(row -> {
        try {
            for (int i = 0; i < mappingList.size(); i++) {
                rdfWriter.handleStatementIter(performer.perform(row, mappingList.get(i), tm_predicates.get(i), listPOM.get(i), processor, i));
            }
            partitionTriples.add(rdfWriter.getString());
        }
        catch (RDFHandlerException e) {
            System.out.println("ERROR while Handling Statement");
            e.printStackTrace();
            System.exit(1);
        }
    });
    return  partitionTriples.iterator();
}
 
Example 12
Source Project: GeoTriples   Source File: FileSesameDataset.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Insert Triple/Statement into graph
 *
 * @param s subject uriref
 * @param p predicate uriref
 * @param o value object (URIref or Literal)
 * @param contexts varArgs context objects (use default graph if null)
 */
@Override
public void add(Resource s, URI p, Value o, Resource... contexts) {
    if (log.isDebugEnabled()) {
        log.debug("[FileSesameDataSet:add] Add triple (" + s.stringValue()
                + ", " + p.stringValue() + ", " + o.stringValue() + ").");
    }

    Statement st = new StatementImpl(s, p, o);
    try {
        writer.handleStatement(st);
        size++;
    } catch (RDFHandlerException ex) {
        log.error(o.toString());
    }

}
 
Example 13
Source Project: GeoTriples   Source File: NTriplesAlternative.java    License: Apache License 2.0 6 votes vote down vote up
public void handleStatementIter(Collection<Statement> statements) throws RDFHandlerException {
    if (!writingStarted)
        throw new RuntimeException("Document writing has not yet been started");
    try {
        // WARNING if you want to produce blank nodes replace all the .append("<").append(X).append(">");
        // with   NTriplesUtil.append(st.getSubject(), sb);
        for(Statement st: statements){
            sb
                    .append("<")
                    .append(st.getSubject().toString())
                    .append("> <")
                    .append(st.getPredicate().toString())
                    .append("> ");
            NTriplesUtilNoEscape.append(st.getObject(), sb);
            sb.append(" .\n");
        }
    } catch (Exception e) {
        throw new RDFHandlerException(e);
    }
}
 
Example 14
Source Project: database   Source File: TestTicket276.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void addData(final RepositoryConnection conn) throws IOException,
		RDFParseException, RepositoryException, RDFHandlerException {

    final RDFParser rdfParser = Rio.createParser(RDFFormat.NTRIPLES,
			conn.getValueFactory());
	rdfParser.setVerifyData(true);
	rdfParser.setStopAtFirstError(true);
	rdfParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE);
	rdfParser.setRDFHandler(new RDFHandlerBase() {
		@Override
		public void handleStatement(Statement st)
				throws RDFHandlerException {
			try {
				conn.add(st);
			} catch (OpenRDFException e) {
				throw new RDFHandlerException(e);
			}
		}
	});
	rdfParser.parse(getClass().getResourceAsStream("TestTicket276.n3"), "");
}
 
Example 15
Source Project: database   Source File: TestNoExceptions.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final SailRepository repo, final String query)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException,
		RDFHandlerException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		conn.setAutoCommit(false);
		try {
			final ValueFactory vf = conn.getValueFactory();
			conn.commit();
			TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
			TupleQueryResult tqr = tq.evaluate();
			tqr.close();
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 16
/**
 * Called by JAX-RS upon building a response.
 *
 * @param out the {@link OutputStream} to write the triples to
 * @throws IOException if there was an error during communication
 * @throws WebApplicationException if there was an error while serialising
 */
@Override
public void write(OutputStream out)
		throws IOException, WebApplicationException {
	try {
		RDFWriter writer = factory.getWriter(out);
		// evaluate query and stream result
		query.evaluate(writer);
		conn.close();
	} catch (RepositoryException |
			 QueryEvaluationException |
			 RDFHandlerException ex) {
		// server error
		close(conn, ex);
		throw new WebApplicationException(ex);
	}
}
 
Example 17
/**
 * Handles a statement.
 * 
 * The statements will be added up until chunk size is reached.
 * After a chunk of statements is added the transaction will be committed
 * and new transaction will be started.
 * @param stmnt
 * @throws RDFHandlerException 
 */
@Override
public void handleStatement(Statement stmnt) throws RDFHandlerException {
	try {
		// check if triple should be added to a specific graph
		if (dctx != null) {
			conn.add(stmnt, dctx);
		} else {
			conn.add(stmnt);
		}
		// check if chunk size is reached and transaction should be
		// committed
		count++;
		if (count >= size) {
			count = 0;
			conn.commit();
			conn.begin();
		}
	} catch (RepositoryException ex) {
		throw new RDFHandlerException(ex);
	}
}
 
Example 18
Source Project: anthelion   Source File: FilterableTripleHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void receiveTriple(Resource s, URI p, Value o, URI g, ExtractionContext context)
		throws TripleHandlerException {
	// if uri is in negative namespace which has to be filtered out and not
	// in the positive list - return directly
	for (String negativeFilterNamespace : negativeFilterNamespaces) {
		if (p.toString().startsWith(negativeFilterNamespace)) {
			for (String positiveFilterNamespace : positiveFilterNamespaces) {
				if (!p.toString().startsWith(positiveFilterNamespace)) {
					System.out.println(
							"Namespace filtered: " + s.toString() + " , " + p.toString() + ", " + o.toString());
					return;
				}
			}
		}
	}

	// check the css
	for (String negativeFileter : eveilNamespacesCSS)
		if (p.toString().toLowerCase().contains(negativeFileter))
			return;

	URI extractorUri = extractorNames.get(context.getExtractorName());
	if (extractorUri == null) {
		extractorUri = ValueFactoryImpl.getInstance().createURI("ex:" + context.getExtractorName());
		extractorNames.put(context.getExtractorName(), extractorUri);
	}

	try {
		handleStatement(s, p, o, context.getDocumentURI(), extractorUri);
		totalTriples++;
	} catch (RDFHandlerException e) {
		throw new TripleHandlerException("Unable to recieve Triple", e);
	}

	String ex = context.getExtractorName();
	if (triplesPerExtractor.containsKey(ex)) {
		triplesPerExtractor.put(ex, new Long(triplesPerExtractor.get(ex) + 1));
	}
}
 
Example 19
Source Project: cumulusrdf   Source File: HTMLWriter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleComment(String arg0) throws RDFHandlerException {

	try {

		_writer.write("<p>");
		_writer.write("# ");
		_writer.write(arg0);
		_writer.write("<p/>");

	} catch (IOException e) {
		throw new RDFHandlerException(e);
	}
}
 
Example 20
Source Project: attic-polygene-java   Source File: AbstractSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize( Iterable<Statement> graph, Writer out ) throws RDFHandlerException
{
    String[] prefixes = { "polygene", "rdf", "rdfs" };
    String[] namespaces = { PolygeneRdf.POLYGENE_MODEL, Rdfs.RDF, Rdfs.RDFS };
    serialize( graph, out, prefixes, namespaces );
}
 
Example 21
Source Project: attic-polygene-java   Source File: ApplicationXmlTest.java    License: Apache License 2.0 5 votes vote down vote up
private void writeN3( Iterable<Statement> graph )
    throws RDFHandlerException, IOException
{
    RDFWriterFactory writerFactory = new N3WriterFactory();
    RDFWriter writer = writerFactory.getWriter( System.out );
    writeOutput( writer, graph );
}
 
Example 22
Source Project: attic-polygene-java   Source File: ApplicationXmlTest.java    License: Apache License 2.0 5 votes vote down vote up
private void writeXml( Iterable<Statement> graph )
    throws RDFHandlerException, IOException
{
    RDFWriterFactory writerFactory = new RDFXMLWriterFactory();
    RDFWriter writer = writerFactory.getWriter( System.out );
    writeOutput( writer, graph );
}
 
Example 23
Source Project: attic-polygene-java   Source File: ApplicationXmlTest.java    License: Apache License 2.0 5 votes vote down vote up
private void writeOutput( RDFWriter writer, Iterable<Statement> graph )
    throws RDFHandlerException
{
    writer.startRDF();
    writer.handleNamespace( "polygene", PolygeneRdf.POLYGENE_MODEL );
    writer.handleNamespace( "rdf", Rdfs.RDF );
    writer.handleNamespace( "rdfs", Rdfs.RDFS );
    for( Statement st : graph )
    {
        writer.handleStatement( st );
    }
    writer.endRDF();
}
 
Example 24
@Override
public void handleStatement(final Statement st) throws RDFHandlerException {
    namespacesReady.countDown();
    if (closed)
        throw new RDFHandlerException("Result closed");
    try {
        queue.put(st);
    } catch (InterruptedException e) {
        throw new RDFHandlerException(e);
    }
}
 
Example 25
private void indexTTLFile(File file, String baseURI)
		throws RDFParseException, RDFHandlerException, FileNotFoundException, IOException {
	log.info("Start parsing: " + file);
	RDFParser parser = new TurtleParser();
	OnlineStatementHandler osh = new OnlineStatementHandler();
	parser.setRDFHandler(osh);
	parser.setStopAtFirstError(false);
	parser.parse(new FileReader(file), baseURI);
	log.info("Finished parsing: " + file);
}
 
Example 26
@Override
   public void exportStatements(final Resource s, final URI p, final Value o,
           final boolean includeInferred, final RDFHandler handler,
           final Resource... c) throws RepositoryException,
           RDFHandlerException {

       try {

           final RemoteRepository remote = repo.getRemoteRepository();

           final GraphQueryResult src = remote.getStatements(s, p, o,
                   includeInferred, c);
           try {
               handler.startRDF();
               while (src.hasNext()) {
                   handler.handleStatement(src.next());
               }
               handler.endRDF();
           } finally {
               src.close();
           }
		
	} catch (Exception ex) {
		
		throw new RepositoryException(ex);

	}
	
}
 
Example 27
@Test
public void testExport() throws RepositoryException, RDFHandlerException {
	final RDFHandler handler = new RDFHandlerBase();
	con.exportStatements(s, p, o, includeInferred, handler, c);
	assertEquals(EncodeDecodeValue.encodeValue(s), remote.data.opts.getRequestParam("s"));
	assertEquals(EncodeDecodeValue.encodeValue(p), remote.data.opts.getRequestParam("p"));
	assertEquals(EncodeDecodeValue.encodeValue(o), remote.data.opts.getRequestParam("o"));
	assertEquals(EncodeDecodeValue.encodeValue(c), remote.data.opts.getRequestParam("c"));
	assertEquals(Boolean.toString(includeInferred), remote.data.opts.getRequestParam(RemoteRepositoryDecls.INCLUDE_INFERRED));
}
 
Example 28
Source Project: database   Source File: TestTicket967.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void executeTest(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, RDFHandlerException,
		IOException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		try {
			conn.setAutoCommit(false);
			final ValueFactory vf = conn.getValueFactory();
	        final URI uri = vf.createURI("os:/elem/example");
	        // run a query which looks for a statement and then adds it if it is not found.
	        addDuringQueryExec(conn, uri, RDF.TYPE, vf.createURI("os:class/Clazz"));
	        // now try to export the statements.
        	final RepositoryResult<Statement> stats = conn.getStatements(null, null, null, false);
	        try {
	        	// materialize the newly added statement.
	        	stats.next();
	        } catch (RuntimeException e) {
	        	fail(e.getLocalizedMessage(), e); // With Bigdata this fails
	        } finally {
	        	stats.close();
	        }
	        conn.rollback(); // discard the result (or commit, but do something to avoid a logged warning from Sesame).
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 29
Source Project: cumulusrdf   Source File: HTMLWriter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void startRDF() throws RDFHandlerException {

	try {
		_writer.write("<html><head><title>" + _title + "</title></head><body>");
		_writer.write("<h1>" + _title + "</h1>");
	} catch (IOException e) {
		throw new RDFHandlerException(e);
	}
}
 
Example 30
Source Project: ldp4j   Source File: RDFModelFormater.java    License: Apache License 2.0 5 votes vote down vote up
protected String exportRepository(RepositoryConnection connection) throws RepositoryException, RDFHandlerException {
	StringWriter writer=new StringWriter();
	RDFWriter rdfWriter=Rio.createWriter(getFormat(),writer);
	if(rdfWriter instanceof TurtleWriter) {
		rdfWriter=new RebasingTurtleWriter(writer);
	}
	connection.export(rdfWriter);
	return writer.toString();
}