Search in sources :

Example 71 with ServletResponse

use of javax.servlet.ServletResponse in project tomcat by apache.

the class Response method setResponse.

/**
     * Set a wrapped HttpServletResponse to pass to the application. Components
     * wishing to wrap the response should obtain the response via
     * {@link #getResponse()}, wrap it and then call this method with the
     * wrapped response.
     *
     * @param applicationResponse The wrapped response to pass to the
     *        application
     */
public void setResponse(HttpServletResponse applicationResponse) {
    // Check the wrapper wraps this request
    ServletResponse r = applicationResponse;
    while (r instanceof HttpServletResponseWrapper) {
        r = ((HttpServletResponseWrapper) r).getResponse();
    }
    if (r != facade) {
        throw new IllegalArgumentException(sm.getString("response.illegalWrap"));
    }
    this.applicationResponse = applicationResponse;
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper)

Example 72 with ServletResponse

use of javax.servlet.ServletResponse in project tomcat by apache.

the class DefaultServlet method serveResource.

/**
     * Serve the specified resource, optionally including the data content.
     *
     * @param request  The servlet request we are processing
     * @param response The servlet response we are creating
     * @param content  Should the content be included?
     * @param encoding The encoding to use if it is necessary to access the
     *                 source as characters rather than as bytes
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet-specified error occurs
     */
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content, String encoding) throws IOException, ServletException {
    boolean serveContent = content;
    // Identify the requested resource path
    String path = getRelativePath(request, true);
    if (debug > 0) {
        if (serveContent)
            log("DefaultServlet.serveResource:  Serving resource '" + path + "' headers and data");
        else
            log("DefaultServlet.serveResource:  Serving resource '" + path + "' headers only");
    }
    if (path.length() == 0) {
        // Context root redirect
        doDirectoryRedirect(request, response);
        return;
    }
    WebResource resource = resources.getResource(path);
    if (!resource.exists()) {
        // Check if we're included so we can return the appropriate
        // missing resource name in the error
        String requestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
        if (requestUri == null) {
            requestUri = request.getRequestURI();
        } else {
            // SRV.9.3 says we must throw a FNFE
            throw new FileNotFoundException(sm.getString("defaultServlet.missingResource", requestUri));
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri);
        return;
    }
    if (!resource.canRead()) {
        // Check if we're included so we can return the appropriate
        // missing resource name in the error
        String requestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
        if (requestUri == null) {
            requestUri = request.getRequestURI();
        } else {
            // reasonable
            throw new FileNotFoundException(sm.getString("defaultServlet.missingResource", requestUri));
        }
        response.sendError(HttpServletResponse.SC_FORBIDDEN, requestUri);
        return;
    }
    // ends with "/" or "\", return NOT FOUND
    if (resource.isFile() && (path.endsWith("/") || path.endsWith("\\"))) {
        // Check if we're included so we can return the appropriate
        // missing resource name in the error
        String requestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
        if (requestUri == null) {
            requestUri = request.getRequestURI();
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri);
        return;
    }
    boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;
    boolean included = false;
    // satisfied.
    if (resource.isFile()) {
        // Checking If headers
        included = (request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH) != null);
        if (!included && !isError && !checkIfHeaders(request, response, resource)) {
            return;
        }
    }
    // Find content type.
    String contentType = resource.getMimeType();
    if (contentType == null) {
        contentType = getServletContext().getMimeType(resource.getName());
        resource.setMimeType(contentType);
    }
    // These need to reflect the original resource, not the potentially
    // precompressed version of the resource so get them now if they are going to
    // be needed later
    String eTag = null;
    String lastModifiedHttp = null;
    if (resource.isFile() && !isError) {
        eTag = resource.getETag();
        lastModifiedHttp = resource.getLastModifiedHttp();
    }
    // Serve a precompressed version of the file if present
    boolean usingPrecompressedVersion = false;
    if (compressionFormats.length > 0 && !included && resource.isFile() && !pathEndsWithCompressedExtension(path)) {
        List<PrecompressedResource> precompressedResources = getAvailablePrecompressedResources(path);
        if (!precompressedResources.isEmpty()) {
            Collection<String> varyHeaders = response.getHeaders("Vary");
            boolean addRequired = true;
            for (String varyHeader : varyHeaders) {
                if ("*".equals(varyHeader) || "accept-encoding".equalsIgnoreCase(varyHeader)) {
                    addRequired = false;
                    break;
                }
            }
            if (addRequired) {
                response.addHeader("Vary", "accept-encoding");
            }
            PrecompressedResource bestResource = getBestPrecompressedResource(request, precompressedResources);
            if (bestResource != null) {
                response.addHeader("Content-Encoding", bestResource.format.encoding);
                resource = bestResource.resource;
                usingPrecompressedVersion = true;
            }
        }
    }
    ArrayList<Range> ranges = null;
    long contentLength = -1L;
    if (resource.isDirectory()) {
        if (!path.endsWith("/")) {
            doDirectoryRedirect(request, response);
            return;
        }
        // suppress them
        if (!listings) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
            return;
        }
        contentType = "text/html;charset=UTF-8";
    } else {
        if (!isError) {
            if (useAcceptRanges) {
                // Accept ranges header
                response.setHeader("Accept-Ranges", "bytes");
            }
            // Parse range specifier
            ranges = parseRange(request, response, resource);
            // ETag header
            response.setHeader("ETag", eTag);
            // Last-Modified header
            response.setHeader("Last-Modified", lastModifiedHttp);
        }
        // Get content length
        contentLength = resource.getContentLength();
        // (silent) ISE when setting the output buffer size
        if (contentLength == 0L) {
            serveContent = false;
        }
    }
    ServletOutputStream ostream = null;
    PrintWriter writer = null;
    if (serveContent) {
        // Trying to retrieve the servlet output stream
        try {
            ostream = response.getOutputStream();
        } catch (IllegalStateException e) {
            // trying to serve a text file
            if (!usingPrecompressedVersion && ((contentType == null) || (contentType.startsWith("text")) || (contentType.endsWith("xml")) || (contentType.contains("/javascript")))) {
                writer = response.getWriter();
                // Cannot reliably serve partial content with a Writer
                ranges = FULL;
            } else {
                throw e;
            }
        }
    }
    // Check to see if a Filter, Valve of wrapper has written some content.
    // If it has, disable range requests and setting of a content length
    // since neither can be done reliably.
    ServletResponse r = response;
    long contentWritten = 0;
    while (r instanceof ServletResponseWrapper) {
        r = ((ServletResponseWrapper) r).getResponse();
    }
    if (r instanceof ResponseFacade) {
        contentWritten = ((ResponseFacade) r).getContentWritten();
    }
    if (contentWritten > 0) {
        ranges = FULL;
    }
    if (resource.isDirectory() || isError || ((ranges == null || ranges.isEmpty()) && request.getHeader("Range") == null) || ranges == FULL) {
        // Set the appropriate output headers
        if (contentType != null) {
            if (debug > 0)
                log("DefaultServlet.serveFile:  contentType='" + contentType + "'");
            response.setContentType(contentType);
        }
        if (resource.isFile() && contentLength >= 0 && (!serveContent || ostream != null)) {
            if (debug > 0)
                log("DefaultServlet.serveFile:  contentLength=" + contentLength);
            // written to the response.
            if (contentWritten == 0) {
                response.setContentLengthLong(contentLength);
            }
        }
        if (serveContent) {
            try {
                response.setBufferSize(output);
            } catch (IllegalStateException e) {
            // Silent catch
            }
            InputStream renderResult = null;
            if (ostream == null) {
                // content directly.
                if (resource.isDirectory()) {
                    renderResult = render(getPathPrefix(request), resource, encoding);
                } else {
                    renderResult = resource.getInputStream();
                }
                copy(resource, renderResult, writer, encoding);
            } else {
                // Output is via an InputStream
                if (resource.isDirectory()) {
                    renderResult = render(getPathPrefix(request), resource, encoding);
                } else {
                    // Output is content of resource
                    if (!checkSendfile(request, response, resource, contentLength, null)) {
                        // sendfile not possible so check if resource
                        // content is available directly
                        byte[] resourceBody = resource.getContent();
                        if (resourceBody == null) {
                            // Resource content not available, use
                            // inputstream
                            renderResult = resource.getInputStream();
                        } else {
                            // Use the resource content directly
                            ostream.write(resourceBody);
                        }
                    }
                }
                // the output (this method closes the stream)
                if (renderResult != null) {
                    copy(resource, renderResult, ostream);
                }
            }
        }
    } else {
        if ((ranges == null) || (ranges.isEmpty()))
            return;
        // Partial content response.
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        if (ranges.size() == 1) {
            Range range = ranges.get(0);
            response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length);
            long length = range.end - range.start + 1;
            response.setContentLengthLong(length);
            if (contentType != null) {
                if (debug > 0)
                    log("DefaultServlet.serveFile:  contentType='" + contentType + "'");
                response.setContentType(contentType);
            }
            if (serveContent) {
                try {
                    response.setBufferSize(output);
                } catch (IllegalStateException e) {
                // Silent catch
                }
                if (ostream != null) {
                    if (!checkSendfile(request, response, resource, range.end - range.start + 1, range))
                        copy(resource, ostream, range);
                } else {
                    // we should not get here
                    throw new IllegalStateException();
                }
            }
        } else {
            response.setContentType("multipart/byteranges; boundary=" + mimeSeparation);
            if (serveContent) {
                try {
                    response.setBufferSize(output);
                } catch (IllegalStateException e) {
                // Silent catch
                }
                if (ostream != null) {
                    copy(resource, ostream, ranges.iterator(), contentType);
                } else {
                    // we should not get here
                    throw new IllegalStateException();
                }
            }
        }
    }
}
Also used : ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletOutputStream(javax.servlet.ServletOutputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) WebResource(org.apache.catalina.WebResource) ResponseFacade(org.apache.catalina.connector.ResponseFacade) ServletResponseWrapper(javax.servlet.ServletResponseWrapper) PrintWriter(java.io.PrintWriter)

Example 73 with ServletResponse

use of javax.servlet.ServletResponse in project tomcat by apache.

the class ApplicationDispatcher method checkSameObjects.

private void checkSameObjects(ServletRequest appRequest, ServletResponse appResponse) throws ServletException {
    ServletRequest originalRequest = ApplicationFilterChain.getLastServicedRequest();
    ServletResponse originalResponse = ApplicationFilterChain.getLastServicedResponse();
    // Some forwards, eg from valves will not set original values
    if (originalRequest == null || originalResponse == null) {
        return;
    }
    boolean same = false;
    ServletRequest dispatchedRequest = appRequest;
    //find the request that was passed into the service method
    while (originalRequest instanceof ServletRequestWrapper && ((ServletRequestWrapper) originalRequest).getRequest() != null) {
        originalRequest = ((ServletRequestWrapper) originalRequest).getRequest();
    }
    //compare with the dispatched request
    while (!same) {
        if (originalRequest.equals(dispatchedRequest)) {
            same = true;
        }
        if (!same && dispatchedRequest instanceof ServletRequestWrapper) {
            dispatchedRequest = ((ServletRequestWrapper) dispatchedRequest).getRequest();
        } else {
            break;
        }
    }
    if (!same) {
        throw new ServletException(sm.getString("applicationDispatcher.specViolation.request"));
    }
    same = false;
    ServletResponse dispatchedResponse = appResponse;
    //find the response that was passed into the service method
    while (originalResponse instanceof ServletResponseWrapper && ((ServletResponseWrapper) originalResponse).getResponse() != null) {
        originalResponse = ((ServletResponseWrapper) originalResponse).getResponse();
    }
    //compare with the dispatched response
    while (!same) {
        if (originalResponse.equals(dispatchedResponse)) {
            same = true;
        }
        if (!same && dispatchedResponse instanceof ServletResponseWrapper) {
            dispatchedResponse = ((ServletResponseWrapper) dispatchedResponse).getResponse();
        } else {
            break;
        }
    }
    if (!same) {
        throw new ServletException(sm.getString("applicationDispatcher.specViolation.response"));
    }
}
Also used : ServletException(javax.servlet.ServletException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) ServletRequestWrapper(javax.servlet.ServletRequestWrapper) ServletResponseWrapper(javax.servlet.ServletResponseWrapper)

Example 74 with ServletResponse

use of javax.servlet.ServletResponse in project tomcat by apache.

the class ApplicationDispatcher method wrapResponse.

/**
     * Create and return a response wrapper that has been inserted in the
     * appropriate spot in the response chain.
     */
private ServletResponse wrapResponse(State state) {
    // Locate the response we should insert in front of
    ServletResponse previous = null;
    ServletResponse current = state.outerResponse;
    while (current != null) {
        if (state.hresponse == null && (current instanceof HttpServletResponse)) {
            state.hresponse = (HttpServletResponse) current;
            if (// Forward only needs hresponse
            !state.including)
                return null;
        }
        if (!(current instanceof ServletResponseWrapper))
            break;
        if (current instanceof ApplicationHttpResponse)
            break;
        if (current instanceof ApplicationResponse)
            break;
        previous = current;
        current = ((ServletResponseWrapper) current).getResponse();
    }
    // Instantiate a new wrapper at this point and insert it in the chain
    ServletResponse wrapper = null;
    if ((current instanceof ApplicationHttpResponse) || (current instanceof Response) || (current instanceof HttpServletResponse))
        wrapper = new ApplicationHttpResponse((HttpServletResponse) current, state.including);
    else
        wrapper = new ApplicationResponse(current, state.including);
    if (previous == null)
        state.outerResponse = wrapper;
    else
        ((ServletResponseWrapper) previous).setResponse(wrapper);
    state.wrapResponse = wrapper;
    return (wrapper);
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.apache.catalina.connector.Response) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponseWrapper(javax.servlet.ServletResponseWrapper)

Example 75 with ServletResponse

use of javax.servlet.ServletResponse in project tomcat by apache.

the class ApplicationDispatcher method unwrapResponse.

/**
     * Unwrap the response if we have wrapped it.
     */
private void unwrapResponse(State state) {
    if (state.wrapResponse == null)
        return;
    if (state.outerRequest.isAsyncStarted()) {
        if (!state.outerRequest.getAsyncContext().hasOriginalRequestAndResponse()) {
            return;
        }
    }
    ServletResponse previous = null;
    ServletResponse current = state.outerResponse;
    while (current != null) {
        // If we run into the container response we are done
        if ((current instanceof Response) || (current instanceof ResponseFacade))
            break;
        // Remove the current response if it is our wrapper
        if (current == state.wrapResponse) {
            ServletResponse next = ((ServletResponseWrapper) current).getResponse();
            if (previous == null)
                state.outerResponse = next;
            else
                ((ServletResponseWrapper) previous).setResponse(next);
            break;
        }
        // Advance to the next response in the chain
        previous = current;
        current = ((ServletResponseWrapper) current).getResponse();
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.apache.catalina.connector.Response) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) ResponseFacade(org.apache.catalina.connector.ResponseFacade) ServletResponseWrapper(javax.servlet.ServletResponseWrapper)

Aggregations

ServletResponse (javax.servlet.ServletResponse)155 ServletRequest (javax.servlet.ServletRequest)129 HttpServletResponse (javax.servlet.http.HttpServletResponse)104 HttpServletRequest (javax.servlet.http.HttpServletRequest)90 FilterChain (javax.servlet.FilterChain)81 Test (org.junit.Test)76 ServletException (javax.servlet.ServletException)59 IOException (java.io.IOException)57 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)35 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)35 MockFilterChain (org.springframework.mock.web.MockFilterChain)32 Filter (javax.servlet.Filter)28 HttpServletResponseWrapper (javax.servlet.http.HttpServletResponseWrapper)26 Injector (com.google.inject.Injector)25 NestedServletException (org.springframework.web.util.NestedServletException)19 ServletTestUtils.newFakeHttpServletRequest (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest)18 ServletTestUtils.newFakeHttpServletResponse (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse)18 FilterConfig (javax.servlet.FilterConfig)15 ErrorPage (org.springframework.boot.web.server.ErrorPage)15 MockHttpServletRequest (org.springframework.mock.web.test.MockHttpServletRequest)14