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.apache.struts2.result.ServletDispatcherResult.java

/**
 * Dispatches to the given location. Does its forward via a RequestDispatcher. If the
 * dispatch fails a 404 error will be sent back in the http response.
 *
 * @param finalLocation the location to dispatch to.
 * @param invocation    the execution state of the action
 * @throws Exception if an error occurs. If the dispatch fails the error will go back via the
 *                   HTTP request./*from   w ww. j  a v a  2 s  .  c om*/
 */
public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    LOG.debug("Forwarding to location: {}", finalLocation);

    PageContext pageContext = ServletActionContext.getPageContext();

    if (pageContext != null) {
        pageContext.include(finalLocation);
    } else {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);

        //add parameters passed on the location to #parameters
        // see WW-2120
        if (StringUtils.isNotEmpty(finalLocation) && finalLocation.indexOf("?") > 0) {
            String queryString = finalLocation.substring(finalLocation.indexOf("?") + 1);
            HttpParameters parameters = getParameters(invocation);
            Map<String, Object> queryParams = urlHelper.parseQueryString(queryString, true);
            if (queryParams != null && !queryParams.isEmpty()) {
                parameters = HttpParameters.create(queryParams).withParent(parameters).build();
                invocation.getInvocationContext().setParameters(parameters);
                // put to extraContext, see Dispatcher#createContextMap
                invocation.getInvocationContext().getContextMap().put("parameters", parameters);
            }
        }

        // if the view doesn't exist, let's do a 404
        if (dispatcher == null) {
            LOG.warn("Location {} not found!", finalLocation);
            response.sendError(404, "result '" + finalLocation + "' not found");
            return;
        }

        //if we are inside an action tag, we always need to do an include
        Boolean insideActionTag = (Boolean) ObjectUtils
                .defaultIfNull(request.getAttribute(StrutsStatics.STRUTS_ACTION_TAG_INVOCATION), Boolean.FALSE);

        // If we're included, then include the view
        // Otherwise do forward
        // This allow the page to, for example, set content type
        if (!insideActionTag && !response.isCommitted()
                && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {
            request.setAttribute("struts.view_uri", finalLocation);
            request.setAttribute("struts.request_uri", request.getRequestURI());

            dispatcher.forward(request, response);
        } else {
            dispatcher.include(request, response);
        }
    }
}

From source file:org.pentaho.platform.web.servlet.ViewAction.java

@SuppressWarnings("unchecked")
protected void handleActionRequest(final HttpServletRequest request, final HttpServletResponse response,
        final IOutputHandler outputHandler, final HttpServletRequestHandler requestHandler,
        OutputStream outputStream, final IContentItem contentItem) throws ServletException, IOException {
    IRuntimeContext runtime = null;//from  ww w .jav  a2 s.  c om
    try {
        runtime = requestHandler.handleActionRequest(0, 0);

        if (runtime == null) {
            StringBuffer buffer = new StringBuffer();
            for (String message : (List<String>) requestHandler.getMessages()) {
                buffer.append(message);
            }
            outputStream.write(buffer.toString().getBytes(LocaleHelper.getSystemEncoding()));
            return;
        }

        /*
         * the flag "hasResponse" should be set if the outputHandler is expected to serve a response back via either the
         * "response.content" output (a final content output), or an intermediate response such as a form to request
         * parameters such as from a SecureFilterComponent.
         */
        boolean hasResponse = outputHandler.isResponseExpected();
        IContentItem responseContentItem = outputHandler.getOutputContentItem(IOutputHandler.RESPONSE,
                IOutputHandler.CONTENT, null, null);

        boolean success = (runtime != null && runtime.getStatus() == IRuntimeContext.RUNTIME_STATUS_SUCCESS);
        boolean debugMessages = doMessages(request);
        boolean printSuccess = (runtime != null) && success && (!hasResponse || debugMessages);
        boolean printError = (runtime != null) && !success && !response.isCommitted();

        if (printSuccess || printError) {
            final String htmlMimeType = "text/html"; //$NON-NLS-1$
            responseContentItem.setMimeType(htmlMimeType);
            // this is going to be the response output stream unless you are in debug mode
            outputStream = responseContentItem.getOutputStream(null);

            response.setContentType(htmlMimeType);
            StringBuffer buffer = new StringBuffer();

            IMessageFormatter formatter = PentahoSystem.get(IMessageFormatter.class,
                    PentahoSessionHolder.getSession());

            if (printSuccess) {
                boolean doWrapper = !("false".equals(request.getParameter("wrapper"))); //$NON-NLS-1$ //$NON-NLS-2$
                formatter.formatSuccessMessage(htmlMimeType, runtime, buffer, debugMessages, doWrapper);
            } else {
                response.resetBuffer();
                formatter.formatFailureMessage(htmlMimeType, runtime, buffer, requestHandler.getMessages());
            }

            outputStream.write(buffer.toString().getBytes(LocaleHelper.getSystemEncoding()));
            responseContentItem.closeOutputStream();
        }
    } finally {
        if (runtime != null) {
            runtime.dispose();
        }
    }
}

From source file:com.alfaariss.oa.helper.stylesheet.StyleSheetEngine.java

/**
 * Let the request be processed by the configured handler.
 *
 * If the request could not be processed by the handler or there is no 
 * handler configured then the requestor will be redirected to the default 
 * css.//w w w .ja  v a2 s .com
 * 
 * @param oRequest the servlet request
 * @param oResponse the servlet response
 * @throws OAException If processing fails.
 */
public void process(HttpServletRequest oRequest, HttpServletResponse oResponse) throws OAException {
    try {
        String sSessionID = oRequest.getParameter(ISession.ID_NAME);
        if (sSessionID == null || sSessionID.trim().length() == 0) {
            _logger.debug("No session id in request");
            throw new StyleSheetException(SystemErrors.ERROR_INTERNAL);
        }

        if (!SessionValidator.validateDefaultSessionId(sSessionID)) {
            _logger.warn("Invalid session id in request: " + sSessionID);
            throw new StyleSheetException(SystemErrors.ERROR_INTERNAL);
        }

        ISession oSession = _sessionFactory.retrieve(sSessionID);
        if (oSession == null) {
            _logger.warn("Session not found: " + sSessionID);
            throw new StyleSheetException(SystemErrors.ERROR_INTERNAL);
        }

        if (_oHandler != null) {
            if (_wurflManager != null && _sDefaultMobileLocation != null && isWirelessDevice(oRequest))
                _oHandler.process(oSession, oResponse, true);
            else
                _oHandler.process(oSession, oResponse, false);
        }
    } catch (StyleSheetException e) {
        //do nothing, handled in finally
    } catch (OAException e) {
        _logger.error("Error during processing", e);
        throw e;
    } catch (Exception e) {
        _logger.fatal("Error during processing", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (!oResponse.isCommitted()) {
            if (_wurflManager != null && _htDeviceSpecificStyleSheets.size() > 0)
                sendDeviceSpecific(oRequest, oResponse);
            else
                sendDefault(oRequest, oResponse);
        }
    }

}

From source file:org.nema.medical.mint.server.controller.StudyMetadataController.java

@RequestMapping("/studies/{uuid}/{type}/metadata")
public void studiesMetadata(final @PathVariable("uuid") String uuid, final @PathVariable("type") String type,
        final HttpServletRequest req, final HttpServletResponse res) throws IOException {
    final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, uuid, res, studyDAO);
    if (studyStatus != Utils.StudyStatus.OK) {
        return;/*  w ww . j a  v a2 s . c  om*/
    }

    final File studyDir = new File(studiesRoot, uuid);
    final File typeDir = new File(studyDir, type);
    if (!typeDir.exists() || !typeDir.canRead()) {
        LOG.error("Unable to locate directory for study: " + studyDir);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid study requested: Not found");
        return;
    }

    try {
        String filename;

        String uri = req.getRequestURI();
        boolean gzip = uri.endsWith(".gz");
        uri = StringUtils.substringBeforeLast(uri, ".gz");
        String extension = StringUtils.substringAfterLast(uri, ".");

        if ("gpb".equals(extension)) {
            res.setContentType("application/octet-stream");
            filename = "metadata.gpb";
        } else if ("xml".equals(extension) || uri.endsWith("metadata")) {
            res.setContentType("text/xml");
            filename = "metadata.xml";
        } else {
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown metadata type.");
            return;
        }

        if (gzip) {
            filename = filename + ".gz";
            res.setContentType("application/gzip");
        }

        final File file = new File(typeDir, filename);
        if (!file.exists()) {
            StudyMetadata study = StudyIO.loadStudy(typeDir);
            StudyIO.writeFile(study, file);
        }

        res.setContentLength(Long.valueOf(file.length()).intValue());
        res.setBufferSize(fileResponseBufferSize);
        Utils.streamFile(file, res.getOutputStream(), fileStreamBufferSize);
    } catch (final IOException e) {
        if (!res.isCommitted()) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Unable to provide study metadata. See server logs.");
        }
    }
}

From source file:nl.nn.adapterframework.webcontrol.action.ShowMonitors.java

public ActionForward executeSub(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {

    // Initialize action
    initAction(request);/*from   ww w . j av a  2  s.  co m*/

    String forward = null;
    DynaActionForm monitorForm = getPersistentForm(mapping, form, request);

    if (isCancelled(request)) {
        log.debug("edit is canceled");
        forward = determineExitForward(monitorForm);
    } else {

        //debugFormData(request,form);

        String action = request.getParameter("action");
        String indexStr = request.getParameter("index");
        String triggerIndexStr = request.getParameter("triggerIndex");
        int index = -1;
        if (StringUtils.isNotEmpty(indexStr)) {
            index = Integer.parseInt(indexStr);
        }
        int triggerIndex = -1;
        if (StringUtils.isNotEmpty(triggerIndexStr)) {
            triggerIndex = Integer.parseInt(triggerIndexStr);
        }

        MonitorManager mm = MonitorManager.getInstance();
        if ("getStatus".equals(action)) {
            response.setContentType("text/xml");
            PrintWriter out = response.getWriter();
            out.print(mm.getStatusXml().toXML());
            out.close();
            return null;
        }
        Lock lock = mm.getStructureLock();
        try {
            lock.acquireExclusive();
            forward = performAction(monitorForm, action, index, triggerIndex, response);
            log.debug("forward [" + forward + "] returned from performAction");
            mm.reconfigure();
        } catch (Exception e) {
            error("could not perform action [" + action + "] on monitorIndex [" + index + "] triggerIndex ["
                    + triggerIndex + "]", e);
        } finally {
            lock.releaseExclusive();
        }
        if (response.isCommitted()) {
            return null;
        }
    }
    if (StringUtils.isEmpty(forward)) {
        log.debug("replacing empty forward with [success]");
        forward = "success";
    }

    initForm(monitorForm);

    ActionForward af = mapping.findForward(forward);
    if (af == null) {
        throw new ServletException("could not find forward [" + forward + "]");
    }
    // Forward control to the specified success URI
    log.debug("forward to [" + forward + "], path [" + af.getPath() + "]");
    return (af);
}

From source file:org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsControllerHelper.java

/**
 * Invokes the action defined by the webRequest for the given arguments
 * /*from   www  . ja  v a2 s . com*/
 * @param controller The controller instance
 * @param controllerClass The GrailsControllerClass that defines the conventions within the controller
 * @param viewName The name of the view to delegate to if necessary
 * @param request The HttpServletRequest object
 * @param response The HttpServletResponse object
 * @param params A map of parameters
 * @return A Spring ModelAndView instance
 */
protected ModelAndView executeAction(GroovyObject controller, GrailsControllerClass controllerClass,
        String viewName, HttpServletRequest request, HttpServletResponse response, Map params) {
    // Step 5a: Check if there is a before interceptor if there is execute it
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
        // Step 6: get closure from closure property
        Closure action;
        try {
            action = (Closure) controller.getProperty(actionName);
        } catch (MissingPropertyException mpe) {
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return null;
            } catch (IOException e) {
                throw new ControllerExecutionException("I/O error sending 404 error", e);
            }
        }

        // Step 7: process the action
        Object returnValue = null;
        try {
            returnValue = handleAction(controller, action, request, response, params);
        } catch (Throwable t) {
            GrailsUtil.deepSanitize(t);
            String pluginName = GrailsPluginUtils.getPluginName(controller.getClass());
            pluginName = pluginName != null ? "in plugin [" + pluginName + "]" : "";
            throw new ControllerExecutionException(
                    "Executing action [" + actionName + "] of controller [" + controller.getClass().getName()
                            + "] " + pluginName + " caused exception: " + t.getMessage(),
                    t);
        }

        // Step 8: determine return value type and handle accordingly
        initChainModel(controller);
        if (response.isCommitted()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Response has been redirected, returning null model and view");
            }
            return null;
        } else {

            TokenResponseHandler handler = (TokenResponseHandler) request
                    .getAttribute(TokenResponseHandler.KEY);
            if (handler != null && !handler.wasInvoked() && handler.wasInvalidToken()) {
                String uri = (String) request.getAttribute(SynchronizerToken.URI);
                if (uri == null) {
                    uri = WebUtils.getForwardURI(request);
                }
                try {
                    FlashScope flashScope = webRequest.getFlashScope();
                    flashScope.put("invalidToken", request.getParameter(SynchronizerToken.KEY));
                    response.sendRedirect(uri);
                    return null;
                } catch (IOException e) {
                    throw new ControllerExecutionException("I/O error sending redirect to URI: " + uri, e);
                }
            } else if (request.getAttribute(ForwardMethod.CALLED) == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Action [" + actionName + "] executed with result [" + returnValue
                            + "] and view name [" + viewName + "]");
                }
                ModelAndView mv = handleActionResponse(controller, returnValue, actionName, viewName);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(
                            "Action [" + actionName + "] handled, created Spring model and view [" + mv + "]");
                }
                return mv;
            } else {
                return null;
            }
        }

    } finally {
        try {
            Thread.currentThread().setContextClassLoader(cl);
        } catch (java.security.AccessControlException e) {
            // not allowed by container, probably related to WAR deployment on AppEngine. Proceed.
        }
    }
}

From source file:org.apache.sling.auth.form.impl.FormAuthenticationHandler.java

/**
 * Called after successful login with the given authentication info. This
 * implementation ensures the authentication data is set in either the
 * cookie or the HTTP session with the correct security tokens.
 * <p>/*  w w  w  .  j av  a2  s . co m*/
 * If no authentication data already exists, it is created. Otherwise if the
 * data has expired the data is updated with a new security token and a new
 * expiry time.
 * <p>
 * If creating or updating the authentication data fails, it is actually
 * removed from the cookie or the HTTP session and future requests will not
 * be authenticated any longer.
 */
@Override
public boolean authenticationSucceeded(HttpServletRequest request, HttpServletResponse response,
        AuthenticationInfo authInfo) {

    /*
     * Note: This method is called if this handler provided credentials
     * which succeeded login into the repository
     */

    // ensure fresh authentication data
    refreshAuthData(request, response, authInfo);

    final boolean result;
    // SLING-1847: only consider a resource redirect if this is a POST request
    // to the j_security_check URL
    if (REQUEST_METHOD.equals(request.getMethod()) && request.getRequestURI().endsWith(REQUEST_URL_SUFFIX)) {

        if (DefaultAuthenticationFeedbackHandler.handleRedirect(request, response)) {
            // terminate request, all done in the default handler
            result = false;
        } else {
            // check whether redirect is requested by the resource parameter
            final String targetResource = AuthUtil.getLoginResource(request, null);
            if (targetResource != null) {
                try {
                    if (response.isCommitted()) {
                        throw new IllegalStateException("Response is already committed");
                    }
                    response.resetBuffer();

                    StringBuilder b = new StringBuilder();
                    if (AuthUtil.isRedirectValid(request, targetResource)) {
                        b.append(targetResource);
                    } else if (request.getContextPath().length() == 0) {
                        b.append("/");
                    } else {
                        b.append(request.getContextPath());
                    }
                    response.sendRedirect(b.toString());
                } catch (IOException ioe) {
                    log.error("Failed to send redirect to: " + targetResource, ioe);
                }

                // terminate request, all done
                result = true;
            } else {
                // no redirect, hence continue processing
                result = false;
            }
        }
    } else {
        // no redirect, hence continue processing
        result = false;
    }

    // no redirect
    return result;
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.oauth.NuxeoOAuthFilter.java

protected void process(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String uri = httpRequest.getRequestURI();

    // process OAuth 3 legged calls
    if (uri.contains("/oauth/")) {
        String call = uri.split("/oauth/")[1];

        if (call.equals("authorize")) {
            processAuthorize(httpRequest, httpResponse);
        } else if (call.equals("request-token")) {
            processRequestToken(httpRequest, httpResponse);
        } else if (call.equals("access-token")) {
            processAccessToken(httpRequest, httpResponse);

        } else {//from   ww  w.  j  a v a 2  s . c  om
            httpResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "OAuth call not supported");
        }
        return;
    }
    // Signed request (simple 2 legged OAuth call or signed request
    // after a 3 legged nego)
    else if (isOAuthSignedRequest(httpRequest)) {

        LoginContext loginContext = processSignedRequest(httpRequest, httpResponse);
        // forward the call if authenticated
        if (loginContext != null) {
            Principal principal = (Principal) loginContext.getSubject().getPrincipals().toArray()[0];
            try {
                chain.doFilter(new NuxeoSecuredRequestWrapper(httpRequest, principal), response);
            } finally {
                try {
                    loginContext.logout();
                } catch (LoginException e) {
                    log.warn("Error when loging out", e);
                }
            }
        } else {
            if (!httpResponse.isCommitted()) {
                httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
            return;
        }
    }
    // Non OAuth calls can pass through
    else {
        throw new RuntimeException("request is not a outh request");
    }
}

From source file:it.classhidra.core.controller.bsController.java

public static void execRedirect(i_stream currentStream, redirects currentStreamRedirect, String id_action,
        ServletContext servletContext, HttpServletRequest request, HttpServletResponse response)
        throws bsControllerException, ServletException, UnavailableException {
    if (currentStream == null || currentStreamRedirect == null)
        return;/*from   w w  w .  ja v a  2 s .co  m*/
    currentStream.onPreRedirect(currentStreamRedirect, id_action);
    RequestDispatcher rd = currentStream.redirect(servletContext, currentStreamRedirect, id_action);
    currentStream.onPostRedirect(rd);

    if (rd == null)
        throw new bsControllerException("Controller generic redirect error. Stream: ["
                + currentStream.get_infostream().getName() + "] ", request, iStub.log_ERROR);
    else {
        try {

            String id_rtype = (String) request.getAttribute(CONST_ID_REQUEST_TYPE);
            if (id_rtype == null)
                id_rtype = CONST_REQUEST_TYPE_FORWARD;

            if (id_rtype.equals(CONST_REQUEST_TYPE_FORWARD)) {
                if (!response.isCommitted())
                    rd.forward(request, response);
                else
                    rd.include(request, response);
            } else {
                rd.include(request, response);
            }

        } catch (Exception e) {
            throw new bsControllerException("Controller generic redirect error. Action: ["
                    + currentStream.get_infostream().getName() + "] ->" + e.toString(), request,
                    iStub.log_ERROR);
        }
    }

}

From source file:org.apache.roller.weblogger.ui.rendering.servlets.RSDServlet.java

/**
 * Handle GET requests for weblog pages.
 *///  ww w. j  a  v a 2s. co m
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("Entering");

    Weblog weblog = null;

    WeblogRequest weblogRequest = null;
    try {
        weblogRequest = new WeblogRequest(request);

        // now make sure the specified weblog really exists
        weblog = weblogRequest.getWeblog();
        if (weblog == null) {
            throw new WebloggerException("Unable to lookup weblog: " + weblogRequest.getWeblogHandle());
        }

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

    // Respond with 304 Not Modified if it is not modified.
    long lastModified = System.currentTimeMillis();
    if (weblog.getLastModified() != null) {
        lastModified = weblog.getLastModified().getTime();
    }
    if (ModDateHeaderUtil.respondIfNotModified(request, response, lastModified)) {
        return;
    }

    // set last-modified date
    ModDateHeaderUtil.setLastModifiedHeader(response, lastModified);

    // set the content type
    response.setContentType("application/rsd+xml; charset=utf-8");

    // populate the model
    HashMap model = new HashMap();
    model.put("website", weblog);
    model.put("absBaseURL", WebloggerRuntimeConfig.getAbsoluteContextURL());

    // lookup Renderer we are going to use
    Renderer renderer = null;
    try {
        log.debug("Looking up renderer");
        Template template = new StaticTemplate("rsd.vm", "velocity");
        renderer = RendererManager.getRenderer(template, DeviceType.standard);
    } catch (Exception e) {
        // nobody wants to render my content :(
        log.error("Couldn't find renderer for rsd template", e);

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

    // render content
    CachedContent rendererOutput = new CachedContent(4096);
    try {
        log.debug("Doing rendering");
        renderer.render(model, rendererOutput.getCachedWriter());

        // flush rendered output and close
        rendererOutput.flush();
        rendererOutput.close();
    } catch (Exception e) {
        // bummer, error during rendering
        log.error("Error during rendering for rsd template", 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");
}