Search in sources :

Example 1 with RDFHandler

use of org.eclipse.rdf4j.rio.RDFHandler in project incubator-rya by apache.

the class RdfController method queryRdf.

@RequestMapping(value = "/queryrdf", method = { RequestMethod.GET, RequestMethod.POST })
public void queryRdf(@RequestParam("query") final String query, @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_QUERY_AUTH, required = false) String auth, @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_CV, required = false) final String vis, @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_INFER, required = false) final String infer, @RequestParam(value = "nullout", required = false) final String nullout, @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_RESULT_FORMAT, required = false) final String emit, @RequestParam(value = "padding", required = false) final String padding, @RequestParam(value = "callback", required = false) final String callback, final HttpServletRequest request, final HttpServletResponse response) {
    // WARNING: if you add to the above request variables,
    // Be sure to validate and encode since they come from the outside and could contain odd damaging character sequences.
    SailRepositoryConnection conn = null;
    final Thread queryThread = Thread.currentThread();
    auth = StringUtils.arrayToCommaDelimitedString(provider.getUserAuths(request));
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            log.debug("interrupting");
            queryThread.interrupt();
        }
    }, QUERY_TIME_OUT_SECONDS * 1000);
    try {
        final ServletOutputStream os = response.getOutputStream();
        conn = repository.getConnection();
        final Boolean isBlankQuery = StringUtils.isEmpty(query);
        final ParsedOperation operation = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, query, null);
        final Boolean requestedCallback = !StringUtils.isEmpty(callback);
        final Boolean requestedFormat = !StringUtils.isEmpty(emit);
        if (!isBlankQuery) {
            if (operation instanceof ParsedGraphQuery) {
                // Perform Graph Query
                final RDFHandler handler = new RDFXMLWriter(os);
                response.setContentType("text/xml");
                performGraphQuery(query, conn, auth, infer, nullout, handler);
            } else if (operation instanceof ParsedTupleQuery) {
                // Perform Tuple Query
                TupleQueryResultHandler handler;
                if (requestedFormat && emit.equalsIgnoreCase("json")) {
                    handler = new SPARQLResultsJSONWriter(os);
                    response.setContentType("application/json");
                } else {
                    handler = new SPARQLResultsXMLWriter(os);
                    response.setContentType("text/xml");
                }
                performQuery(query, conn, auth, infer, nullout, handler);
            } else if (operation instanceof ParsedUpdate) {
                // Perform Update Query
                performUpdate(query, conn, os, infer, vis);
            } else {
                throw new MalformedQueryException("Cannot process query. Query type not supported.");
            }
        }
        if (requestedCallback) {
            os.print(")");
        }
    } catch (final Exception e) {
        log.error("Error running query", e);
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (final RepositoryException e) {
                log.error("Error closing connection", e);
            }
        }
    }
    timer.cancel();
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ParsedGraphQuery(org.eclipse.rdf4j.query.parser.ParsedGraphQuery) RepositoryException(org.eclipse.rdf4j.repository.RepositoryException) SailRepositoryConnection(org.eclipse.rdf4j.repository.sail.SailRepositoryConnection) SPARQLResultsJSONWriter(org.eclipse.rdf4j.query.resultio.sparqljson.SPARQLResultsJSONWriter) ParsedOperation(org.eclipse.rdf4j.query.parser.ParsedOperation) QueryEvaluationException(org.eclipse.rdf4j.query.QueryEvaluationException) RDFParseException(org.eclipse.rdf4j.rio.RDFParseException) RepositoryException(org.eclipse.rdf4j.repository.RepositoryException) UpdateExecutionException(org.eclipse.rdf4j.query.UpdateExecutionException) MalformedQueryException(org.eclipse.rdf4j.query.MalformedQueryException) TupleQueryResultHandlerException(org.eclipse.rdf4j.query.TupleQueryResultHandlerException) QueryResultHandlerException(org.eclipse.rdf4j.query.QueryResultHandlerException) RDFHandlerException(org.eclipse.rdf4j.rio.RDFHandlerException) IOException(java.io.IOException) SPARQLResultsXMLWriter(org.eclipse.rdf4j.query.resultio.sparqlxml.SPARQLResultsXMLWriter) ParsedUpdate(org.eclipse.rdf4j.query.parser.ParsedUpdate) Timer(java.util.Timer) TimerTask(java.util.TimerTask) RDFXMLWriter(org.eclipse.rdf4j.rio.rdfxml.RDFXMLWriter) MalformedQueryException(org.eclipse.rdf4j.query.MalformedQueryException) TupleQueryResultHandler(org.eclipse.rdf4j.query.TupleQueryResultHandler) RDFHandler(org.eclipse.rdf4j.rio.RDFHandler) ParsedTupleQuery(org.eclipse.rdf4j.query.parser.ParsedTupleQuery) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with RDFHandler

use of org.eclipse.rdf4j.rio.RDFHandler in project incubator-rya by apache.

the class RdfController method performGraphQuery.

private void performGraphQuery(final String query, final RepositoryConnection conn, final String auth, final String infer, final String nullout, final RDFHandler handler) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFHandlerException {
    final GraphQuery graphQuery = conn.prepareGraphQuery(QueryLanguage.SPARQL, query);
    if (auth != null && auth.length() > 0) {
        graphQuery.setBinding(RdfCloudTripleStoreConfiguration.CONF_QUERY_AUTH, VALUE_FACTORY.createLiteral(auth));
    }
    if (infer != null && infer.length() > 0) {
        graphQuery.setBinding(RdfCloudTripleStoreConfiguration.CONF_INFER, VALUE_FACTORY.createLiteral(Boolean.parseBoolean(infer)));
    }
    if (nullout != null && nullout.length() > 0) {
        // output nothing, but still run query
        // TODO this seems like a strange use case.
        graphQuery.evaluate(new RDFHandler() {

            @Override
            public void startRDF() throws RDFHandlerException {
            }

            @Override
            public void endRDF() throws RDFHandlerException {
            }

            @Override
            public void handleNamespace(final String prefix, final String uri) throws RDFHandlerException {
            }

            @Override
            public void handleStatement(final Statement st) throws RDFHandlerException {
            }

            @Override
            public void handleComment(final String comment) throws RDFHandlerException {
            }
        });
    } else {
        final long startTime = System.currentTimeMillis();
        graphQuery.evaluate(handler);
        log.info(String.format("Query Time = %.3f\n", (System.currentTimeMillis() - startTime) / 1000.));
    }
}
Also used : RDFHandlerException(org.eclipse.rdf4j.rio.RDFHandlerException) Statement(org.eclipse.rdf4j.model.Statement) ParsedGraphQuery(org.eclipse.rdf4j.query.parser.ParsedGraphQuery) GraphQuery(org.eclipse.rdf4j.query.GraphQuery) RDFHandler(org.eclipse.rdf4j.rio.RDFHandler)

Example 3 with RDFHandler

use of org.eclipse.rdf4j.rio.RDFHandler in project termit by kbss-cvut.

the class DataDao method exportDataAsTurtle.

/**
 * Exports the specified repository contexts as Turtle.
 *
 * @param contexts The contexts to export, possibly empty (in which case the default context is exported)
 * @return Resource containing the exported data in Turtle
 */
public TypeAwareResource exportDataAsTurtle(URI... contexts) {
    final org.eclipse.rdf4j.repository.Repository repo = em.unwrap(org.eclipse.rdf4j.repository.Repository.class);
    try (final RepositoryConnection con = repo.getConnection()) {
        final ValueFactory vf = con.getValueFactory();
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        RDFHandler writer = Rio.createWriter(RDFFormat.TURTLE, bos);
        con.export(writer, Arrays.stream(contexts).map(u -> vf.createIRI(u.toString())).toArray(Resource[]::new));
        return new TypeAwareByteArrayResource(bos.toByteArray(), Turtle.MEDIA_TYPE, Turtle.FILE_EXTENSION);
    }
}
Also used : RepositoryConnection(org.eclipse.rdf4j.repository.RepositoryConnection) Resource(org.eclipse.rdf4j.model.Resource) TypeAwareResource(cz.cvut.kbss.termit.util.TypeAwareResource) TypeAwareByteArrayResource(cz.cvut.kbss.termit.service.export.util.TypeAwareByteArrayResource) RdfsResource(cz.cvut.kbss.termit.dto.RdfsResource) ValueFactory(org.eclipse.rdf4j.model.ValueFactory) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TypeAwareByteArrayResource(cz.cvut.kbss.termit.service.export.util.TypeAwareByteArrayResource) RDFHandler(org.eclipse.rdf4j.rio.RDFHandler)

Example 4 with RDFHandler

use of org.eclipse.rdf4j.rio.RDFHandler in project commons-rdf by apache.

the class RDF4JParser method parseSynchronusly.

@Override
protected void parseSynchronusly() throws IOException {
    final Optional<RDFFormat> formatByMimeType = getContentType().flatMap(Rio::getParserFormatForMIMEType);
    final String base = getBase().map(IRI::getIRIString).orElse(null);
    final ParserConfig parserConfig = getParserConfig();
    // TODO: Should we need to set anything?
    final RDFLoader loader = new RDFLoader(parserConfig, rdf4jTermFactory.getValueFactory());
    final RDFHandler rdfHandler = makeRDFHandler();
    if (getSourceFile().isPresent()) {
        // NOTE: While we could have used
        // loader.load(sourcePath.toFile()
        // if the path fs provider == FileSystems.getDefault(),
        // that RDFLoader method does not use absolute path
        // as the base URI, so to be consistent
        // we'll always do it with our own input stream
        // 
        // That means we may have to guess format by extensions:
        final Optional<RDFFormat> formatByFilename = getSourceFile().map(Path::getFileName).map(Path::toString).flatMap(Rio::getParserFormatForFileName);
        // TODO: for the excited.. what about the extension after following
        // symlinks?
        final RDFFormat format = formatByMimeType.orElse(formatByFilename.orElse(null));
        try (InputStream in = Files.newInputStream(getSourceFile().get())) {
            loader.load(in, base, format, rdfHandler);
        }
    } else if (getSourceIri().isPresent()) {
        try {
            // TODO: Handle international IRIs properly
            // (Unicode support for for hostname, path and query)
            final URL url = new URL(getSourceIri().get().getIRIString());
            // TODO: This probably does not support https:// -> http://
            // redirections
            loader.load(url, base, formatByMimeType.orElse(null), makeRDFHandler());
        } catch (final MalformedURLException ex) {
            throw new IOException("Can't handle source URL: " + getSourceIri().get(), ex);
        }
    }
    // must be getSourceInputStream then, this is guaranteed by
    // super.checkSource();
    loader.load(getSourceInputStream().get(), base, formatByMimeType.orElse(null), rdfHandler);
}
Also used : Path(java.nio.file.Path) MalformedURLException(java.net.MalformedURLException) InputStream(java.io.InputStream) Rio(org.eclipse.rdf4j.rio.Rio) IOException(java.io.IOException) ParserConfig(org.eclipse.rdf4j.rio.ParserConfig) RDFLoader(org.eclipse.rdf4j.repository.util.RDFLoader) URL(java.net.URL) RDFFormat(org.eclipse.rdf4j.rio.RDFFormat) AbstractRDFHandler(org.eclipse.rdf4j.rio.helpers.AbstractRDFHandler) RDFHandler(org.eclipse.rdf4j.rio.RDFHandler)

Aggregations

RDFHandler (org.eclipse.rdf4j.rio.RDFHandler)4 IOException (java.io.IOException)2 ParsedGraphQuery (org.eclipse.rdf4j.query.parser.ParsedGraphQuery)2 RDFHandlerException (org.eclipse.rdf4j.rio.RDFHandlerException)2 RdfsResource (cz.cvut.kbss.termit.dto.RdfsResource)1 TypeAwareByteArrayResource (cz.cvut.kbss.termit.service.export.util.TypeAwareByteArrayResource)1 TypeAwareResource (cz.cvut.kbss.termit.util.TypeAwareResource)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 InputStream (java.io.InputStream)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 Path (java.nio.file.Path)1 Timer (java.util.Timer)1 TimerTask (java.util.TimerTask)1 ServletOutputStream (javax.servlet.ServletOutputStream)1 Resource (org.eclipse.rdf4j.model.Resource)1 Statement (org.eclipse.rdf4j.model.Statement)1 ValueFactory (org.eclipse.rdf4j.model.ValueFactory)1 GraphQuery (org.eclipse.rdf4j.query.GraphQuery)1 MalformedQueryException (org.eclipse.rdf4j.query.MalformedQueryException)1