Search in sources :

Example 51 with ServletResponse

use of javax.servlet.ServletResponse in project lucene-solr by apache.

the class DelegationTokenKerberosFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    // HttpClient 4.4.x throws NPE if query string is null and parsed through URLEncodedUtils.
    // See HTTPCLIENT-1746 and HADOOP-12767
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String queryString = httpRequest.getQueryString();
    final String nonNullQueryString = queryString == null ? "" : queryString;
    HttpServletRequest requestNonNullQueryString = new HttpServletRequestWrapper(httpRequest) {

        @Override
        public String getQueryString() {
            return nonNullQueryString;
        }
    };
    // include Impersonator User Name in case someone (e.g. logger) wants it
    FilterChain filterChainWrapper = new FilterChain() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
            HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
            UserGroupInformation ugi = HttpUserGroupInformation.get();
            if (ugi != null && ugi.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.PROXY) {
                UserGroupInformation realUserUgi = ugi.getRealUser();
                if (realUserUgi != null) {
                    httpRequest.setAttribute(KerberosPlugin.IMPERSONATOR_USER_NAME, realUserUgi.getShortUserName());
                }
            }
            filterChain.doFilter(servletRequest, servletResponse);
        }
    };
    super.doFilter(requestNonNullQueryString, response, filterChainWrapper);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) ServletResponse(javax.servlet.ServletResponse) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) FilterChain(javax.servlet.FilterChain) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation) HttpUserGroupInformation(org.apache.hadoop.security.token.delegation.web.HttpUserGroupInformation)

Example 52 with ServletResponse

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

the class ExternalServletContextWrapperTest method testUnwrappingDoubleWrappedResponse.

@Test
public void testUnwrappingDoubleWrappedResponse() {
    final ServletResponse resp = context.mock(ServletResponse.class);
    final ServletResponseWrapper wrapper = new ServletResponseWrapper(resp);
    final ServletResponseWrapper wrapper2 = new ServletResponseWrapper(wrapper);
    ServletResponse unwrapped = ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletResponse(wrapper2);
    assertEquals(resp, unwrapped);
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) ServletResponseWrapper(javax.servlet.ServletResponseWrapper) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) Test(org.junit.Test)

Example 53 with ServletResponse

use of javax.servlet.ServletResponse 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);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) ServletRequestWrapper(javax.servlet.ServletRequestWrapper) IOException(java.io.IOException) Deque(java.util.Deque) ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) DispatcherType(javax.servlet.DispatcherType) ServletResponseWrapper(javax.servlet.ServletResponseWrapper)

Example 54 with ServletResponse

use of javax.servlet.ServletResponse 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);
    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);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) ServletOutputStream(javax.servlet.ServletOutputStream) ServletRequestWrapper(javax.servlet.ServletRequestWrapper) IOException(java.io.IOException) Deque(java.util.Deque) ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) ServletResponseWrapper(javax.servlet.ServletResponseWrapper) PrintWriter(java.io.PrintWriter)

Example 55 with ServletResponse

use of javax.servlet.ServletResponse in project undertow by undertow-io.

the class ServletInitialHandler method handleFirstRequest.

private void handleFirstRequest(final HttpServerExchange exchange, ServletRequestContext servletRequestContext) throws Exception {
    ServletRequest request = servletRequestContext.getServletRequest();
    ServletResponse response = servletRequestContext.getServletResponse();
    //set request attributes from the connector
    //generally this is only applicable if apache is sending AJP_ prefixed environment variables
    Map<String, String> attrs = exchange.getAttachment(HttpServerExchange.REQUEST_ATTRIBUTES);
    if (attrs != null) {
        for (Map.Entry<String, String> entry : attrs.entrySet()) {
            request.setAttribute(entry.getKey(), entry.getValue());
        }
    }
    servletRequestContext.setRunningInsideHandler(true);
    try {
        listeners.requestInitialized(request);
        next.handleRequest(exchange);
        //
        if (servletRequestContext.getErrorCode() > 0) {
            servletRequestContext.getOriginalResponse().doErrorDispatch(servletRequestContext.getErrorCode(), servletRequestContext.getErrorMessage());
        }
    } catch (Throwable t) {
        //by default this will just log the exception
        boolean handled = exceptionHandler.handleThrowable(exchange, request, response, t);
        if (handled) {
            exchange.endExchange();
        } else if (request.isAsyncStarted() || request.getDispatcherType() == DispatcherType.ASYNC) {
            exchange.unDispatch();
            servletRequestContext.getOriginalRequest().getAsyncContextInternal().handleError(t);
        } else {
            if (!exchange.isResponseStarted()) {
                //reset the response
                response.reset();
                exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
                exchange.getResponseHeaders().clear();
                String location = servletContext.getDeployment().getErrorPages().getErrorLocation(t);
                if (location == null) {
                    location = servletContext.getDeployment().getErrorPages().getErrorLocation(StatusCodes.INTERNAL_SERVER_ERROR);
                }
                if (location != null) {
                    RequestDispatcherImpl dispatcher = new RequestDispatcherImpl(location, servletContext);
                    try {
                        dispatcher.error(servletRequestContext, request, response, servletRequestContext.getOriginalServletPathMatch().getServletChain().getManagedServlet().getServletInfo().getName(), t);
                    } catch (Exception e) {
                        UndertowLogger.REQUEST_LOGGER.exceptionGeneratingErrorPage(e, location);
                    }
                } else {
                    if (servletRequestContext.displayStackTraces()) {
                        ServletDebugPageHandler.handleRequest(exchange, servletRequestContext, t);
                    } else {
                        servletRequestContext.getOriginalResponse().doErrorDispatch(StatusCodes.INTERNAL_SERVER_ERROR, StatusCodes.INTERNAL_SERVER_ERROR_STRING);
                    }
                }
            }
        }
    } finally {
        servletRequestContext.setRunningInsideHandler(false);
        listeners.requestDestroyed(request);
    }
    //if it is not dispatched and is not a mock request
    if (!exchange.isDispatched() && !(exchange.getConnection() instanceof MockServerConnection)) {
        servletRequestContext.getOriginalResponse().responseDone();
        servletRequestContext.getOriginalRequest().clearAttributes();
    }
    if (!exchange.isDispatched()) {
        AsyncContextImpl ctx = servletRequestContext.getOriginalRequest().getAsyncContextInternal();
        if (ctx != null) {
            ctx.complete();
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContextImpl(io.undertow.servlet.spec.AsyncContextImpl) HttpString(io.undertow.util.HttpString) OptionMap(org.xnio.OptionMap) Map(java.util.Map) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) RequestDispatcherImpl(io.undertow.servlet.spec.RequestDispatcherImpl)

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