org.openrdf.rio.RDFWriterRegistry Java Examples

The following examples show how to use org.openrdf.rio.RDFWriterRegistry. 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: GraphHandler.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
/**
 * Get all statements and export them as RDF.
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param response the HttpServletResponse object
 * @return a model and view for exporting the statements.
 * @throws ClientHTTPException throws when errors in parameters 
 */
private ModelAndView getExportStatementsResult(final Repository repository, final HttpServletRequest request,
		final HttpServletResponse response)
		throws ClientHTTPException {
	ProtocolUtil.logRequestParameters(request);

	ValueFactory vf = repository.getValueFactory();

	URI graph = getGraphName(request, vf);

	RDFWriterFactory rdfWriterFactory = ProtocolUtil.getAcceptableService(request, response,
			RDFWriterRegistry.getInstance());

	Map<String, Object> model = new HashMap<String, Object>();

	model.put(ExportStatementsView.CONTEXTS_KEY, new Resource[] { graph });
	model.put(ExportStatementsView.FACTORY_KEY, rdfWriterFactory);
	model.put(ExportStatementsView.USE_INFERENCING_KEY, true);
	model.put(ExportStatementsView.HEADERS_ONLY, METHOD_HEAD.equals(request.getMethod()));
	return new ModelAndView(ExportStatementsView.getInstance(), model);
}
 
Example #2
Source File: RepositoryRegistry.java    From neo4j-sparql-extension with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This is needed, because Rio is unable to find the Parser/Writer Factories
 * automatically when the jar gets deployed as plugin inside the Neo4j
 * Server.
 */
private synchronized void initRio() {
	if (!rioInitialized) {
		RDFParserRegistry parserRegistry = RDFParserRegistry.getInstance();
		parserRegistry.add(new TurtleParserFactory());
		parserRegistry.add(new RDFXMLParserFactory());
		parserRegistry.add(new NTriplesParserFactory());
		parserRegistry.add(new RDFJSONParserFactory());
		RDFWriterRegistry writerRegistry = RDFWriterRegistry.getInstance();
		writerRegistry.add(new TurtleWriterFactory());
		writerRegistry.add(new RDFXMLWriterFactory());
		writerRegistry.add(new NTriplesWriterFactory());
		writerRegistry.add(new RDFJSONWriterFactory());
		rioInitialized = true;
	}
}
 
Example #3
Source File: RDFModelFormater.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
private RDFWriter createWriter(StringWriter writer) {
	RDFWriter result=null;
	if(format.equals(Format.TURTLE)) {
		result=new TurtlePrettyPrinter(new MemValueFactory().createURI(baseURI.toString()),writer);
	} else {
		RDFWriterRegistry registry=RDFWriterRegistry.getInstance();
		RDFFormat rawFormat=Rio.getWriterFormatForMIMEType(format.getMime(),RDFFormat.RDFXML);
		RDFWriterFactory factory=registry.get(rawFormat);
		result=factory.getWriter(writer);
		if(format.equals(Format.JSON_LD)) {
			result.getWriterConfig().set(JSONLDSettings.JSONLD_MODE,JSONLDMode.FLATTEN);
			result.getWriterConfig().set(BasicWriterSettings.PRETTY_PRINT,true);
		}
	}
	return result;
}
 
Example #4
Source File: SparqlQueryController.java    From sparql-playground with GNU General Public License v2.0 5 votes vote down vote up
private FileFormatServiceRegistry<? extends FileFormat, ?> getRegistryInstance(SparqlQueryType queryType) {
	switch(queryType){
		case TUPLE_QUERY: return TupleQueryResultWriterRegistry.getInstance();
		case GRAPH_QUERY: return RDFWriterRegistry.getInstance();
		case BOOLEAN_QUERY: return BooleanQueryResultWriterRegistry.getInstance();
	}
	return null;
}
 
Example #5
Source File: StatementHandler.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * Get all statements and export them as RDF.
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param response the HttpServletResponse object
 * @return a model and view for exporting the statements.
 * @throws ClientHTTPException throws when there errors in parsing the request
 */
private ModelAndView getExportStatementsResult(final Repository repository, final HttpServletRequest request,
		final HttpServletResponse response)
		throws ClientHTTPException {
	ProtocolUtil.logRequestParameters(request);

	ValueFactory vf = repository.getValueFactory();

	Resource subj = ProtocolUtil.parseResourceParam(request, SUBJECT_PARAM_NAME, vf);
	URI pred = ProtocolUtil.parseURIParam(request, PREDICATE_PARAM_NAME, vf);
	Value obj = ProtocolUtil.parseValueParam(request, OBJECT_PARAM_NAME, vf);
	Resource[] contexts = ProtocolUtil.parseContextParam(request, CONTEXT_PARAM_NAME, vf);
	boolean useInferencing = ProtocolUtil.parseBooleanParam(request, INCLUDE_INFERRED_PARAM_NAME, true);

	RDFWriterFactory rdfWriterFactory = ProtocolUtil.getAcceptableService(request, response,
			RDFWriterRegistry.getInstance());

	Map<String, Object> model = new HashMap<String, Object>();
	model.put(ExportStatementsView.SUBJECT_KEY, subj);
	model.put(ExportStatementsView.PREDICATE_KEY, pred);
	model.put(ExportStatementsView.OBJECT_KEY, obj);
	model.put(ExportStatementsView.CONTEXTS_KEY, contexts);
	model.put(ExportStatementsView.USE_INFERENCING_KEY, Boolean.valueOf(useInferencing));
	model.put(ExportStatementsView.FACTORY_KEY, rdfWriterFactory);
	model.put(ExportStatementsView.HEADERS_ONLY, METHOD_HEAD.equals(request.getMethod()));
	model.put(ExportStatementsView.REPO_KEY, repository);
	return new ModelAndView(ExportStatementsView.getInstance(), model);
}
 
Example #6
Source File: RDFStreamingOutput.java    From neo4j-sparql-extension with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a new RDF streaming output that uses the given connection to
 * stream RDF triples in the given format from the a graph.
 *
 * @param conn the repository connection
 * @param format the RDF format
 * @param contexts the graphs to stream from
 */
public RDFStreamingOutput(
		RepositoryConnection conn,
		RDFFormat format,
		Resource... contexts) {
	super(conn);
	this.contexts = contexts;
	this.factory = RDFWriterRegistry.getInstance().get(format);
}
 
Example #7
Source File: RemoteRepositoryBase.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Serialize an iteration of statements into a byte[] to send across the
 * wire.
 */
protected static byte[] serialize(final Iterable<? extends Statement> stmts,
        final RDFFormat format) throws Exception {
    
    final RDFWriterFactory writerFactory = 
        RDFWriterRegistry.getInstance().get(format);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
    final RDFWriter writer = writerFactory.getWriter(baos);
    
    writer.startRDF();
    
    for (Statement stmt : stmts) {
    
        writer.handleStatement(stmt);
        
    }

    writer.endRDF();
    
    final byte[] data = baos.toByteArray();
    
    return data;

}
 
Example #8
Source File: ExportKB.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
     * Exports all told statements associated with the last commit point for the
     * KB.
     * 
     * @throws IOException
     * @throws SailException
     * @throws RDFHandlerException
     */
    public void exportData() throws IOException, SailException,
            RDFHandlerException {
        prepare();
//        final BigdataSail sail = new BigdataSail(kb);
//        try {
//            sail.initialize();
//            final SailConnection conn = sail.getReadOnlyConnection();
//            try {
                final CloseableIteration<? extends Statement, SailException> itr = conn
                        .getStatements(null/* s */, null/* p */, null/* o */,
                                includeInferred, new Resource[] {}/* contexts */);
                try {
                    final File file = new File(kbdir, "data."
                            + format.getDefaultFileExtension()+".gz");
                    System.out.println("Writing " + file);
                    final OutputStream os = new GZIPOutputStream(
                            new FileOutputStream(file));
                    try {
                        final RDFWriter writer = RDFWriterRegistry
                                .getInstance().get(format).getWriter(os);
                        writer.startRDF();
                        while (itr.hasNext()) {
                            final Statement stmt = itr.next();
                            writer.handleStatement(stmt);
                        }
                        writer.endRDF();
                    } finally {
                        os.close();
                    }
                } finally {
                    itr.close();
                }
//            } finally {
//                conn.close();
//            }
//        } finally {
//            sail.shutDown();
//        }

    }
 
Example #9
Source File: BigdataRDFContext.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void doQuery(final BigdataSailRepositoryConnection cxn,
		final OutputStream os) throws Exception {

          final BigdataSailGraphQuery query = (BigdataSailGraphQuery) setupQuery(cxn);

          // Note: getQueryTask() verifies that format will be non-null.
          final RDFFormat format = RDFWriterRegistry.getInstance()
                  .getFileFormatForMIMEType(mimeType);

          final RDFWriter w = RDFWriterRegistry.getInstance().get(format)
                  .getWriter(os);

       query.evaluate(w);
       
      }
 
Example #10
Source File: QueryServlet.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Void call() throws Exception {

  BigdataSailRepositoryConnection conn = null;
  
  try {

      conn = getQueryConnection();

      String mimeType = null;
      RDFFormat format = null;
      if (mimeTypes!=null) {
          mimeTypesLoop:
      	while(mimeTypes.hasMoreElements()) {
          	for (String mt:mimeTypes.nextElement().split(",")) {
          		mt = mt.trim();
               RDFFormat fmt = RDFWriterRegistry.getInstance()
                   .getFileFormatForMIMEType(mt);
               if (conn.getTripleStore().isQuads() && (mt.equals(RDFFormat.NQUADS.getDefaultMIMEType()) || mt.equals(RDFFormat.TURTLE.getDefaultMIMEType())) || !conn.getTripleStore().isQuads() && fmt != null) {
                   mimeType = mt;
                   format = fmt;
                   break mimeTypesLoop;
               }
          	}
          }
      }
      if (format==null) {
          if(conn.getTripleStore().isQuads()){
              mimeType = RDFFormat.NQUADS.getDefaultMIMEType();
          } else {
              mimeType = RDFFormat.NTRIPLES.getDefaultMIMEType();
          }
          format = RDFWriterRegistry.getInstance()
              .getFileFormatForMIMEType(mimeType);
      }
      resp.setContentType(mimeType);

      final OutputStream os = resp.getOutputStream();

      final RDFWriter w = RDFWriterRegistry.getInstance().get(format)
          .getWriter(os);

      RepositoryResult<Statement> stmts = null;

      try {
          w.startRDF();
          stmts = conn.getStatements(s, p, o, includeInferred, c);
          while(stmts.hasNext()){
              w.handleStatement(stmts.next());
          }
          w.endRDF();
      } finally {
          if (stmts != null) {
              stmts.close();
          }
          os.flush();
          os.close();
      }

      return null;
  } finally {
      if (conn != null) {
          conn.close();
      }
  }
}
 
Example #11
Source File: BigdataRDFServlet.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
     * Send an RDF Graph as a response using content negotiation.
     * 
     * @param req
     * @param resp
     */
    static public void sendGraph(final HttpServletRequest req,
            final HttpServletResponse resp, final Graph g) throws IOException {
        /*
         * CONNEG for the MIME type.
         */
        final List<String> acceptHeaders = Collections.list(req.getHeaders("Accept"));
		final String acceptStr = ConnegUtil.getMimeTypeForQueryParameterQueryRequest(req
				.getParameter(BigdataRDFServlet.OUTPUT_FORMAT_QUERY_PARAMETER),
				acceptHeaders.toArray(new String[acceptHeaders.size()])); 
		
        final ConnegUtil util = new ConnegUtil(acceptStr);

        // The best RDFFormat for that Accept header.
        RDFFormat format = util.getRDFFormat();

        if (format == null)
            format = RDFFormat.RDFXML;

		RDFWriterFactory writerFactory = RDFWriterRegistry.getInstance().get(
				format);

		if (writerFactory == null) {

			if (log.isDebugEnabled()) {
				log.debug("No writer for format: format=" + format
						+ ", Accept=\"" + acceptStr + "\"");
			}

			format = RDFFormat.RDFXML;
			
			writerFactory = RDFWriterRegistry.getInstance().get(format);
			
		}

//        if (writerFactory == null) {
//
//			buildResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN,
//					"No writer for format: Accept=\"" + acceptStr
//							+ "\", format=" + format);
//			
//			return;
//
//		}
		
        resp.setStatus(HTTP_OK);

        resp.setContentType(format.getDefaultMIMEType());

        final OutputStream os = resp.getOutputStream();
        try {
            final RDFWriter writer = writerFactory.getWriter(os);
            writer.startRDF();
            final Iterator<Statement> itr = g.iterator();
            while (itr.hasNext()) {
                final Statement stmt = itr.next();
                writer.handleStatement(stmt);
            }
            writer.endRDF();
            os.flush();
        } catch (RDFHandlerException e) {
        	// wrap and rethrow. will be handled by launderThrowable().
            throw new IOException(e);
        } finally {
            os.close();
        }
    }
 
Example #12
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Generates some statements and serializes them using the specified
 * {@link RDFFormat}.
 * 
 * @param ntriples
 *            The #of statements to generate.
 * @param format
 *            The format.
 * 
 * @return the serialized statements.
 */
protected byte[] genNTRIPLES(final int ntriples, final RDFFormat format)
        throws RDFHandlerException {

    final Graph g = genNTRIPLES2(ntriples);
    
    final RDFWriterFactory writerFactory = RDFWriterRegistry.getInstance()
            .get(format);

    if (writerFactory == null)
        fail("RDFWriterFactory not found: format=" + format);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    final RDFWriter writer = writerFactory.getWriter(baos);

    writer.startRDF();

    for (Statement stmt : g) {

        writer.handleStatement(stmt);

    }

    writer.endRDF();

    return baos.toByteArray();
    
}
 
Example #13
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Write a graph on a buffer suitable for sending as an HTTP request body.
 * 
 * @param format
 *            The RDF Format to use.
 * @param g
 *            The graph.
 *            
 * @return The serialized data.
 * 
 * @throws RDFHandlerException
 */
static protected byte[] writeOnBuffer(final RDFFormat format, final Graph g)
        throws RDFHandlerException {

    final RDFWriterFactory writerFactory = RDFWriterRegistry.getInstance()
            .get(format);

    if (writerFactory == null)
        fail("RDFWriterFactory not found: format=" + format);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    final RDFWriter writer = writerFactory.getWriter(baos);

    writer.startRDF();

    for (Statement stmt : g) {

        writer.handleStatement(stmt);

    }

    writer.endRDF();

    return baos.toByteArray();

}
 
Example #14
Source File: SPARQLQuery.java    From neo4j-sparql-extension with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Returns a {@link RDFWriterFactory} that produces RDF data according to a
 * given MIME-type.
 *
 * @param mimetype the mimetype
 * @return the corresponding writer factory
 */
private RDFWriterFactory getRDFWriterFactory(String mimetype) {
	RDFWriterRegistry registry = RDFWriterRegistry.getInstance();
	return registry.get(getRDFFormat(mimetype));
}