Java Code Examples for javax.servlet.http.HttpServletResponse#isCommitted()

The following examples show how to use javax.servlet.http.HttpServletResponse#isCommitted() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GatewayHttpProxy.java    From jboot with Apache License 2.0 6 votes vote down vote up
private void copyConnStreamToResponse(HttpURLConnection conn, HttpServletResponse resp) throws IOException {
    InputStream inStream = null;
    InputStreamReader reader = null;
    try {
        if (!resp.isCommitted()) {
            PrintWriter writer = resp.getWriter();
            inStream = getInputStream(conn);
            reader = new InputStreamReader(inStream);
            int len;
            char[] buffer = new char[1024];
            while ((len = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, len);
            }
        }
    } finally {
        quetlyClose(inStream, reader);
    }
}
 
Example 2
Source File: RequestLogFilter.java    From plumdo-work with Apache License 2.0 6 votes vote down vote up
private void updateResponse(String requestUri, ContentCachingResponseWrapper responseWrapper) {
    try {
        HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse();
        byte[] body = responseWrapper.getContentAsByteArray();
        ServletOutputStream outputStream = rawResponse.getOutputStream();
        if (rawResponse.isCommitted()) {
            if (body.length > 0) {
                StreamUtils.copy(body, outputStream);
            }
        } else {
            if (body.length > 0) {
                rawResponse.setContentLength(body.length);
                StreamUtils.copy(body, rawResponse.getOutputStream());
            }
        }
        finishResponse(outputStream, body);
    } catch (Exception ex) {
        log.error("请求地址为" + requestUri + "的连接返回报文失败,原因是{}", ex.getMessage());
    }
}
 
Example 3
Source File: ResponseEntityExceptionHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Customize the response for AsyncRequestTimeoutException.
 * <p>This method delegates to {@link #handleExceptionInternal}.
 * @param ex the exception
 * @param headers the headers to be written to the response
 * @param status the selected response status
 * @param webRequest the current request
 * @return a {@code ResponseEntity} instance
 * @since 4.2.8
 */
@Nullable
protected ResponseEntity<Object> handleAsyncRequestTimeoutException(
		AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) {

	if (webRequest instanceof ServletWebRequest) {
		ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
		HttpServletResponse response = servletWebRequest.getResponse();
		if (response != null && response.isCommitted()) {
			if (logger.isWarnEnabled()) {
				logger.warn("Async request timed out");
			}
			return null;
		}
	}

	return handleExceptionInternal(ex, null, headers, status, webRequest);
}
 
Example 4
Source File: CustomFailureHandler.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
		AuthenticationException exception) throws IOException, ServletException {
	System.out.println("failure");
	String targetUrl = "";
	if(exception instanceof BadCredentialsException){
		targetUrl = "/login.html?error=" + exception.getMessage();
	}
	else {
		targetUrl = "/login.html?error=" + true;
	}
	  
	if (response.isCommitted()) {
            System.out.println("Internal problem in redirection");
            return;
    }
   
    redirectStrategy.sendRedirect(request, response, targetUrl);
}
 
Example 5
Source File: ResponseEntityExceptionHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Customize the response for NoHandlerFoundException.
 * <p>This method delegates to {@link #handleExceptionInternal}.
 * @param ex the exception
 * @param headers the headers to be written to the response
 * @param status the selected response status
 * @param webRequest the current request
 * @return a {@code ResponseEntity} instance
 * @since 4.2.8
 */
protected ResponseEntity<Object> handleAsyncRequestTimeoutException(
		AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) {

	if (webRequest instanceof ServletWebRequest) {
		ServletWebRequest servletRequest = (ServletWebRequest) webRequest;
		HttpServletRequest request = servletRequest.getNativeRequest(HttpServletRequest.class);
		HttpServletResponse response = servletRequest.getNativeResponse(HttpServletResponse.class);
		if (response.isCommitted()) {
			if (logger.isErrorEnabled()) {
				logger.error("Async timeout for " + request.getMethod() + " [" + request.getRequestURI() + "]");
			}
			return null;
		}
	}

	return handleExceptionInternal(ex, null, headers, status, webRequest);
}
 
Example 6
Source File: TraceeFilter.java    From tracee with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
final void doFilterHttp(final HttpServletRequest request, final HttpServletResponse response,
						final FilterChain filterChain) throws IOException, ServletException {

	final TraceeFilterConfiguration configuration = backend.getConfiguration(profile);

	try {
		// we need to eagerly write ResponseHeaders since the inner servlets may flush the output stream
		// and writing of response headers become impossible afterwards. This is a best effort trade-off.
		writeContextToResponse(response, configuration);
		filterChain.doFilter(request, response);
	} finally {
		if (!response.isCommitted()) {
			writeContextToResponse(response, configuration);
		}
	}
}
 
Example 7
Source File: TokenErrorResponseHandler.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
public void handle(Exception exception, HttpServletResponse response) {
    if (!response.isCommitted()) {
        try {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);

            if (exception instanceof TokenException) {
                handleTokenException((TokenException) exception, response);
            } else if (exception instanceof AccessDeniedException) {
                handleAccessDeniedException(response);
            } else if (exception instanceof AuthenticationException) {
                handleAuthenticationException((AuthenticationException) exception, response);
            } else {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                mapper.writeValue(response.getWriter(), TokenErrorResponse.of(exception.getMessage(),
                        TokenErrorCode.GENERAL, HttpStatus.INTERNAL_SERVER_ERROR));
            }
        } catch (IOException e) {
        }
    }
}
 
Example 8
Source File: ProxyFilter.java    From esigate with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    IncomingRequest incomingRequest = requestFactory.create(httpServletRequest, httpServletResponse, chain);

    try {
        CloseableHttpResponse driverResponse = DriverFactory.proxy(incomingRequest);
        responseSender.sendResponse(driverResponse, incomingRequest, httpServletResponse);
    } catch (HttpErrorPage e) {
        if (!httpServletResponse.isCommitted()) {
            responseSender.sendResponse(e.getHttpResponse(), incomingRequest, httpServletResponse);
        }
    }
}
 
Example 9
Source File: AjaxSupportedAccessDeniedHandler.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpServletRequest request,
		HttpServletResponse response,
		AccessDeniedException accessDeniedException) throws IOException,
		ServletException {
	String url = request.getMethod() + "|" + request.getRequestURI();
	String errorMsg = getErrorMessage(accessDeniedException);
	
	if(RequestUtils.isAjaxRequest(request)){
		SimpleResultBuilder<?> builder = DataResults.error(errorMsg+
																", at "+request.getRequestURI())
														.code(SecurityErrors.ACCESS_DENIED)
														.data(url);
		
		DataResult<?> rs = WebUtils.buildErrorCode(builder, request, accessDeniedException).build();
		String text = mapper.toJson(rs);
		logger.info("[] AccessDenied, render json: {}", url, text);
		ResponseUtils.render(response, text, ResponseUtils.JSON_TYPE, true);
	}else if(!response.isCommitted() && StringUtils.isNotBlank(redirectErrorUrl)) {
		String rurl = redirectErrorUrl;
		if(rurl.contains("?")){
			rurl += "&";
		}else{
			rurl += "?";
		}
		rurl += "accessDenied=true&status="+HttpServletResponse.SC_FORBIDDEN+"&message=";
		rurl += URLEncoder.encode(errorMsg, Charsets.UTF_8.name());//encode value, otherwise will redirect failed

		logger.info("{} AccessDenied, redirect to {}", url, rurl);
		response.sendRedirect(rurl);
	}else{
		defaultHandle(request, response, accessDeniedException);
	}
}
 
Example 10
Source File: MySimpleUrlAuthenticationSuccessHandler.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
    final String targetUrl = determineTargetUrl(authentication);

    if (response.isCommitted()) {
        log.debug("Response has already been committed. Unable to redirect to " + targetUrl);
        return;
    }

    redirectStrategy.sendRedirect(request, response, targetUrl);
}
 
Example 11
Source File: HandlerExceptionResolver.java    From plumemo with Apache License 2.0 5 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
    log.error("系统统一异常处理:", exception);

    // 若响应已响应或已关闭,则不操作
    if (response.isCommitted()) {
        return new ModelAndView();
    }

    // 组装错误提示信息
    String errorCode = exception instanceof BusinessException ? ((BusinessException) exception).getCode() : ErrorEnum.ERROR.getCode();

    String message;
    ErrorEnum errorEnumMap = ErrorEnum.getErrorEnumMap(errorCode);
    if (errorEnumMap != null) {
        message = errorEnumMap.getZhMsg();
    } else {
        message = exception instanceof BusinessException ? exception.getMessage() : ErrorEnum.ERROR.getZhMsg();
    }

    if (exception instanceof ApiInvalidParamException) {
        //定义错误编码
        //errorCode = 10001;
        message = exception.getMessage();
    }
    // 响应类型设置
    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

    // 响应结果输出
    try (PrintWriter writer = response.getWriter()) {
        writer.write(JsonUtil.toJsonString(Result.createWithErrorMessage(message, errorCode)));
    } catch (Exception e) {
        log.error("响应输出失败!原因如下:", e);
    }
    return new ModelAndView();
}
 
Example 12
Source File: HandlerExceptionResolver.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
    log.error("系统统一异常处理:", exception);

    // 若响应已响应或已关闭,则不操作
    if (response.isCommitted()) {
        return new ModelAndView();
    }

    // 组装错误提示信息
    String errorCode = exception instanceof BusinessException ? ((BusinessException) exception).getCode() : ErrorConstants.OPERATION_FAIL;
    String message = ErrorMessageUtil.getErrorMessage(errorCode, null);
    if (exception instanceof ApiInvalidParamException) {
        //定义错误编码
        //errorCode = 10001;
        message = exception.getMessage();
    }
    // 响应类型设置
    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

    // 响应结果输出
    try (PrintWriter writer = response.getWriter()) {
        writer.write(JsonUtils.objectToJson(Result.createWithErrorMessage(message, errorCode)));
    } catch (Exception e) {
        log.error("响应输出失败!原因如下:", e);
    }
    return new ModelAndView();
}
 
Example 13
Source File: MySimpleUrlAuthenticationSuccessHandler.java    From tutorials with MIT License 5 votes vote down vote up
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    String targetUrl = determineTargetUrl(authentication);

    if (response.isCommitted()) {
        logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
        return;
    }

    redirectStrategy.sendRedirect(request, response, targetUrl);
}
 
Example 14
Source File: TimeoutDeferredResultProcessingInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception {
	HttpServletResponse servletResponse = request.getNativeResponse(HttpServletResponse.class);
	if (!servletResponse.isCommitted()) {
		servletResponse.sendError(HttpStatus.SERVICE_UNAVAILABLE.value());
	}
	return false;
}
 
Example 15
Source File: CustomSuccessHandler.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
        throws IOException {
	

    String targetUrl = targetUrl(authentication);
    if (response.isCommitted()) {
        System.out.println("Can't redirect");
        return;
    }
    redirectStrategy.sendRedirect(request, response, targetUrl);
}
 
Example 16
Source File: ResponseSender.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void sendResponse(HttpResponse httpResponse, IncomingRequest httpRequest, HttpServletResponse response)
        throws IOException {
    if (response.isCommitted()) {
        return; // Response already sent
    }
    sendHeaders(httpResponse, httpRequest, response);
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        HttpResponseUtils.writeTo(httpEntity, response.getOutputStream());
    } else {
        response.sendError(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine()
                .getReasonPhrase());
    }
}
 
Example 17
Source File: SocialAuthSecurityFilter.java    From socialauth with MIT License 4 votes vote down vote up
public void doFilter(final HttpServletRequest req,
		final HttpServletResponse res, final FilterChain fc)
		throws Exception {
	SASFHelper h = new DefaultSASFHelper(req, this.props,
			this.sdbSocialAuthManager, req.getSession());
	String path = lookupPath(req);
	if (path != null && path.startsWith(h.getServletMain())) {
		try {
			if (path.equals(h.getServletSuccess())) {
				SocialAuthManager manager = h.getAuthManager();
				AuthProvider provider = manager.connect(SocialAuthUtil
						.getRequestParametersMap(req));
				h.setProvider(provider);
				res.sendRedirect(h.getWebappSuccessAction());
				return;
			} else {
				String id = req.getParameter("id");
				SocialAuthManager socialAuthManager = null;
				synchronized (req.getSession()) {
					if (h.getAuthManager() != null) {
						socialAuthManager = h.getAuthManager();
					} else {
						socialAuthManager = h.getMgr()
								.getSocialAuthManager();
						h.setAuthManager(socialAuthManager);
					}
				}

				res.sendRedirect(socialAuthManager.getAuthenticationUrl(id,
						h.getOpenidReturnUrl()));
				return;

			}
		} catch (Throwable t) {
			h.setError(t.getMessage(), t);
			res.sendRedirect(h.getErrorPage());
			return;
		}
	}
	if (!res.isCommitted()) {
		fc.doFilter(req, res);
	}
}
 
Example 18
Source File: HALoadBalancerServlet.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Overridden to provide more information about the error. The
 * implementation is derived from the jetty 9.1.4 implementation of the
 * method in the base {@link ProxyServlet} class, but logs @ ERROR so we can
 * see more about the underlying problem.
 * 
 * @see <a href="http://trac.blazegraph.com/ticket/941" > HA LBS Gateway errors
 *      under heavy load </a>
 * 
 *      TODO jetty 9.2 provides a fully asynchronous proxy servlet. We will
 *      wind up replacing our base class with that implementation soon,
 *      probably for the 1.3.2 release. Until then, this will provide
 *      additional diagnoistic information about the root causes when there
 *      is a gateway error (proxying fails). If we can find some patterns to
 *      these failures, then it would be useful to recharacterize more of
 *      them to encourage the client to retry the request. Those semantics
 *      are not really available for 502 (Bad Gateway). They are more a
 *      appropriate for both 503 (Service Unavailable - temporary overload),
 *      and 504 (Gateway Timeout). 503 might be the best choice if there is
 *      not an explicit timeout and the root cause does not clearly indicate
 *      a durable problem with the target host.
 */
@Override
protected void onProxyResponseFailure(//
        final HttpServletRequest request,//
        final HttpServletResponse response,//
        final Response proxyResponse,//
        final Throwable failure) {
    
    log.error(getRequestId(request) + " proxying failed: " + request, failure);
    if (!response.isCommitted())
    {
        if (failure instanceof TimeoutException)
            response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        else
            response.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
    }
    
    AsyncContext asyncContext = request.getAsyncContext();
    asyncContext.complete();
}
 
Example 19
Source File: ServletRequestDispatcher.java    From spring-boot-protocol with Apache License 2.0 4 votes vote down vote up
/**
 * dispatch (asynchronous)
 * @param request request
 * @param response response
 * @param asyncContext asyncContext
 * @return Runnable
 */
public Runnable dispatchAsync(HttpServletRequest request, HttpServletResponse response, ServletAsyncContext asyncContext){
    if(path == null){
        return null;
    }
    if(request instanceof ServletHttpAsyncRequest
            && path.equals(request.getAttribute(AsyncContext.ASYNC_REQUEST_URI))){
        return null;
    }

    ServletHttpServletResponse httpResponse = ServletUtil.unWrapper(response);
    if(httpResponse == null){
        throw new UnsupportedOperationException("Not found Original Response");
    }
    HttpServletRequest httpRequest = ServletUtil.unWrapper(request);
    if(httpRequest == null){
        throw new UnsupportedOperationException("Not found Original Request");
    }
    if (response.isCommitted()) {
        throw new IllegalStateException("Cannot perform this operation after response has been committed");
    }

    //Hand over control of the output stream
    ServletOutputStreamWrapper outWrapper = httpResponse.getOutputStream();

    //Pause the current response
    outWrapper.setSuspendFlag(true);
    //To the next servlet
    ServletHttpAsyncResponse asyncResponse = new ServletHttpAsyncResponse(httpResponse,outWrapper.unwrap());
    ServletHttpAsyncRequest asyncRequest = new ServletHttpAsyncRequest(request,asyncContext);
    asyncRequest.setDispatchPath(path);
    if (asyncRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI) == null) {
        asyncRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH, asyncRequest.getContextPath());
        asyncRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO, asyncRequest.getPathInfo());
        asyncRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING, asyncRequest.getQueryString());
        asyncRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI, asyncRequest.getRequestURI());
        asyncRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH, asyncRequest.getServletPath());
    }

    //Return to the task
    Runnable runnable = ()->{
        try {
            dispatch(asyncRequest, asyncResponse);
        } catch (Exception e) {
            throw new ServletAsyncContext.AsyncRuntimeException(e);
        }
    };
    return runnable;
}
 
Example 20
Source File: InternalResourceView.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Determine whether to use RequestDispatcher's {@code include} or
 * {@code forward} method.
 * <p>Performs a check whether an include URI attribute is found in the request,
 * indicating an include request, and whether the response has already been committed.
 * In both cases, an include will be performed, as a forward is not possible anymore.
 * @param request current HTTP request
 * @param response current HTTP response
 * @return {@code true} for include, {@code false} for forward
 * @see javax.servlet.RequestDispatcher#forward
 * @see javax.servlet.RequestDispatcher#include
 * @see javax.servlet.ServletResponse#isCommitted
 * @see org.springframework.web.util.WebUtils#isIncludeRequest
 */
protected boolean useInclude(HttpServletRequest request, HttpServletResponse response) {
	return (this.alwaysInclude || WebUtils.isIncludeRequest(request) || response.isCommitted());
}