Search in sources :

Example 1 with HttpResponseWrapper

use of org.exist.http.servlets.HttpResponseWrapper 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 HttpResponseWrapper

use of org.exist.http.servlets.HttpResponseWrapper 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 3 with HttpResponseWrapper

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

the class Forward method doRewrite.

@Override
public void doRewrite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    final RequestDispatcher dispatcher = getRequestDispatcher(request);
    if (dispatcher == null) {
        throw new ServletException("Failed to initialize request dispatcher to forward request to " + uri);
    }
    setHeaders(new HttpResponseWrapper(response));
    dispatcher.forward(request, response);
}
Also used : ServletException(javax.servlet.ServletException) HttpResponseWrapper(org.exist.http.servlets.HttpResponseWrapper) RequestDispatcher(javax.servlet.RequestDispatcher)

Example 4 with HttpResponseWrapper

use of org.exist.http.servlets.HttpResponseWrapper 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)

Example 5 with HttpResponseWrapper

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

the class Redirect method doRewrite.

@Override
public void doRewrite(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    setHeaders(new HttpResponseWrapper(response));
    response.sendRedirect(target);
}
Also used : HttpResponseWrapper(org.exist.http.servlets.HttpResponseWrapper)

Aggregations

HttpResponseWrapper (org.exist.http.servlets.HttpResponseWrapper)5 HttpRequestWrapper (org.exist.http.servlets.HttpRequestWrapper)3 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)2 PermissionDeniedException (org.exist.security.PermissionDeniedException)2 SAXException (org.xml.sax.SAXException)2 Matcher (java.util.regex.Matcher)1 RequestDispatcher (javax.servlet.RequestDispatcher)1 ServletException (javax.servlet.ServletException)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 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 SAXParseException (org.xml.sax.SAXParseException)1