Search in sources :

Example 1 with IndentedWriter

use of org.apache.jena.atlas.io.IndentedWriter in project jena by apache.

the class UpdateValidator method execute.

//static final String paramSyntaxExtended   = "extendedSyntax" ;
@Override
protected void execute(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
        //            if ( log.isInfoEnabled() )
        //                log.info("validation request") ;
        String[] args = httpRequest.getParameterValues(paramUpdate);
        if (args == null || args.length == 0) {
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "No update parameter to validator");
            return;
        }
        if (args.length > 1) {
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Too many update parameters");
            return;
        }
        final String updateString = httpRequest.getParameter(paramUpdate).replaceAll("(\r|\n| )*$", "");
        String updateSyntax = httpRequest.getParameter(paramSyntax);
        if (updateSyntax == null || updateSyntax.equals(""))
            updateSyntax = "SPARQL";
        Syntax language = Syntax.lookup(updateSyntax);
        if (language == null) {
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown syntax: " + updateSyntax);
            return;
        }
        String lineNumbersArg = httpRequest.getParameter(paramLineNumbers);
        String[] a = httpRequest.getParameterValues(paramFormat);
        // Currently default.
        boolean outputSPARQL = true;
        boolean lineNumbers = true;
        if (lineNumbersArg != null)
            lineNumbers = lineNumbersArg.equalsIgnoreCase("true") || lineNumbersArg.equalsIgnoreCase("yes");
        // Headers
        setHeaders(httpResponse);
        ServletOutputStream outStream = httpResponse.getOutputStream();
        outStream.println("<html>");
        printHead(outStream, "SPARQL Update Validation Report");
        outStream.println("<body>");
        outStream.println("<h1>SPARQL Update Validator</h1>");
        // Print as received
        {
            outStream.println("<p>Input:</p>");
            // Not Java's finest hour.
            Content c = new Content() {

                @Override
                public void print(IndentedWriter out) {
                    out.print(updateString);
                }
            };
            output(outStream, c, lineNumbers);
        }
        // Attempt to parse it.
        UpdateRequest request = null;
        try {
            request = UpdateFactory.create(updateString, "http://example/base/", language);
        } catch (ARQException ex) {
            // Over generous exception (should be QueryException)
            // but this makes the code robust.
            outStream.println("<p>Syntax error:</p>");
            startFixed(outStream);
            outStream.println(ex.getMessage());
            finishFixed(outStream);
        } catch (RuntimeException ex) {
            outStream.println("<p>Internal error:</p>");
            startFixed(outStream);
            outStream.println(ex.getMessage());
            finishFixed(outStream);
        }
        // Because we pass into anon inner classes
        final UpdateRequest updateRequest = request;
        // OK?  Pretty print
        if (updateRequest != null && outputSPARQL) {
            outStream.println("<p>Formatted, parsed update request:</p>");
            Content c = new Content() {

                @Override
                public void print(IndentedWriter out) {
                    updateRequest.output(out);
                }
            };
            output(outStream, c, lineNumbers);
        }
        outStream.println("</body>");
        outStream.println("</html>");
    } catch (Exception ex) {
        serviceLog.warn("Exception in doGet", ex);
    }
}
Also used : IndentedWriter(org.apache.jena.atlas.io.IndentedWriter) ServletOutputStream(javax.servlet.ServletOutputStream) UpdateRequest(org.apache.jena.update.UpdateRequest) ARQException(org.apache.jena.sparql.ARQException) Syntax(org.apache.jena.query.Syntax) ARQException(org.apache.jena.sparql.ARQException) IOException(java.io.IOException)

Example 2 with IndentedWriter

use of org.apache.jena.atlas.io.IndentedWriter in project jena by apache.

the class QueryValidator method execute.

//static final String paramSyntaxExtended   = "extendedSyntax" ;
@Override
protected void execute(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
        //            if ( log.isInfoEnabled() )
        //                log.info("validation request") ;
        String[] args = httpRequest.getParameterValues(paramQuery);
        if (args == null || args.length == 0) {
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "No query parameter to validator");
            return;
        }
        if (args.length > 1) {
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Too many query parameters");
            return;
        }
        final String queryString = httpRequest.getParameter(paramQuery).replaceAll("(\r|\n| )*$", "");
        //            queryString = queryString.replace("\r\n", "\n") ;
        //            queryString.replaceAll("(\r|\n| )*$", "") ;
        String querySyntax = httpRequest.getParameter(paramSyntax);
        if (querySyntax == null || querySyntax.equals(""))
            querySyntax = "SPARQL";
        Syntax language = Syntax.lookup(querySyntax);
        if (language == null) {
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown syntax: " + querySyntax);
            return;
        }
        String lineNumbersArg = httpRequest.getParameter(paramLineNumbers);
        String[] a = httpRequest.getParameterValues(paramFormat);
        boolean outputSPARQL = false;
        boolean outputPrefix = false;
        boolean outputAlgebra = false;
        boolean outputQuads = false;
        boolean outputOptimized = false;
        boolean outputOptimizedQuads = false;
        if (a != null) {
            for (String anA : a) {
                if (anA.equals("sparql")) {
                    outputSPARQL = true;
                }
                if (anA.equals("prefix")) {
                    outputPrefix = true;
                }
                if (anA.equals("algebra")) {
                    outputAlgebra = true;
                }
                if (anA.equals("quads")) {
                    outputQuads = true;
                }
                if (anA.equals("opt")) {
                    outputOptimized = true;
                }
                if (anA.equals("optquads")) {
                    outputOptimizedQuads = true;
                }
            }
        }
        //            if ( ! outputSPARQL && ! outputPrefix )
        //                outputSPARQL = true ;
        boolean lineNumbers = true;
        if (lineNumbersArg != null)
            lineNumbers = lineNumbersArg.equalsIgnoreCase("true") || lineNumbersArg.equalsIgnoreCase("yes");
        // Headers
        setHeaders(httpResponse);
        ServletOutputStream outStream = httpResponse.getOutputStream();
        outStream.println("<html>");
        printHead(outStream, "SPARQL Query Validation Report");
        outStream.println("<body>");
        outStream.println("<h1>SPARQL Query Validator</h1>");
        // Print query as received
        {
            outStream.println("<p>Input:</p>");
            // Not Java's finest hour.
            Content c = new Content() {

                @Override
                public void print(IndentedWriter out) {
                    out.print(queryString);
                }
            };
            output(outStream, c, lineNumbers);
        }
        // Attempt to parse it.
        Query query = null;
        try {
            query = QueryFactory.create(queryString, "http://example/base/", language);
        } catch (ARQException ex) {
            // Over generous exception (should be QueryException)
            // but this makes the code robust.
            outStream.println("<p>Syntax error:</p>");
            startFixed(outStream);
            outStream.println(ex.getMessage());
            finishFixed(outStream);
        } catch (RuntimeException ex) {
            outStream.println("<p>Internal error:</p>");
            startFixed(outStream);
            outStream.println(ex.getMessage());
            finishFixed(outStream);
        }
        if (query != null) {
            if (outputSPARQL)
                outputSyntax(outStream, query, lineNumbers);
            if (outputAlgebra)
                outputAlgebra(outStream, query, lineNumbers);
            if (outputQuads)
                outputAlgebraQuads(outStream, query, lineNumbers);
            if (outputOptimized)
                outputAlgebraOpt(outStream, query, lineNumbers);
            if (outputOptimizedQuads)
                outputAlgebraOptQuads(outStream, query, lineNumbers);
        }
        outStream.println("</body>");
        outStream.println("</html>");
    } catch (Exception ex) {
        serviceLog.warn("Exception in doGet", ex);
    }
}
Also used : IndentedWriter(org.apache.jena.atlas.io.IndentedWriter) Query(org.apache.jena.query.Query) ServletOutputStream(javax.servlet.ServletOutputStream) ARQException(org.apache.jena.sparql.ARQException) Syntax(org.apache.jena.query.Syntax) ARQException(org.apache.jena.sparql.ARQException) IOException(java.io.IOException)

Example 3 with IndentedWriter

use of org.apache.jena.atlas.io.IndentedWriter in project jena by apache.

the class query method queryExec.

protected void queryExec(boolean timed, ResultsFormat fmt) {
    try {
        Query query = modQuery.getQuery();
        if (isVerbose()) {
            IndentedWriter out = new IndentedWriter(System.out, true);
            query.serialize(out);
            out.flush();
            System.out.println();
        }
        if (isQuiet())
            LogCtl.setError(SysRIOT.riotLoggerName);
        Dataset dataset = getDataset(query);
        // The default policy is to create an empty one - convenience for VALUES and BIND providing the data.
        if (dataset == null && !query.hasDatasetDescription()) {
            System.err.println("Dataset not specified in query nor provided on command line.");
            throw new TerminationException(1);
        }
        Transactional transactional = (dataset != null && dataset.supportsTransactionAbort()) ? dataset : new TransactionalNull();
        Txn.executeRead(transactional, () -> {
            modTime.startTimer();
            try (QueryExecution qe = QueryExecutionFactory.create(query, dataset)) {
                try {
                    QueryExecUtils.executeQuery(query, qe, fmt);
                } catch (QueryCancelledException ex) {
                    System.out.flush();
                    System.err.println("Query timed out");
                }
                long time = modTime.endTimer();
                if (timed) {
                    totalTime += time;
                    System.err.println("Time: " + modTime.timeStr(time) + " sec");
                }
            } catch (ResultSetException ex) {
                System.err.println(ex.getMessage());
                ex.printStackTrace(System.err);
            } catch (QueryException qEx) {
                // System.err.println(qEx.getMessage()) ;
                throw new CmdException("Query Exeception", qEx);
            }
        });
    } catch (ARQInternalErrorException intEx) {
        System.err.println(intEx.getMessage());
        if (intEx.getCause() != null) {
            System.err.println("Cause:");
            intEx.getCause().printStackTrace(System.err);
            System.err.println();
        }
        intEx.printStackTrace(System.err);
    } catch (JenaException | CmdException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new CmdException("Exception", ex);
    }
}
Also used : CmdException(jena.cmd.CmdException) ARQInternalErrorException(org.apache.jena.sparql.ARQInternalErrorException) ARQInternalErrorException(org.apache.jena.sparql.ARQInternalErrorException) RiotException(org.apache.jena.riot.RiotException) ResultSetException(org.apache.jena.sparql.resultset.ResultSetException) CmdException(jena.cmd.CmdException) TerminationException(jena.cmd.TerminationException) JenaException(org.apache.jena.shared.JenaException) RiotNotFoundException(org.apache.jena.riot.RiotNotFoundException) IndentedWriter(org.apache.jena.atlas.io.IndentedWriter) JenaException(org.apache.jena.shared.JenaException) TerminationException(jena.cmd.TerminationException) ResultSetException(org.apache.jena.sparql.resultset.ResultSetException) TransactionalNull(org.apache.jena.sparql.core.TransactionalNull) Transactional(org.apache.jena.sparql.core.Transactional)

Example 4 with IndentedWriter

use of org.apache.jena.atlas.io.IndentedWriter in project jena by apache.

the class ResultSetFormatter method output.

/**
 * Output an iterator of JSON values.
 *
 * @param outStream output stream
 * @param jsonItems The JSON values
 */
public static void output(OutputStream outStream, Iterator<JsonObject> jsonItems) {
    IndentedWriter out = new IndentedWriter(outStream);
    out.println("[");
    out.incIndent();
    while (jsonItems.hasNext()) {
        JsonObject jsonItem = jsonItems.next();
        jsonItem.output(out);
        if (jsonItems.hasNext())
            out.println(" ,");
        else
            out.println();
    }
    out.decIndent();
    out.println("]");
    out.flush();
}
Also used : IndentedWriter(org.apache.jena.atlas.io.IndentedWriter) JsonObject(org.apache.jena.atlas.json.JsonObject)

Example 5 with IndentedWriter

use of org.apache.jena.atlas.io.IndentedWriter in project jena by apache.

the class QueryOutputUtils method printQuery.

public static void printQuery(Query query) {
    IndentedWriter out = IndentedWriter.stdout;
    printQuery(out, query);
}
Also used : IndentedWriter(org.apache.jena.atlas.io.IndentedWriter)

Aggregations

IndentedWriter (org.apache.jena.atlas.io.IndentedWriter)57 SerializationContext (org.apache.jena.sparql.serializer.SerializationContext)5 TerminationException (org.apache.jena.cmd.TerminationException)4 Node (org.apache.jena.graph.Node)4 PrefixMapping (org.apache.jena.shared.PrefixMapping)4 CmdException (org.apache.jena.cmd.CmdException)3 Triple (org.apache.jena.graph.Triple)3 Syntax (org.apache.jena.query.Syntax)3 IOException (java.io.IOException)2 ServletOutputStream (javax.servlet.ServletOutputStream)2 Pair (org.apache.jena.atlas.lib.Pair)2 RiotException (org.apache.jena.riot.RiotException)2 RiotNotFoundException (org.apache.jena.riot.RiotNotFoundException)2 NodeFormatter (org.apache.jena.riot.out.NodeFormatter)2 NodeFormatterTTL (org.apache.jena.riot.out.NodeFormatterTTL)2 JenaException (org.apache.jena.shared.JenaException)2 ARQException (org.apache.jena.sparql.ARQException)2 Var (org.apache.jena.sparql.core.Var)2 Plan (org.apache.jena.sparql.engine.Plan)2 Expr (org.apache.jena.sparql.expr.Expr)2