Example usage for javax.servlet.http HttpServletResponse isCommitted

List of usage examples for javax.servlet.http HttpServletResponse isCommitted

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse isCommitted.

Prototype

public boolean isCommitted();

Source Link

Document

Returns a boolean indicating if the response has been committed.

Usage

From source file:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java

protected void buildResponseInfo(StringBuilder sb, HttpServletRequest request, HttpServletResponse response) {
    sb.append("Response class=" + response.getClass().getName());
    sb.append(", ContentType=").append(response.getContentType());
    sb.append(", Committed=").append(response.isCommitted());
    String exp = response.toString().trim();
    if (exp != null) {
        exp = replaceString(exp, "\r\n", "\n");
        exp = replaceString(exp, "\n", " ");
        final int limitLength = 120;
        if (exp.length() >= limitLength) {
            // it is possible that Response toString() show all HTML strings
            // so cut it to suppress too big logging here
            exp = exp.substring(0, limitLength) + "...";
        }/*from  w  w  w  .j  av a 2 s  . c  o m*/
        sb.append(LF).append(IND);
        sb.append(", toString()=").append(exp);
        // e.g. Jetty
        // HTTP/1.1 200  Expires: Thu, 01-Jan-1970 00:00:00 GMT Set-Cookie: ...
    }
}

From source file:com.almende.eve.transport.http.AgentServlet.java

/**
 * Create a new agent Usage: PUT /servlet/{agentId}?type={agentType} Where
 * agentType is the full class path of the agent. Returns a list with the
 * urls of the created agent./*from  ww  w . ja v  a 2 s. co  m*/
 * 
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPut(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final String agentUrl = req.getRequestURI();
    String agentId;
    try {
        agentId = httpTransport.getAgentId(new URI(agentUrl));
    } catch (URISyntaxException e) {
        throw new ServletException(AGENTURLWARNING, e);
    }
    String agentType = req.getParameter("type");

    if (!handleSession(req, resp)) {
        if (!resp.isCommitted()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        return;
    }
    if (agentType == null) {
        // TODO: class is deprecated since 2013-02-19. Remove this some day
        agentType = req.getParameter("class");
        LOG.warning("Query parameter 'class' is deprecated. Use 'type' instead.");
    }

    if (agentId == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No agentId found in url.");
        return;
    }
    if (agentType == null || agentType.equals("")) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Query parameter 'type' missing in url.");
        return;
    }

    try {
        final Agent agent = host.createAgent(agentType, agentId);
        for (final String url : agent.getUrls()) {
            resp.getWriter().println(url);
        }
        agent.signalAgent(new AgentSignal<Void>(AgentSignal.DESTROY, null));
    } catch (final Exception e) {
        throw new ServletException(e);
    }
}

From source file:org.segrada.servlet.SegradaSimplePageCachingFilter.java

@Override
protected void doFilter(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        FilterChain filterChain) throws Exception {
    // exclude?/*from www  .ja va 2 s.  com*/
    String url = servletRequest.getRequestURL().toString();

    // session set?
    Identity identity = injector.getInstance(Identity.class);
    boolean loggedIn = identity.getName() != null;

    // only get request and matched urls when logged in and not on POST methods
    if (!loggedIn || servletRequest.getMethod().equals("POST") || excludePatterns.matcher(url).find()) {
        if (logger.isDebugEnabled())
            logger.debug("Not caching url " + url);

        // build page info and return gzipped if needed
        PageInfo pageInfo = this.buildPage(servletRequest, servletResponse, filterChain);
        if (pageInfo.isOk() && !servletResponse.isCommitted()) {
            this.writeResponse(servletRequest, servletResponse, pageInfo);
        }
    } else {
        // included cached filter chain loaded
        super.doFilter(servletRequest, servletResponse, filterChain);
    }
}

From source file:com.alfaariss.oa.authentication.remote.saml2.profile.re.ResponseEndpoint.java

private void processRedirect(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws OAException {
    ISession session = null;//from  ww w .j  a va  2  s. c o  m

    String sSessionID = servletRequest.getParameter(ISession.ID_NAME);

    try {
        if (sSessionID == null) {
            _logger.debug("Could not redirect to webapp; Parameter 'asid' missing");
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);

            return;
        }

        if (!SessionValidator.validateDefaultSessionId(sSessionID)) {
            StringBuffer sbError = new StringBuffer("Invalid '");
            sbError.append(ISession.ID_NAME);
            sbError.append("' in request: ");
            sbError.append(sSessionID);
            _logger.debug(sbError.toString());
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);

            return;
        }

        session = _sessionFactory.retrieve(sSessionID);
        if (session == null) {
            _logger.debug("Could not redirect to webapp; Could not retrieve session");
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);

            return;
        }

        if (session.isExpired()) {
            _logger.debug("Could not redirect to webapp; Session expired");
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);

            return;
        }

        if (session.getState() != SessionState.AUTHN_OK) {
            IUser user = session.getUser();
            String uid = null;
            if (user != null)
                uid = user.getID();
            if (uid == null)
                uid = "<not found>";
            _logger.debug("Could not redirect to webapp; AuthN failed (uid: " + uid + ")");
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);

            return;
        }

        String returnTo = (String) session.getAttributes().get(ResponseEndpoint.class,
                SAML2AuthNConstants.ATTR_TARGET);
        if (returnTo == null) {
            _logger.debug("Could not redirect to webapp; Cannot retrieve target");
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        if (!servletResponse.isCommitted())
            servletResponse.sendRedirect(returnTo);
    } catch (ClassCastException cce) {
        _logger.error("Could not redirect to webapp; Target in wrong format", cce);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.SESSION_INVALID, null,
                servletRequest.getRemoteAddr(), null, this, null));
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (IOException e) {
        _logger.error("Could not redirect to webapp; I/O error", e);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.INTERNAL_ERROR, null,
                servletRequest.getRemoteAddr(), null, this, null));
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        //authn session no longer necessary
        if (session != null) {
            session.expire();
            session.persist();
        }
    }
}

From source file:org.alfresco.web.app.Application.java

/**
 * Handles errors thrown from servlets//from w  w  w  .j a  va  2s.c  om
 * 
 * @param servletContext The servlet context
 * @param request The HTTP request
 * @param response The HTTP response
 * @param error The exception
 * @param logger The logger
 */
public static void handleServletError(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response, Throwable error, Log logger, String returnPage)
        throws IOException, ServletException {
    // get the error bean from the session and set the error that occurred.
    HttpSession session = request.getSession();
    ErrorBean errorBean = (ErrorBean) session.getAttribute(ErrorBean.ERROR_BEAN_NAME);
    if (errorBean == null) {
        errorBean = new ErrorBean();
        session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean);
    }
    errorBean.setLastError(error);
    errorBean.setReturnPage(returnPage);

    // try and find the configured error page
    boolean errorShown = false;
    String errorPage = getErrorPage(servletContext);

    if (errorPage != null) {
        if (logger.isDebugEnabled())
            logger.debug("An error has occurred, redirecting to error page: " + errorPage);

        if (response.isCommitted() == false) {
            errorShown = true;
            response.sendRedirect(request.getContextPath() + errorPage);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Response is already committed, re-throwing error");
        }
    } else {
        if (logger.isDebugEnabled())
            logger.debug("No error page defined, re-throwing error");
    }

    // if we could not show the error page for whatever reason, re-throw the error
    if (!errorShown) {
        if (error instanceof IOException) {
            throw (IOException) error;
        } else if (error instanceof ServletException) {
            throw (ServletException) error;
        } else {
            throw new ServletException(error);
        }
    }
}

From source file:org.craftercms.engine.controller.rest.RestScriptsController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    SiteContext siteContext = SiteContext.getCurrent();
    ScriptFactory scriptFactory = siteContext.getScriptFactory();

    if (scriptFactory == null) {
        throw new IllegalStateException(
                "No script factory associate to current site context '" + siteContext.getSiteName() + "'");
    }/*from   w  ww  . j  a va  2s.  c  o  m*/

    String serviceUrl = getServiceUrl(request);
    String scriptUrl = getScriptUrl(scriptFactory, siteContext, request, serviceUrl);
    Map<String, Object> scriptVariables = createScriptVariables(request, response);

    scriptUrl = parseScriptUrlForVariables(siteContext, scriptUrl, scriptVariables);

    Object responseBody = executeScript(scriptFactory, scriptVariables, response, scriptUrl);

    if (response.isCommitted()) {
        // If response has been already committed by the script, just return null
        logger.debug("Response already committed by script " + scriptUrl);

        return null;
    }

    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject(responseBodyModelAttributeName, responseBody);

    return modelAndView;
}

From source file:org.alfresco.web.app.Application.java

/**
 * Handles error conditions detected by servlets.
 * /*from w w w  .ja va  2  s  .  c  o  m*/
 * @param servletContext
 *           The servlet context
 * @param request
 *           The HTTP request
 * @param response
 *           The HTTP response
 * @param messageKey
 *           the resource bundle key for the error mesage
 * @param statusCode
 *           the status code to set on the response
 * @param logger
 *           The logger
 * @throws IOException
 *            Signals that an I/O exception has occurred.
 * @throws ServletException
 *            the servlet exception
 */
public static void handleSystemError(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response, String messageKey, int statusCode, Log logger)
        throws IOException, ServletException {
    // get the error bean from the session and set the error that occurred.
    HttpSession session = request.getSession();
    ErrorBean errorBean = (ErrorBean) session.getAttribute(ErrorBean.ERROR_BEAN_NAME);
    if (errorBean == null) {
        errorBean = new ErrorBean();
        session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean);
    }
    errorBean.setErrorMessageKey(messageKey);
    errorBean.setReturnPage(null);

    // try and find the configured error page
    boolean errorShown = false;
    String errorPage = getErrorPage(servletContext);

    if (errorPage != null) {
        if (logger.isDebugEnabled())
            logger.debug("An error has occurred, forwarding to error page: " + errorPage);

        if (!response.isCommitted()) {
            errorShown = true;
            response.reset();
            response.setStatus(statusCode);
            response.setContentType(MimetypeMap.MIMETYPE_HTML);
            response.setCharacterEncoding("utf-8");
            servletContext.getRequestDispatcher(errorPage).include(request, response);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Response is already committed, re-throwing error");
        }
    } else {
        if (logger.isDebugEnabled())
            logger.debug("No error page defined, re-throwing error");
    }

    // if we could not show the error page for whatever reason, re-throw the error
    if (!errorShown) {
        throw new ServletException(getMessage(session, messageKey));
    }
}

From source file:at.ac.univie.isc.asio.insight.ExplorerPageRedirectFilter.java

@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws ServletException, IOException {
    final String redirect = template.findRedirectTarget(request);
    final String original = request.getRequestURI();

    if (redirect == null) { // skip redirect
        log.debug(Scope.REQUEST.marker(), "not an explorer request ({}) - skip redirecting", original);
        chain.doFilter(request, response);
        return;//from w  w  w. j  a  v a  2 s.c om
    }

    assert redirect.startsWith("/") : "redirect target is not an absolute path";
    final RequestDispatcher dispatcher = request.getRequestDispatcher(redirect);
    if (dispatcher == null) { // redirect cannot be handled
        final String message = Pretty.format("no handler for request to <%s> (redirected from <%s>) found",
                redirect, original);
        log.debug(Scope.REQUEST.marker(), message);
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
        }
        return;
    }

    log.debug(Scope.REQUEST.marker(), "redirect request from {} to {}", original, redirect);
    dispatcher.forward(request, response);
}

From source file:org.ms123.common.rpc.JsonRpcServlet.java

/**
 * Remote method execution. The method name and parameters are expected
 * in JSON format in the request body./*  w ww. j av a 2  s  .co  m*/
 *
 * @param request  the servlet request.
 * @param response the servlet response.
 * @throws ServletException thrown when executing the method or writing the response fails.
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    String result = null;
    String requestString = null;
    try {
        requestString = getRequestString(request);
    } catch (Exception e) {
        throw new ServletException("Cannot read request", e);
    }
    result = handleRPC(request, requestString, response);
    if (!response.isCommitted()) {
        String origin = request.getHeader("Origin");
        if (origin != null) {
            response.setHeader("Access-Control-Allow-Origin", origin);
        }
        response.setContentType(DOPOST_RESPONSE_CONTENTTYPE);
        try {
            final Writer responseWriter = response.getWriter();
            if (request.getParameter("pretty") != null) {
                result = makePretty(result);
            }
            responseWriter.write(result);
        } catch (IOException e) {
            throw new ServletException("Cannot write response", e);
        }
    }
}