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.apereo.portal.portlet.rendering.PortletExecutionManager.java

@Override
public void doPortletServeResource(IPortletWindowId portletWindowId, HttpServletRequest request,
        HttpServletResponse response) {
    final long timeout = getPortletResourceTimeout(portletWindowId, request);

    final IPortletExecutionWorker<Long> resourceWorker = this.portletWorkerFactory.createResourceWorker(request,
            response, portletWindowId);/*from w  w w. j a v  a 2  s .  c  o  m*/
    resourceWorker.submit();

    try {
        resourceWorker.get(timeout);
    } catch (Exception e) {
        // Log the exception but not this thread's stacktrace. The portlet worker has already logged its stack trace
        this.logger.error("resource worker {} failed with exception {}", resourceWorker, e.toString());
        // render generic serveResource error
        try {
            if (!response.isCommitted()) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "resource unavailable");
            }
        } catch (IOException e1) {
            logger.error("caught IOException trying to send error response for failed resource worker", e);
        }
    }

    //If the worker is still running add it to the hung-workers queue
    if (!resourceWorker.isComplete()) {
        cancelWorker(request, resourceWorker);
    }
}

From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java

private void flushError(HttpServletResponse response, HttpServletResponse wrappedResponse) throws IOException {
    if (!response.isCommitted()) {
        final byte[] data = ((CachingResponseWrapper) wrappedResponse).getData();
        if (data != null) {
            response.setContentType(wrappedResponse.getContentType());
            response.setCharacterEncoding(wrappedResponse.getCharacterEncoding());
            response.getOutputStream().write(data);
            response.flushBuffer();//from   ww  w .  j  a v  a2s . c  o m
        }
    }
}

From source file:org.jasig.portal.portlet.rendering.PortletExecutionManager.java

@Override
public void doPortletServeResource(IPortletWindowId portletWindowId, HttpServletRequest request,
        HttpServletResponse response) {
    final long timeout = getPortletResourceTimeout(portletWindowId, request);

    final IPortletExecutionWorker<Long> resourceWorker = this.portletWorkerFactory.createResourceWorker(request,
            response, portletWindowId);//from   w  w w  .  j  a va  2  s  . co m
    resourceWorker.submit();

    try {
        resourceWorker.get(timeout);
    } catch (Exception e) {
        //log the exception
        this.logger.error("resource worker failed with exception", e);
        // render generic serveResource error
        try {
            if (!response.isCommitted()) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "resource unavailable");
            }
        } catch (IOException e1) {
            logger.error("caught IOException trying to send error response for failed resource worker", e);
        }
    }

    //If the worker is still running add it to the hung-workers queue
    if (!resourceWorker.isComplete()) {
        cancelWorker(request, resourceWorker);
    }
}

From source file:org.wings.session.WingServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException {

    try {/*from   w  w w.  java  2 s  .c  o m*/
        /*
         * make sure, that our context ends with '/'. Otherwise redirect
         * to the same location with appended slash.
         *
         * We need a '/' at the
         * end of the servlet, so that relative requests work. Relative
         * requests are either externalization requests, providing the
         * required resource name in the path info (like 'abc_121.gif')
         * or 'normal' requests which are just an empty URL with the
         * request parameter (like '?12_22=121').
         * The browser assembles the request URL from the current context
         * (the 'directory' it assumes it is in) plus the relative URL.
         * Thus emitted URLs are as short as possible and thus the
         * generated page size.
         */
        String pathInfo = getPathInfo(req);
        // XXX - response.isCommited() is needed because due to some bug
        // when using the tomcat form authentication the response WILL get commited.
        if ((pathInfo == null || pathInfo.length() == 0) && !response.isCommitted()) {
            StringBuffer pathUrl = req.getRequestURL();
            pathUrl.append('/');
            if (req.getQueryString() != null) {
                pathUrl.append('?').append(req.getQueryString());
            }

            log.debug("redirect to " + pathUrl.toString());
            // XXX - response.isCommited() is needed because due to some bug
            // when using the tomcat form authentication the response WILL get commited.
            if (!response.isCommitted()) {
                response.sendRedirect(pathUrl.toString());
                return;
            }
        }

        /*
        * we either have a request for the system externalizer
        * (if there is something in the path info, that starts with '-')
        * or just a normal request to this servlet.
        */
        if (isSystemExternalizeRequest(req)) {
            String identifier = pathInfo.substring(1);
            AbstractExternalizeManager extManager = SystemExternalizeManager.getSharedInstance();
            ExternalizedResource extInfo = extManager.getExternalizedResource(identifier);
            if (extInfo != null) {
                final Device outputDevice = createOutputDevice(req, response, extInfo);
                try {
                    extManager.deliver(extInfo, response, outputDevice);
                } finally {
                    outputDevice.close();
                }
            }
            return;
        }

        SessionServlet sessionServlet = getSessionServlet(req, response, true);

        sessionServlet.doGet(req, response);

    } catch (ServletException e) {
        log.fatal("doGet", e);
        throw e;
    } catch (Throwable e) {
        log.fatal("doGet", e);
        throw new ServletException(e);
    }
}

From source file:org.springframework.flex.servlet.MessageBrokerHandlerAdapter.java

/**
 * //from  w w  w.java  2 s .  c o m
 * {@inheritDoc}
 */
public ModelAndView handle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
    MessageBroker broker = (MessageBroker) handler;

    try {
        // Update thread locals
        broker.initThreadLocals();

        // Set this first so it is in place for the session creation event.
        FlexContext.setThreadLocalObjects(null, null, broker, req, res, this.servletConfig);

        Object providerToCheck = broker.getFlexSessionManager().getFlexSessionProvider(HttpFlexSession.class);
        Assert.isInstanceOf(HttpFlexSessionProvider.class, providerToCheck,
                "MessageBrokerHandlerAdapter requires an instance of " + HttpFlexSessionProvider.class.getName()
                        + " to have been registered with the MessageBroker.");
        HttpFlexSessionProvider provider = (HttpFlexSessionProvider) providerToCheck;
        provider.getOrCreateSession(req);

        String contextPath = req.getContextPath();
        String pathInfo = req.getPathInfo();
        String endpointPath = req.getServletPath();
        if (pathInfo != null) {
            endpointPath = endpointPath + pathInfo;
        }
        Endpoint endpoint = null;
        try {
            endpoint = broker.getEndpoint(endpointPath, contextPath);
        } catch (MessageException me) {
            if (logger.isErrorEnabled()) {
                logger.error("Received invalid request for endpoint path '" + endpointPath + "'.");
            }

            if (!res.isCommitted()) {
                res.sendError(HttpServletResponse.SC_NOT_FOUND);
            }

            return null;
        }

        try {
            if (logger.isInfoEnabled()) {
                logger.info("Channel endpoint " + endpoint.getId() + " received request.");
            }
            endpoint.service(req, res);
        } catch (UnsupportedOperationException ue) {
            if (logger.isErrorEnabled()) {
                logger.error("Channel endpoint " + endpoint.getId()
                        + " received request for an unsupported operation.", ue);
            }

            if (!res.isCommitted()) {
                res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
    } finally {
        FlexContext.clearThreadLocalObjects();
        SerializationContext.clearThreadLocalObjects();
    }

    return null;
}

From source file:org.exist.http.SOAPServer.java

private void writeResponse(HttpServletResponse response, String data, String contentType, String encoding)
        throws IOException {
    // possible format contentType: application/xml; charset=UTF-8
    if (contentType != null && !response.isCommitted()) {

        final int semicolon = contentType.indexOf(';');
        if (semicolon != Constants.STRING_NOT_FOUND) {
            contentType = contentType.substring(0, semicolon);
        }/*from   ww  w. j a  va  2  s . c  om*/

        response.setContentType(contentType + "; charset=" + encoding);
    }

    final OutputStream is = response.getOutputStream();
    is.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes());
    is.write(data.getBytes(encoding));
}

From source file:eionet.cr.api.feeds.xmlconv.XmlConvFeedServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String methodName = XmlConvFeedServlet.class.getSimpleName() + ".doGet()";
    LOGGER.debug("Entered " + methodName);

    response.setContentType("text/xml");

    try {/*from  ww  w .  ja v  a 2 s. c  om*/
        List<SubjectDTO> subjects = new ArrayList<SubjectDTO>();
        String xmlSchema = request.getParameter(SCHEMA_PARAM);
        if (!StringUtils.isBlank(xmlSchema)) {

            SearchDAO searchDao = DAOFactory.get().getDao(SearchDAO.class);
            Map<String, String> criteria = new HashMap<String, String>();
            criteria.put(Predicates.CR_SCHEMA, xmlSchema);

            SearchResultDTO<SubjectDTO> result = searchDao.searchByFilters(criteria, false, null, null, null,
                    true);

            int subjectCount = result.getMatchCount();
            LOGGER.debug(methodName + ", " + subjectCount + " subjects found in total");
            subjects = result.getItems();
        }

        SubjectsRDFWriter rdfWriter = new SubjectsRDFWriter(
                request.getParameter(XmlConvFeedServlet.INCLUDE_DERIVED_VALUES) != null);
        rdfWriter.addNamespace(Namespace.CR);
        rdfWriter.addNamespace(Namespace.DC);
        rdfWriter.addNamespace(Namespace.OWL);
        rdfWriter.addNamespace(Namespace.ROD);
        rdfWriter.addNamespace(Namespace.EPER);

        rdfWriter.write(subjects, response.getOutputStream());
    } catch (Exception e) {
        LOGGER.error("Error in " + methodName, e);
        if (!response.isCommitted()) {
            response.sendError(500);
        }
    }

    response.getOutputStream().flush();

}

From source file:org.apache.roller.planet.ui.rendering.servlets.PageServlet.java

/**
 * Handle GET requests for weblog feeds.
 *///from   ww  w.j a va  2s  .c  o  m
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("Entering");

    Planet planet = null;
    PlanetGroup group = null;

    PlanetGroupPageRequest pageRequest = null;
    try {
        // parse the incoming request and extract the relevant data
        pageRequest = new PlanetGroupPageRequest(request);

        planet = pageRequest.getPlanet();
        if (planet == null) {
            throw new PlanetException("unable to lookup planet: " + pageRequest.getPlanetHandle());
        }

        group = pageRequest.getGroup();

    } catch (Exception e) {
        // invalid feed request format or weblog doesn't exist
        log.debug("error creating planet page request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // set content type
    response.setContentType("text/html; charset=utf-8");

    // looks like we need to render content
    HashMap model = new HashMap();
    try {
        // populate the rendering model
        Map initData = new HashMap();
        initData.put("planetRequest", pageRequest);

        // Load models for pages
        String pageModels = PlanetConfig.getProperty("rendering.pageModels");
        ModelLoader.loadModels(pageModels, model, initData, true);

    } catch (PlanetException ex) {
        log.error("ERROR loading model for page", ex);

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // lookup Renderer we are going to use
    Renderer renderer = null;
    try {
        log.debug("Looking up renderer");

        // what template are we going to render?
        Template template = null;
        if (group == null) {
            // planet homepage
            template = new StaticTemplate("planet.vm", null, "velocity");
        } else {
            // group homepage
            template = new StaticTemplate("group.vm", null, "velocity");
        }

        // get the Renderer
        renderer = RendererManager.getRenderer(template);

    } catch (Exception e) {
        // nobody wants to render my content :(

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // render content
    try {
        log.debug("Doing rendering");
        renderer.render(model, response.getWriter());
    } catch (Exception e) {
        // bummer, error during rendering
        log.error("Error during rendering", e);

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // post rendering process

    // flush rendered content to response
    log.debug("Flushing response output");
    //response.setContentLength(rendererOutput.getContent().length);
    //response.getOutputStream().write(rendererOutput.getContent());

    log.debug("Exiting");
}

From source file:com.logiclander.jaasmine.authentication.http.SPNegoFilter.java

/**
 * This implementation will filter requests for credentials and determine if
 * processing of the FilterChain can proceed.  Filtering occurs as follows:
 * <OL>//  w w w.  j a  v a2 s  . c om
 *  <LI>If the request is not an HttpServletRequest and the response is not
 * an HttpServletResponse, continue processing the filter chain (this almost
 * never happens)</LI>
 *  <LI>The HttpServletRequest is checked for a {@code WWW-Authenticate}
 * request header.  If found, it is checked for the scheme used, which must
 * be set to {@code Negotiate}.</LI>
 *  <LI>If found, the SPNego token is decoded and validated.  If it is
 * valid, processing is allowed to continue.  If not, processing will stop
 * and an HTTP 401 is returned with a {@code WWW-Authenticate} request
 * header set to {@code Negotiate}.</LI>
 *  <LI>If the request header is not found, an HTTP 401 is returned with a
 * {@code WWW-Authenticate} request header set to {@code Negotiate}.</LI>
 * </OL>
 *
 * @param request the ServletRequest
 * @param response the ServletResponse
 * @param chain the FilterChain
 * @throws IOException if an I/O error occurs in the FilterChain
 * @throws ServletException if a processing error occurs in the FilterChain
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("%s: entering doFilter", filterName));
    }

    if (!(request instanceof HttpServletRequest) && !(response instanceof HttpServletResponse)) {

        chain.doFilter(request, response);

    } else {

        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Filtering request: %s%s", httpReq.getContextPath(),
                    httpReq.getServletPath()));
        }

        String sPNegoToken = getSPNegoToken(httpReq);
        boolean canExecute = false;
        SPNegoServer server = null;

        try {

            server = new SPNegoServer(sPNegoToken);
            canExecute = server.isValidToken();

            // Wrap the HttpServletRequest with the requester's GSSName
            // so that additional processing can take place w/out having
            // to re-examine the SPNego token.
            httpReq = new JaasmineHttpServletRequest(httpReq, server.getRequesterName());

        } catch (GSSException ex) {

            if (logger.isDebugEnabled()) {

                logger.debug("Problem with SPNego token", ex);

            } else {

                logger.info(String.format("Problem with SPNego token: %s", ex.getMessage()));

            }

            canExecute = false;

        } catch (Exception ex) {

            if (logger.isFatalEnabled()) {
                logger.fatal(ex.getMessage(), ex);
            }

            canExecute = false;

        }

        if (canExecute) {

            chain.doFilter(httpReq, httpResp);

        } else {

            if (!httpResp.isCommitted()) {
                httpResp.setHeader("WWW-Authenticate", "Negotiate");
                httpResp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }

        }
    }
}