Search in sources :

Example 1 with HttpRequestWrapper

use of org.exist.http.servlets.HttpRequestWrapper in project exist by eXist-db.

the class RESTServer method declareVariables.

/**
 * Pass the request, response and session objects to the XQuery context.
 *
 * @param context
 * @param request
 * @param response
 * @throws XPathException
 */
private HttpRequestWrapper declareVariables(final XQueryContext context, final ElementImpl variables, final HttpServletRequest request, final HttpServletResponse response) throws XPathException {
    final HttpRequestWrapper reqw = new HttpRequestWrapper(request, formEncoding, containerEncoding);
    final ResponseWrapper respw = new HttpResponseWrapper(response);
    context.setHttpContext(new XQueryContext.HttpContext(reqw, respw));
    // enable EXQuery Request Module (if present)
    try {
        if (xqueryContextExqueryRequestAttribute != null && cstrHttpServletRequestAdapter != null) {
            final HttpRequest exqueryRequestAdapter = cstrHttpServletRequestAdapter.apply(request, () -> (String) context.getBroker().getConfiguration().getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY));
            if (exqueryRequestAdapter != null) {
                context.setAttribute(xqueryContextExqueryRequestAttribute, exqueryRequestAdapter);
            }
        }
    } catch (final Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("EXQuery Request Module is not present: {}", e.getMessage(), e);
        }
    }
    if (variables != null) {
        declareExternalAndXQJVariables(context, variables);
    }
    return reqw;
}
Also used : HttpRequest(org.exquery.http.HttpRequest) HttpResponseWrapper(org.exist.http.servlets.HttpResponseWrapper) HttpRequestWrapper(org.exist.http.servlets.HttpRequestWrapper) ResponseWrapper(org.exist.http.servlets.ResponseWrapper) HttpResponseWrapper(org.exist.http.servlets.HttpResponseWrapper) PermissionDeniedException(org.exist.security.PermissionDeniedException) XMLStreamException(javax.xml.stream.XMLStreamException) SAXException(org.xml.sax.SAXException) TriggerException(org.exist.collections.triggers.TriggerException) EXistException(org.exist.EXistException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) SAXParseException(org.xml.sax.SAXParseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 2 with HttpRequestWrapper

use of org.exist.http.servlets.HttpRequestWrapper in project exist by eXist-db.

the class RESTServer method executeXQuery.

/**
 * Directly execute an XQuery stored as a binary document in the database.
 *
 * @throws PermissionDeniedException
 */
private void executeXQuery(final DBBroker broker, final Txn transaction, final DocumentImpl resource, final HttpServletRequest request, final HttpServletResponse response, final Properties outputProperties, final String servletPath, final String pathInfo) throws XPathException, BadRequestException, PermissionDeniedException {
    final Source source = new DBSource(broker, (BinaryDocument) resource, true);
    final XQueryPool pool = broker.getBrokerPool().getXQueryPool();
    CompiledXQuery compiled = null;
    try {
        final XQuery xquery = broker.getBrokerPool().getXQueryService();
        compiled = pool.borrowCompiledXQuery(broker, source);
        XQueryContext context;
        if (compiled == null) {
            // special header to indicate that the query is not returned from
            // cache
            response.setHeader("X-XQuery-Cached", "false");
            context = new XQueryContext(broker.getBrokerPool());
        } else {
            response.setHeader("X-XQuery-Cached", "true");
            context = compiled.getContext();
            context.prepareForReuse();
        }
        // TODO: don't hardcode this?
        context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI.append(resource.getCollection().getURI()).toString());
        context.setStaticallyKnownDocuments(new XmldbURI[] { resource.getCollection().getURI() });
        final HttpRequestWrapper reqw = declareVariables(context, null, request, response);
        reqw.setServletPath(servletPath);
        reqw.setPathInfo(pathInfo);
        final long compilationTime;
        if (compiled == null) {
            try {
                final long compilationStart = System.currentTimeMillis();
                compiled = xquery.compile(context, source);
                compilationTime = System.currentTimeMillis() - compilationStart;
            } catch (final IOException e) {
                throw new BadRequestException("Failed to read query from " + resource.getURI(), e);
            }
        } else {
            compilationTime = 0;
        }
        DebuggeeFactory.checkForDebugRequest(request, context);
        boolean wrap = outputProperties.getProperty("_wrap") != null && "yes".equals(outputProperties.getProperty("_wrap"));
        try {
            final long executeStart = System.currentTimeMillis();
            final Sequence result = xquery.execute(broker, compiled, null, outputProperties);
            writeResults(response, broker, transaction, result, -1, 1, false, outputProperties, wrap, compilationTime, System.currentTimeMillis() - executeStart);
        } finally {
            context.runCleanupTasks();
        }
    } finally {
        if (compiled != null) {
            pool.returnCompiledXQuery(source, compiled);
        }
    }
}
Also used : XQueryPool(org.exist.storage.XQueryPool) HttpRequestWrapper(org.exist.http.servlets.HttpRequestWrapper) DBSource(org.exist.source.DBSource) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) DBSource(org.exist.source.DBSource) InputSource(org.xml.sax.InputSource) URLSource(org.exist.source.URLSource)

Example 3 with HttpRequestWrapper

use of org.exist.http.servlets.HttpRequestWrapper in project exist by eXist-db.

the class XQueryURLRewrite method declareVariables.

private void declareVariables(final XQueryContext context, final SourceInfo sourceInfo, final URLRewrite staticRewrite, final String basePath, final RequestWrapper request, final HttpServletResponse response) throws XPathException {
    final HttpRequestWrapper reqw = new HttpRequestWrapper(request, "UTF-8", "UTF-8", false);
    final HttpResponseWrapper respw = new HttpResponseWrapper(response);
    // context.declareNamespace(RequestModule.PREFIX,
    // RequestModule.NAMESPACE_URI);
    context.setHttpContext(new XQueryContext.HttpContext(reqw, respw));
    context.declareVariable("exist:controller", sourceInfo.controllerPath);
    request.setAttribute("$exist:controller", sourceInfo.controllerPath);
    context.declareVariable("exist:root", basePath);
    request.setAttribute("$exist:root", basePath);
    context.declareVariable("exist:context", request.getContextPath());
    request.setAttribute("$exist:context", request.getContextPath());
    final String prefix = staticRewrite == null ? null : staticRewrite.getPrefix();
    context.declareVariable("exist:prefix", prefix == null ? "" : prefix);
    request.setAttribute("$exist:prefix", prefix == null ? "" : prefix);
    String path;
    if (sourceInfo.controllerPath.length() > 0 && !"/".equals(sourceInfo.controllerPath)) {
        path = request.getInContextPath().substring(sourceInfo.controllerPath.length());
    } else {
        path = request.getInContextPath();
    }
    final int p = path.lastIndexOf(';');
    if (p != Constants.STRING_NOT_FOUND) {
        path = path.substring(0, p);
    }
    context.declareVariable("exist:path", path);
    request.setAttribute("$exist:path", path);
    String resource = "";
    final Matcher nameMatcher = NAME_REGEX.matcher(path);
    if (nameMatcher.matches()) {
        resource = nameMatcher.group(1);
    }
    context.declareVariable("exist:resource", resource);
    request.setAttribute("$exist:resource", resource);
    if (LOG.isDebugEnabled()) {
        LOG.debug("\nexist:path = {}\nexist:resource = {}\nexist:controller = {}", path, resource, sourceInfo.controllerPath);
    }
}
Also used : HttpResponseWrapper(org.exist.http.servlets.HttpResponseWrapper) Matcher(java.util.regex.Matcher) HttpRequestWrapper(org.exist.http.servlets.HttpRequestWrapper)

Example 4 with HttpRequestWrapper

use of org.exist.http.servlets.HttpRequestWrapper in project exist by eXist-db.

the class RESTServer method executeXProc.

/**
 * Directly execute an XProc stored as a XML document in the database.
 *
 * @throws PermissionDeniedException
 */
private void executeXProc(final DBBroker broker, final Txn transaction, final DocumentImpl resource, final HttpServletRequest request, final HttpServletResponse response, final Properties outputProperties, final String servletPath, final String pathInfo) throws XPathException, BadRequestException, PermissionDeniedException {
    final URLSource source = new URLSource(this.getClass().getResource("run-xproc.xq"));
    final XQueryPool pool = broker.getBrokerPool().getXQueryPool();
    CompiledXQuery compiled = null;
    try {
        final XQuery xquery = broker.getBrokerPool().getXQueryService();
        compiled = pool.borrowCompiledXQuery(broker, source);
        XQueryContext context;
        if (compiled == null) {
            context = new XQueryContext(broker.getBrokerPool());
        } else {
            context = compiled.getContext();
            context.prepareForReuse();
        }
        context.declareVariable("pipeline", resource.getURI().toString());
        final String stdin = request.getParameter("stdin");
        context.declareVariable("stdin", stdin == null ? "" : stdin);
        final String debug = request.getParameter("debug");
        context.declareVariable("debug", debug == null ? "0" : "1");
        final String bindings = request.getParameter("bindings");
        context.declareVariable("bindings", bindings == null ? "<bindings/>" : bindings);
        final String autobind = request.getParameter("autobind");
        context.declareVariable("autobind", autobind == null ? "0" : "1");
        final String options = request.getParameter("options");
        context.declareVariable("options", options == null ? "<options/>" : options);
        // TODO: don't hardcode this?
        context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI.append(resource.getCollection().getURI()).toString());
        context.setStaticallyKnownDocuments(new XmldbURI[] { resource.getCollection().getURI() });
        final HttpRequestWrapper reqw = declareVariables(context, null, request, response);
        reqw.setServletPath(servletPath);
        reqw.setPathInfo(pathInfo);
        final long compilationTime;
        if (compiled == null) {
            try {
                final long compilationStart = System.currentTimeMillis();
                compiled = xquery.compile(context, source);
                compilationTime = System.currentTimeMillis() - compilationStart;
            } catch (final IOException e) {
                throw new BadRequestException("Failed to read query from " + source.getURL(), e);
            }
        } else {
            compilationTime = 0;
        }
        try {
            final long executeStart = System.currentTimeMillis();
            final Sequence result = xquery.execute(broker, compiled, null, outputProperties);
            writeResults(response, broker, transaction, result, -1, 1, false, outputProperties, false, compilationTime, System.currentTimeMillis() - executeStart);
        } finally {
            context.runCleanupTasks();
        }
    } finally {
        if (compiled != null) {
            pool.returnCompiledXQuery(source, compiled);
        }
    }
}
Also used : XQueryPool(org.exist.storage.XQueryPool) URLSource(org.exist.source.URLSource) HttpRequestWrapper(org.exist.http.servlets.HttpRequestWrapper)

Example 5 with HttpRequestWrapper

use of org.exist.http.servlets.HttpRequestWrapper in project exist by eXist-db.

the class RESTServer method writeResourceAs.

// writes out a resource, uses asMimeType as the specified mime-type or if
// null uses the type of the resource
private void writeResourceAs(final DocumentImpl resource, final DBBroker broker, final Txn transaction, final String stylesheet, final String encoding, String asMimeType, final Properties outputProperties, final HttpServletRequest request, final HttpServletResponse response) throws BadRequestException, PermissionDeniedException, IOException {
    // Do we have permission to read the resource
    if (!resource.getPermissions().validate(broker.getCurrentSubject(), Permission.READ)) {
        throw new PermissionDeniedException("Not allowed to read resource");
    }
    // get the document metadata
    final long lastModified = resource.getLastModified();
    setCreatedAndLastModifiedHeaders(response, resource.getCreated(), lastModified);
    // handle If-Modified-Since request header
    try {
        final long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if (ifModifiedSince > -1) {
            /*
                 a) A date which is later than the server's
                 current time is invalid.
                 */
            if (ifModifiedSince <= System.currentTimeMillis()) {
                /*
                     b) If the variant has been modified since the If-Modified-Since
                     date, the response is exactly the same as for a normal GET.
                     */
                if (lastModified <= ifModifiedSince) {
                    /*
                         c) If the variant has not been modified since a valid If-
                         Modified-Since date, the server SHOULD return a 304 (Not
                         Modified) response.
                         */
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }
            }
        }
    } catch (final IllegalArgumentException iae) {
        LOG.warn("Illegal If-Modified-Since HTTP Header sent on request, ignoring. {}", iae.getMessage(), iae);
    }
    if (resource.getResourceType() == DocumentImpl.BINARY_FILE) {
        if (asMimeType == null) {
            // wasn't a mime-type specified?
            asMimeType = resource.getMimeType();
        }
        if (asMimeType.startsWith("text/")) {
            response.setContentType(asMimeType + "; charset=" + encoding);
        } else {
            response.setContentType(asMimeType);
        }
        // As HttpServletResponse.setContentLength is limited to integers,
        // (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4187336)
        // next sentence:
        // response.setContentLength(resource.getContentLength());
        // must be set so
        response.addHeader("Content-Length", Long.toString(resource.getContentLength()));
        final OutputStream os = response.getOutputStream();
        broker.readBinaryResource((BinaryDocument) resource, os);
        os.flush();
    } else {
        // xml resource
        SAXSerializer sax = null;
        final Serializer serializer = broker.borrowSerializer();
        // setup the http context
        final HttpRequestWrapper reqw = new HttpRequestWrapper(request, formEncoding, containerEncoding);
        final HttpResponseWrapper resw = new HttpResponseWrapper(response);
        serializer.setHttpContext(new XQueryContext.HttpContext(reqw, resw));
        // Serialize the document
        try {
            sax = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
            // use a stylesheet if specified in query parameters
            if (stylesheet != null) {
                serializer.setStylesheet(resource, stylesheet);
            }
            serializer.setProperties(outputProperties);
            serializer.prepareStylesheets(resource);
            if (asMimeType != null) {
                // was a mime-type specified?
                response.setContentType(asMimeType + "; charset=" + encoding);
            } else {
                if (serializer.isStylesheetApplied() || serializer.hasXSLPi(resource) != null) {
                    asMimeType = serializer.getStylesheetProperty(OutputKeys.MEDIA_TYPE);
                    if (!useDynamicContentType || asMimeType == null) {
                        asMimeType = MimeType.HTML_TYPE.getName();
                    }
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("media-type: {}", asMimeType);
                    }
                    response.setContentType(asMimeType + "; charset=" + encoding);
                } else {
                    asMimeType = resource.getMimeType();
                    response.setContentType(asMimeType + "; charset=" + encoding);
                }
            }
            if (asMimeType.equals(MimeType.HTML_TYPE.getName())) {
                outputProperties.setProperty("method", "xhtml");
                outputProperties.setProperty("media-type", "text/html; charset=" + encoding);
                outputProperties.setProperty("indent", "yes");
                outputProperties.setProperty("omit-xml-declaration", "no");
            }
            final OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), encoding);
            sax.setOutput(writer, outputProperties);
            serializer.setSAXHandlers(sax, sax);
            serializer.toSAX(resource);
            writer.flush();
            // DO NOT use in try-write-resources, otherwise ther response stream is always closed, and we can't report the errors
            writer.close();
        } catch (final SAXException saxe) {
            LOG.warn(saxe);
            throw new BadRequestException("Error while serializing XML: " + saxe.getMessage());
        } catch (final TransformerConfigurationException e) {
            LOG.warn(e);
            throw new BadRequestException(e.getMessageAndLocation());
        } finally {
            if (sax != null) {
                SerializerPool.getInstance().returnObject(sax);
            }
            broker.returnSerializer(serializer);
        }
    }
}
Also used : HttpResponseWrapper(org.exist.http.servlets.HttpResponseWrapper) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) SAXException(org.xml.sax.SAXException) HttpRequestWrapper(org.exist.http.servlets.HttpRequestWrapper) PermissionDeniedException(org.exist.security.PermissionDeniedException) SAXSerializer(org.exist.util.serializer.SAXSerializer) XQuerySerializer(org.exist.util.serializer.XQuerySerializer) SAXSerializer(org.exist.util.serializer.SAXSerializer) Serializer(org.exist.storage.serializers.Serializer)

Aggregations

HttpRequestWrapper (org.exist.http.servlets.HttpRequestWrapper)5 HttpResponseWrapper (org.exist.http.servlets.HttpResponseWrapper)3 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)2 PermissionDeniedException (org.exist.security.PermissionDeniedException)2 URLSource (org.exist.source.URLSource)2 XQueryPool (org.exist.storage.XQueryPool)2 SAXException (org.xml.sax.SAXException)2 Matcher (java.util.regex.Matcher)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 XMLStreamException (javax.xml.stream.XMLStreamException)1 EXistException (org.exist.EXistException)1 TriggerException (org.exist.collections.triggers.TriggerException)1 ResponseWrapper (org.exist.http.servlets.ResponseWrapper)1 DBSource (org.exist.source.DBSource)1 Source (org.exist.source.Source)1 StringSource (org.exist.source.StringSource)1 Serializer (org.exist.storage.serializers.Serializer)1 SAXSerializer (org.exist.util.serializer.SAXSerializer)1 XQuerySerializer (org.exist.util.serializer.XQuerySerializer)1 HttpRequest (org.exquery.http.HttpRequest)1