use of javax.servlet.ServletResponseWrapper in project tomcat70 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"));
}
}
use of javax.servlet.ServletResponseWrapper in project undertow by undertow-io.
the class RequestDispatcherImpl method includeImpl.
private void includeImpl(ServletRequest request, ServletResponse response, ServletRequestContext servletRequestContext, HttpServletRequestImpl requestImpl, HttpServletResponseImpl responseImpl) throws ServletException, IOException {
if (!servletContext.getDeployment().getDeploymentInfo().isAllowNonStandardWrappers()) {
if (servletRequestContext.getOriginalRequest() != request) {
if (!(request instanceof ServletRequestWrapper)) {
throw UndertowServletMessages.MESSAGES.requestWasNotOriginalOrWrapper(request);
}
}
if (servletRequestContext.getOriginalResponse() != response) {
if (!(response instanceof ServletResponseWrapper)) {
throw UndertowServletMessages.MESSAGES.responseWasNotOriginalOrWrapper(response);
}
}
}
final ServletRequest oldRequest = servletRequestContext.getServletRequest();
final ServletResponse oldResponse = servletRequestContext.getServletResponse();
Object requestUri = null;
Object contextPath = null;
Object servletPath = null;
Object pathInfo = null;
Object queryString = null;
Map<String, Deque<String>> queryParameters = requestImpl.getQueryParameters();
if (!named) {
requestUri = request.getAttribute(INCLUDE_REQUEST_URI);
contextPath = request.getAttribute(INCLUDE_CONTEXT_PATH);
servletPath = request.getAttribute(INCLUDE_SERVLET_PATH);
pathInfo = request.getAttribute(INCLUDE_PATH_INFO);
queryString = request.getAttribute(INCLUDE_QUERY_STRING);
int qsPos = path.indexOf("?");
String newServletPath = path;
if (qsPos != -1) {
String newQueryString = newServletPath.substring(qsPos + 1);
newServletPath = newServletPath.substring(0, qsPos);
String encoding = QueryParameterUtils.getQueryParamEncoding(servletRequestContext.getExchange());
Map<String, Deque<String>> newQueryParameters = QueryParameterUtils.mergeQueryParametersWithNewQueryString(queryParameters, newQueryString, encoding);
requestImpl.setQueryParameters(newQueryParameters);
requestImpl.setAttribute(INCLUDE_QUERY_STRING, newQueryString);
} else {
requestImpl.setAttribute(INCLUDE_QUERY_STRING, "");
}
String newRequestUri = servletContext.getContextPath() + newServletPath;
requestImpl.setAttribute(INCLUDE_REQUEST_URI, newRequestUri);
requestImpl.setAttribute(INCLUDE_CONTEXT_PATH, servletContext.getContextPath());
requestImpl.setAttribute(INCLUDE_SERVLET_PATH, pathMatch.getMatched());
requestImpl.setAttribute(INCLUDE_PATH_INFO, pathMatch.getRemaining());
}
boolean inInclude = responseImpl.isInsideInclude();
responseImpl.setInsideInclude(true);
DispatcherType oldDispatcherType = servletRequestContext.getDispatcherType();
ServletContextImpl oldContext = requestImpl.getServletContext();
try {
requestImpl.setServletContext(servletContext);
responseImpl.setServletContext(servletContext);
try {
servletRequestContext.setServletRequest(request);
servletRequestContext.setServletResponse(response);
servletContext.getDeployment().getServletDispatcher().dispatchToServlet(requestImpl.getExchange(), chain, DispatcherType.INCLUDE);
} catch (ServletException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
} finally {
responseImpl.setInsideInclude(inInclude);
requestImpl.setServletContext(oldContext);
responseImpl.setServletContext(oldContext);
servletRequestContext.setServletRequest(oldRequest);
servletRequestContext.setServletResponse(oldResponse);
servletRequestContext.setDispatcherType(oldDispatcherType);
if (!named) {
requestImpl.setAttribute(INCLUDE_REQUEST_URI, requestUri);
requestImpl.setAttribute(INCLUDE_CONTEXT_PATH, contextPath);
requestImpl.setAttribute(INCLUDE_SERVLET_PATH, servletPath);
requestImpl.setAttribute(INCLUDE_PATH_INFO, pathInfo);
requestImpl.setAttribute(INCLUDE_QUERY_STRING, queryString);
requestImpl.setQueryParameters(queryParameters);
}
}
}
use of javax.servlet.ServletResponseWrapper in project undertow by undertow-io.
the class RequestDispatcherImpl method forwardImpl.
private void forwardImpl(ServletRequest request, ServletResponse response, ServletRequestContext servletRequestContext) throws ServletException, IOException {
final HttpServletRequestImpl requestImpl = servletRequestContext.getOriginalRequest();
final HttpServletResponseImpl responseImpl = servletRequestContext.getOriginalResponse();
if (!servletContext.getDeployment().getDeploymentInfo().isAllowNonStandardWrappers()) {
if (servletRequestContext.getOriginalRequest() != request) {
if (!(request instanceof ServletRequestWrapper)) {
throw UndertowServletMessages.MESSAGES.requestWasNotOriginalOrWrapper(request);
}
}
if (servletRequestContext.getOriginalResponse() != response) {
if (!(response instanceof ServletResponseWrapper)) {
throw UndertowServletMessages.MESSAGES.responseWasNotOriginalOrWrapper(response);
}
}
}
response.resetBuffer();
final ServletRequest oldRequest = servletRequestContext.getServletRequest();
final ServletResponse oldResponse = servletRequestContext.getServletResponse();
Map<String, Deque<String>> queryParameters = requestImpl.getQueryParameters();
request.removeAttribute(INCLUDE_REQUEST_URI);
request.removeAttribute(INCLUDE_CONTEXT_PATH);
request.removeAttribute(INCLUDE_SERVLET_PATH);
request.removeAttribute(INCLUDE_PATH_INFO);
request.removeAttribute(INCLUDE_QUERY_STRING);
final String oldURI = requestImpl.getExchange().getRequestURI();
final String oldRequestPath = requestImpl.getExchange().getRequestPath();
final String oldPath = requestImpl.getExchange().getRelativePath();
final ServletPathMatch oldServletPathMatch = requestImpl.getExchange().getAttachment(ServletRequestContext.ATTACHMENT_KEY).getServletPathMatch();
if (!named) {
// only update if this is the first forward
if (request.getAttribute(FORWARD_REQUEST_URI) == null) {
requestImpl.setAttribute(FORWARD_REQUEST_URI, requestImpl.getRequestURI());
requestImpl.setAttribute(FORWARD_CONTEXT_PATH, requestImpl.getContextPath());
requestImpl.setAttribute(FORWARD_SERVLET_PATH, requestImpl.getServletPath());
requestImpl.setAttribute(FORWARD_PATH_INFO, requestImpl.getPathInfo());
requestImpl.setAttribute(FORWARD_QUERY_STRING, requestImpl.getQueryString());
}
int qsPos = path.indexOf("?");
String newServletPath = path;
if (qsPos != -1) {
String newQueryString = newServletPath.substring(qsPos + 1);
newServletPath = newServletPath.substring(0, qsPos);
String encoding = QueryParameterUtils.getQueryParamEncoding(servletRequestContext.getExchange());
Map<String, Deque<String>> newQueryParameters = QueryParameterUtils.mergeQueryParametersWithNewQueryString(queryParameters, newQueryString, encoding);
requestImpl.getExchange().setQueryString(newQueryString);
requestImpl.setQueryParameters(newQueryParameters);
}
String newRequestUri = servletContext.getContextPath() + newServletPath;
requestImpl.getExchange().setRelativePath(newServletPath);
requestImpl.getExchange().setRequestPath(newRequestUri);
requestImpl.getExchange().setRequestURI(newRequestUri);
requestImpl.getExchange().getAttachment(ServletRequestContext.ATTACHMENT_KEY).setServletPathMatch(pathMatch);
requestImpl.setServletContext(servletContext);
responseImpl.setServletContext(servletContext);
}
try {
try {
servletRequestContext.setServletRequest(request);
servletRequestContext.setServletResponse(response);
if (named) {
servletContext.getDeployment().getServletDispatcher().dispatchToServlet(requestImpl.getExchange(), chain, DispatcherType.FORWARD);
} else {
servletContext.getDeployment().getServletDispatcher().dispatchToPath(requestImpl.getExchange(), pathMatch, DispatcherType.FORWARD);
}
// if we are not in an async or error dispatch then we close the response
if (!request.isAsyncStarted()) {
if (response instanceof HttpServletResponseImpl) {
responseImpl.closeStreamAndWriter();
} else {
try {
final PrintWriter writer = response.getWriter();
writer.flush();
writer.close();
} catch (IllegalStateException e) {
final ServletOutputStream outputStream = response.getOutputStream();
outputStream.flush();
outputStream.close();
}
}
}
} catch (ServletException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
} finally {
servletRequestContext.setServletRequest(oldRequest);
servletRequestContext.setServletResponse(oldResponse);
final boolean preservePath = servletRequestContext.getDeployment().getDeploymentInfo().isPreservePathOnForward();
if (preservePath) {
requestImpl.getExchange().setRelativePath(oldPath);
requestImpl.getExchange().getAttachment(ServletRequestContext.ATTACHMENT_KEY).setServletPathMatch(oldServletPathMatch);
requestImpl.getExchange().setRequestPath(oldRequestPath);
requestImpl.getExchange().setRequestURI(oldURI);
}
}
}
use of javax.servlet.ServletResponseWrapper in project openolat by klemens.
the class DefaultDispatcher 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;
boolean debug = log.isDebug();
// Identify the requested resource path
String path = getRelativePath(request);
if (debug) {
if (serveContent)
log.debug("DefaultServlet.serveResource: Serving resource '" + path + "' headers and data");
else
log.debug("DefaultServlet.serveResource: Serving resource '" + path + "' headers only");
}
WebResourceRoot resources = getResources(request);
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("defaultServlet.missingResource");
}
response.sendError(HttpServletResponse.SC_NOT_FOUND, 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 = request.getServletContext().getMimeType(resource.getName());
resource.setMimeType(contentType);
}
// These need to reflect the original resource, not the potentially
// gzip'd 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 gzipped version of the file if present
boolean usingGzippedVersion = false;
if (gzip && !included && resource.isFile() && !path.endsWith(".gz")) {
WebResource gzipResource = resources.getResource(path + ".gz");
if (gzipResource.exists() && gzipResource.isFile()) {
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");
}
if (checkIfGzip(request)) {
response.addHeader("Content-Encoding", "gzip");
resource = gzipResource;
usingGzippedVersion = true;
}
}
}
ArrayList<Range> ranges = null;
long contentLength = -1L;
if (resource.isDirectory()) {
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 (!usingGzippedVersion && ((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 (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)
log.debug("DefaultServlet.serveFile: contentType='" + contentType + "'");
response.setContentType(contentType);
}
if (resource.isFile() && contentLength >= 0 && (!serveContent || ostream != null)) {
if (debug)
log.debug("DefaultServlet.serveFile: contentLength=" + contentLength);
// written to the response.
if (contentWritten == 0) {
response.setContentLengthLong(contentLength);
}
}
InputStream renderResult = null;
if (resource.isDirectory()) {
if (serveContent) {
// Serve the directory browser
// TODO tomcat render(getPathPrefix(request), resource);
renderResult = null;
}
}
// Copy the input stream to our output stream (if requested)
if (serveContent) {
resource.increaseDownloadCount();
try {
response.setBufferSize(output);
} catch (IllegalStateException e) {
// Silent catch
}
if (ostream == null) {
// content directly.
if (resource.isDirectory()) {
// render(getPathPrefix(request), resource);
renderResult = null;
} else {
renderResult = resource.getInputStream();
}
copy(resource, renderResult, writer, encoding);
} else {
// Output is via an InputStream
if (resource.isDirectory()) {
// render(getPathPrefix(request), resource);
renderResult = null;
} else {
renderResult = resource.getInputStream();
}
// the output (this method closes the stream)
if (renderResult != null) {
copy(renderResult, ostream);
}
}
}
} else {
// download counter
resource.increaseDownloadCount();
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)
log.debug("DefaultServlet.serveFile: contentType='" + contentType + "'");
response.setContentType(contentType);
}
if (serveContent) {
try {
response.setBufferSize(output);
} catch (IllegalStateException e) {
// Silent catch
}
if (ostream != null) {
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();
}
}
}
}
}
use of javax.servlet.ServletResponseWrapper in project sling by apache.
the class ExternalServletContextWrapperTest method testUnwrappingWrappedResponse.
/**
* Unwrapping a wrapper response should return in the response.
*/
@Test
public void testUnwrappingWrappedResponse() {
final ServletResponse resp = context.mock(ServletResponse.class);
final ServletResponseWrapper wrapper = new ServletResponseWrapper(resp);
ServletResponse unwrapped = ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletResponse(wrapper);
assertEquals(resp, unwrapped);
}
Aggregations