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:com.jeeframework.webframework.filter.dispatcher.JSONJspServletDispatcherResult.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./*from ww  w .  ja  va  2s .c o  m*/
 * 
 * @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.
 */
public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    if (log.isDebugEnabled()) {
        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();

        String curFileName = StringUtils.getFileNamePreffix(finalLocation);
        String curFileSuffix = StringUtils.getFilenameExtension(finalLocation);
        String dstFile = curFileName;

        if (curFileName.startsWith(JSONJspServletDispatcherResult.JSONJSP_PREFIX)
                && curFileName.length() > JSONJspServletDispatcherResult.JSONJSP_PREFIX.length()) {
            dstFile = curFileName.substring(JSONJspServletDispatcherResult.JSONJSP_PREFIX.length());
        }
        if (curFileName.endsWith(JSONJspServletDispatcherResult.JSONJSP_SUFFIX)
                && curFileName.length() > JSONJspServletDispatcherResult.JSONJSP_SUFFIX.length()) {
            dstFile = dstFile.substring(0,
                    dstFile.length() - JSONJspServletDispatcherResult.JSONJSP_SUFFIX.length());
        }

        String webroot = System.getProperty(StrutsPrepareAndExecuteFilterWrapper.CUR_DEFAULT_WEBROOT_KEY);
        if (!webroot.endsWith("/") && !webroot.endsWith("\\")) {
            webroot = webroot + "/";
        }

        String dstFilePath = webroot + finalLocation;

        File dstCurjsp = new File(dstFilePath);
        // && !dstCurjsp.exists()
        if (!dstCurjsp.exists()) {
            try {
                String srcFilePath = webroot;//
                if (!(dstFile.startsWith("/") || dstFile.startsWith("\\"))) {
                    srcFilePath = srcFilePath + "/";
                }
                srcFilePath = srcFilePath + dstFile + "." + curFileSuffix;

                File srcCurjsp = new File(srcFilePath);

                String srcCurjspContent = FileUtils.readFileToString(srcCurjsp,
                        StrutsPrepareAndExecuteFilterWrapper.FILE_ENCODING);
                srcCurjspContent = srcCurjspContent.replaceAll("[\r\n\t]", "");

                FileUtils.writeStringToFile(dstCurjsp, srcCurjspContent,
                        StrutsPrepareAndExecuteFilterWrapper.FILE_ENCODING);

            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("? jsonjsp " + dstFilePath + "error");
            }
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);

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

            return;
        }

        // If we're included, then include the view
        // Otherwise do forward
        // This allow the page to, for example, set content type
        if (!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.nuxeo.ecm.platform.web.common.exceptionhandling.DefaultNuxeoExceptionHandler.java

@Override
public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t)
        throws IOException, ServletException {

    Throwable unwrappedException = ExceptionHelper.unwrapException(t);

    // check for Anonymous case
    if (ExceptionHelper.isSecurityError(unwrappedException)) {
        Principal principal = request.getUserPrincipal();
        if (principal instanceof NuxeoPrincipal) {
            NuxeoPrincipal nuxeoPrincipal = (NuxeoPrincipal) principal;
            if (nuxeoPrincipal.isAnonymous()) {
                // redirect to login than to requested page
                if (handleAnonymousException(request, response)) {
                    return;
                }/*from   www  .j  a v  a 2 s .  c  om*/
            }
        }
    }

    startHandlingException(request, response, t);
    try {
        ErrorHandler handler = getHandler(t);
        Integer code = handler.getCode();
        int status = code == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : code.intValue();
        parameters.getListener().startHandling(t, request, response);

        StringWriter swriter = new StringWriter();
        PrintWriter pwriter = new PrintWriter(swriter);
        t.printStackTrace(pwriter);
        String stackTrace = swriter.getBuffer().toString();
        if (status < HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { // 500
            log.debug(t.getMessage(), t);
        } else {
            log.error(stackTrace);
            parameters.getLogger().error(stackTrace);
        }

        parameters.getListener().beforeSetErrorPageAttribute(unwrappedException, request, response);
        request.setAttribute("exception_message", unwrappedException.getLocalizedMessage());
        request.setAttribute("user_message", getUserMessage(handler.getMessage(), request.getLocale()));
        request.setAttribute("securityError", ExceptionHelper.isSecurityError(unwrappedException));
        request.setAttribute("messageBundle", ResourceBundle.getBundle(parameters.getBundleName(),
                request.getLocale(), Thread.currentThread().getContextClassLoader()));
        String dumpedRequest = parameters.getRequestDumper().getDump(request);
        if (status >= HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { // 500
            parameters.getLogger().error(dumpedRequest);
        }
        request.setAttribute("isDevModeSet", Framework.isDevModeSet());
        if (Framework.isDevModeSet()) {
            request.setAttribute("stackTrace", stackTrace);
            request.setAttribute("request_dump", dumpedRequest);
        }

        parameters.getListener().beforeForwardToErrorPage(unwrappedException, request, response);
        if (!response.isCommitted()) {
            response.setStatus(status);
            String errorPage = handler.getPage();
            errorPage = (errorPage == null) ? parameters.getDefaultErrorPage() : errorPage;
            RequestDispatcher requestDispatcher = request.getRequestDispatcher(errorPage);
            if (requestDispatcher != null) {
                requestDispatcher.forward(request, response);
            } else {
                log.error("Cannot forward to error page, " + "no RequestDispatcher found for errorPage="
                        + errorPage + " handler=" + handler);
            }
            parameters.getListener().responseComplete();
        } else {
            // do not throw an error, just log it: afterDispatch needs to
            // be called, and sometimes the initial error is a
            // ClientAbortException
            log.error("Cannot forward to error page: " + "response is already committed");
        }
        parameters.getListener().afterDispatch(unwrappedException, request, response);
    } catch (ServletException e) {
        throw e;
    } catch (RuntimeException | IOException e) {
        throw new ServletException(e);
    }
}

From source file:org.josso.liferay5.agent.LiferaySSOAgentFilter.java

@Override
protected void processFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;

    // URI pattern matching is implemented programmatically in case this filter is bound to the root web context
    // (i.e. '/*' url pattern) required for intercepting locale-prefixed URLs.
    if (!hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGIN_URI)
            && !hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGOUT_URI)
            && !hreq.getRequestURI().contains(LIFERAY_GROUP_URI)
            && !hreq.getRequestURI().contains(LIFERAY_USER_URI)
            && !hreq.getRequestURI().contains(LIFERAY_WEB_URI)
            && !hreq.getRequestURI().contains(JOSSO_SECURITY_CHECK_URI)) {
        filterChain.doFilter(hreq, hres);
        return;/* w ww  .  j  ava  2s .com*/
    }

    if (log.isDebugEnabled())
        log.debug("Processing : " + hreq.getContextPath());

    try {
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();
        long companyId = PortalUtil.getCompanyId(request);

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";

        if (!_agent.isPartnerApp(vhost, contextPath)) {
            filterChain.doFilter(hreq, hres);
            if (log.isDebugEnabled())
                log.debug("Context is not a josso partner app : " + hreq.getContextPath());

            return;
        }

        // ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        // Get our session ...
        HttpSession session = hreq.getSession(true);

        // ------------------------------------------------------------------
        // Check if the Liferay application required its login form [/c/portal/login]
        // ------------------------------------------------------------------
        if (JossoLiferayProps.isEnabled(companyId) && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGIN_URI)) {
            if (log.isDebugEnabled())
                log.debug("Requested liferay login: '" + hreq.getRequestURI() + "'");
            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {
                saveLoginBackToURL(hreq, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (log.isDebugEnabled())
                log.debug("Redirecting to login url '" + loginUrl + "'");

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

            return;
        }

        // ------------------------------------------------------------------
        // Check if the Liferay application required its logout form [/c/portal/logout]
        // ------------------------------------------------------------------
        if (JossoLiferayProps.isEnabled(companyId)
                && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGOUT_URI)) {
            if (log.isDebugEnabled())
                log.debug("Requested liferay logout: '" + hreq.getRequestURI() + "'");

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (log.isDebugEnabled())
                log.debug("Redirecting to logout url '" + logoutUrl + "'");

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);

            // invalidate session (unbind josso security context)
            session.invalidate();

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));

            return;
        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking for SSO cookie");
        Cookie cookie = null;
        Cookie cookies[] = hreq.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
                cookie = cookies[i];
                break;
            }
        }

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        LiferayLocalSession localSession = new LiferayLocalSession(session);

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'");
            }

            LiferaySSOAgentRequest customAuthRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest(
                    cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession,
                    null, hreq, hres);

            _agent.processRequest(customAuthRequest);

            return;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, verifying optional login process ");

            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = getSavedRequestURL(hreq);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                return;

            }

            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) {

                if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) {

                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, attempting automatic login");

                    // Save current request, so we can co back to it later ...
                    saveRequestURL(hreq, hres);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (log.isDebugEnabled())
                        log.debug("Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    return;
                } else {
                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, but login optional process is not required");
                }
            }

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, checking for outbound relaying");

            if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log.debug("SSO cookie not present and relaying was not requested, skipping");
                filterChain.doFilter(hreq, hres);
                return;
            }

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            filterChain.doFilter(hreq, hres);
            return;
        }

        // This URI should be protected by SSO, go on ...
        if (log.isDebugEnabled())
            log.debug("Session is: " + session);

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Executing agent...");

        // ------------------------------------------------------------------
        // Check if a user has been authenitcated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (log.isDebugEnabled())
                log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '"
                        + hreq.getParameter("josso_assertion_id"));

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            LiferaySSOAgentRequest relayRequest;

            if (log.isDebugEnabled())
                log.debug("Outbound relaying requested for assertion id [" + assertionId + "]");

            relayRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres);

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            if (entry == null) {
                // This is wrong! We should have an entry here!
                log.error(
                        "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found.");
                // Throw an exception and let the container send the INERNAL SERVER ERROR
                throw new ServletException("No Principal found. Verify your SSO Agent Configuration!");
            }

            if (log.isDebugEnabled())
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (log.isDebugEnabled())
                log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]");

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure());
            hres.addCookie(cookie);

            // Redirect the user to the original request URI (which will cause
            // the original request to be restored)
            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                if (requestURI == null) {

                    if (cfg.getDefaultResource() != null) {
                        requestURI = cfg.getDefaultResource();
                    } else {
                        // If no saved request is found, redirect to the partner app root :
                        requestURI = hreq.getRequestURI().substring(0,
                                (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length()));
                    }

                    // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
                    String singlePointOfAccess = _agent.getSinglePointOfAccess();
                    if (singlePointOfAccess != null) {
                        requestURI = singlePointOfAccess + requestURI;
                    } else {
                        String reverseProxyHost = hreq
                                .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                        if (reverseProxyHost != null) {
                            requestURI = reverseProxyHost + requestURI;
                        }
                    }

                    if (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            clearSavedRequestURLs(hreq, hres);
            _agent.clearAutomaticLoginReferer(hreq, hres);
            _agent.prepareNonCacheResponse(hres);

            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
                String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
                if (log.isDebugEnabled())
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Redirecting to original '" + requestURI + "'");
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            return;
        }

        SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(),
                SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq,
                hres);
        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled())
            log.debug("Executed agent.");

        // Get session map for this servlet context.
        Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
        if (sessionMap.get(localSession.getWrapped()) == null) {
            // the local session is new so, make the valve listen for its events so that it can
            // map them to local session events.
            // Not supported : session.addSessionListener(this);
            sessionMap.put(session, localSession);
        }

        // ------------------------------------------------------------------
        // Has a valid user already been authenticated?
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Process request for '" + hreq.getRequestURI() + "'");

        if (entry != null) {
            if (log.isDebugEnabled())
                log.debug("Principal '" + entry.principal + "' has already been authenticated");
            // TODO : Not supported
            // (request).setAuthType(entry.authType);
            // (request).setUserPrincipal(entry.principal);
        } else {
            log.info("No Valid SSO Session, attempt an optional login?");
            // This is a standard anonymous request!

            if (cookie != null) {
                // cookie is not valid
                cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

            if (cookie != null
                    || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) {

                if (log.isDebugEnabled())
                    log.debug("SSO Session is not valid, attempting automatic login");

                // Save current request, so we can co back to it later ...
                saveRequestURL(hreq, hres);
                String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                if (log.isDebugEnabled())
                    log.debug("Redirecting to login url '" + loginUrl + "'");

                //set non cache headers
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                return;
            } else {
                if (log.isDebugEnabled())
                    log.debug("SSO cookie is not present, but login optional process is not required");
            }

        }

        // propagate the login and logout URLs to
        // partner applications.
        hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
        hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
        hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

        // ------------------------------------------------------------------
        // Invoke the next Valve in our pipeline
        // ------------------------------------------------------------------
        filterChain.doFilter(hreq, hres);
    } finally {
        if (log.isDebugEnabled())
            log.debug("Processed : " + hreq.getContextPath());
    }
}

From source file:ORG.oclc.os.SRW.SRWServlet.java

/**
 * write a message to the response, set appropriate headers for content
 * type..etc./*from   w w  w  .j a  v a2s.c o  m*/
 * @param clientVersion client protocol, one of the HTTPConstants strings
 * @param res   response
 * @param responseMsg message to write
 * @throws AxisFault
 * @throws IOException if the response stream can not be written to
 */
private void sendResponse(final String clientVersion, String contentType, HttpServletResponse res,
        Message responseMsg) throws AxisFault, IOException {
    if (responseMsg == null) {
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        if (isDebug)
            servletLog.debug("NO AXIS MESSAGE TO RETURN!");
        //String resp = Messages.getMessage("noData00");
        //res.setContentLength((int) resp.getBytes().length);
        //res.getWriter().print(resp);
    } else {
        if (isDebug) {
            servletLog.debug("Returned Content-Type:" + contentType);
            // log.debug("Returned Content-Length:" +
            //          responseMsg.getContentLength());
        }

        try {
            res.setContentType(contentType);

            /* My understand of Content-Length
             * HTTP 1.0
             *   -Required for requests, but optional for responses.
             * HTTP 1.1
             *  - Either Content-Length or HTTP Chunking is required.
             *   Most servlet engines will do chunking if content-length is not specified.
             *
             *
             */

            //if(clientVersion == HTTPConstants.HEADER_PROTOCOL_V10) //do chunking if necessary.
            //     res.setContentLength(responseMsg.getContentLength());

            responseMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }
    }

    if (!res.isCommitted()) {
        res.flushBuffer(); // Force it right now.
    }
}

From source file:org.sakaiproject.cheftool.ToolServlet.java

/**
 * Respond to a request by dispatching to a portlet like "do" method based on the portlet mode and tool mode
 */// ww w . ja va2  s .c  o m
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException {
    // get the panel
    String panel = ((ParameterParser) req.getAttribute(ATTR_PARAMS)).getString(ActionURL.PARAM_PANEL);

    if (panel == null || panel.equals("") || panel.equals("null")) {
        panel = MAIN_PANEL;
    } else {
        // sanitize value
        panel = panel.replaceAll("[\r\n]", "");
    }

    // HELPER_ID needs the panel appended
    String helperId = HELPER_ID + panel;

    // detect a helper done
    ToolSession toolSession = SessionManager.getCurrentToolSession();
    String helper = ((ParameterParser) req.getAttribute(ATTR_PARAMS)).getString(helperId);
    if (helper != null) {
        // clear our helper id indicator from session
        toolSession.removeAttribute(helperId);

        // redirect to the same URL w/o the helper done indication, otherwise this is left in the browser and can be re-processed later
        String newUrl = req.getContextPath() + req.getServletPath()
                + (req.getPathInfo() == null ? "" : req.getPathInfo()) + "?" + ActionURL.PARAM_PANEL + "="
                + panel;
        try {
            res.sendRedirect(newUrl);
        } catch (IOException e) {
            M_log.warn("redirecting after helper done detection  to: " + newUrl + " : " + e.toString());
        }
        return;
    }

    // get the sakai.tool.helper.id helper id from the tool session
    // if defined and it's not our tool id, we need to defer to the helper
    helper = (String) toolSession.getAttribute(helperId);
    Tool me = ToolManager.getCurrentTool();
    if ((helper != null) && (!helper.equals(me.getId()))) {
        toolSession.removeAttribute(helperId);
        String newUrl = req.getContextPath() + req.getServletPath()
                + (req.getPathInfo() == null ? "" : req.getPathInfo()) + "/" + helper + HELPER_EXT;

        try {
            res.sendRedirect(newUrl);
        } catch (IOException e) {
            M_log.warn("redirecting to helper to: " + newUrl + " : " + e.toString());
        }
        return;
    }

    // see if we have a helper request
    if (sendToHelper(req, res, req.getPathInfo())) {
        return;
    }

    // init or update the session state
    prepState(req, res);

    // see if there's an action to process
    processAction(req, res);

    // if not redirected
    if (!res.isCommitted()) {
        // dispatch
        toolModeDispatch("doView", getToolMode(req), req, res);
    }

}

From source file:com.alfaariss.oa.profile.saml2.profile.sso.WebBrowserSSO.java

/**
 * @see ISAML2Profile#process(javax.servlet.http.HttpServletRequest, 
 *  javax.servlet.http.HttpServletResponse)
 *//*from w  w  w.ja v a 2  s.  c  o  m*/
public void process(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException {
    ISession session = null;
    try {
        String sSessionId = servletRequest.getParameter(ISession.ID_NAME);
        if (sSessionId != null) {
            if (!SessionValidator.validateDefaultSessionId(sSessionId)) {
                _logger.warn("Invalid session id in request: " + sSessionId);
                throw new UserException(UserEvent.REQUEST_INVALID);
            }
            session = _sessionFactory.retrieve(sSessionId);

            if (session == null) {
                StringBuffer sbError = new StringBuffer("No session with id '");
                sbError.append(sSessionId);
                sbError.append("' found in request sent from IP: ");
                sbError.append(servletRequest.getRemoteAddr());
                _logger.debug(sbError.toString());
                throw new UserException(UserEvent.REQUEST_INVALID);
            }

            if (session.isExpired()) {
                StringBuffer sbError = new StringBuffer("Expired session with id '");
                sbError.append(sSessionId);
                sbError.append("' found in request sent from IP: ");
                sbError.append(servletRequest.getRemoteAddr());
                _logger.debug(sbError.toString());

                throw new UserException(UserEvent.REQUEST_INVALID);
            }

            processAuthenticationResponse(servletRequest, servletResponse, session);
        } else
            processSAMLRequest(servletRequest, servletResponse, session);
    } catch (UserException e) //User error
    {
        UserEventLogItem logItem = null;
        if (session != null)
            logItem = new UserEventLogItem(session, servletRequest.getRemoteAddr(), e.getEvent(), this, null);
        else
            logItem = new UserEventLogItem(null, null, null, e.getEvent(), null, servletRequest.getRemoteAddr(),
                    null, this, null);
        _eventLogger.info(logItem);

        if (!servletResponse.isCommitted()) {
            try {
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } catch (IOException e1) {
                _logger.warn("Could not send response", e1);
            }
        }
    } catch (SAML2SecurityException e) {
        //DD Security error -> Return a "403 Forbidden" response
        _logger.debug("Security error", e);

        _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null,
                servletRequest.getRemoteAddr(), null, this, "Security Fault"));

        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e1) {
            _logger.warn("Could not send response", e1);
        }
    } catch (OAException e) {
        RequestorEventLogItem oLogItem = null;
        if (session != null)
            oLogItem = new RequestorEventLogItem(session, servletRequest.getRemoteAddr(),
                    RequestorEvent.REQUEST_INVALID, this, null);
        else
            oLogItem = new RequestorEventLogItem(null, null, null, RequestorEvent.REQUEST_INVALID, null,
                    servletRequest.getRemoteAddr(), null, this, null);
        _eventLogger.info(oLogItem);

        throw e;
    } catch (Exception e) {
        RequestorEventLogItem oLogItem = null;
        if (session != null)
            oLogItem = new RequestorEventLogItem(session, servletRequest.getRemoteAddr(),
                    RequestorEvent.INTERNAL_ERROR, this, null);
        else
            oLogItem = new RequestorEventLogItem(null, null, null, RequestorEvent.INTERNAL_ERROR, null,
                    servletRequest.getRemoteAddr(), null, this, null);
        _eventLogger.info(oLogItem);

        _logger.fatal("Internal error during process", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

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

/**
 * Handles requests for user uploaded media file resources.
 *//*from www .  j  av  a 2s. c  o  m*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    MediaFileManager mfMgr = WebloggerFactory.getWeblogger().getMediaFileManager();

    Weblog weblog = null;
    String ctx = request.getContextPath();
    String servlet = request.getServletPath();
    String reqURI = request.getRequestURI();

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

        weblog = resourceRequest.getWeblog();
        if (weblog == null) {
            throw new WebloggerException("unable to lookup weblog: " + resourceRequest.getWeblogHandle());
        }

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

    long resourceLastMod = 0;
    InputStream resourceStream = null;
    MediaFile mediaFile = null;

    try {
        mediaFile = mfMgr.getMediaFile(resourceRequest.getResourceId(), true);
        resourceLastMod = mediaFile.getLastModified();

    } catch (Exception ex) {
        // still not found? then we don't have it, 404.
        log.debug("Unable to get resource", ex);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Respond with 304 Not Modified if it is not modified.
    if (ModDateHeaderUtil.respondIfNotModified(request, response, resourceLastMod)) {
        return;
    } else {
        // set last-modified date
        ModDateHeaderUtil.setLastModifiedHeader(response, resourceLastMod);
    }

    // set the content type based on whatever is in our web.xml mime defs
    if (resourceRequest.isThumbnail()) {
        response.setContentType("image/png");
        try {
            resourceStream = mediaFile.getThumbnailInputStream();
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("ERROR loading thumbnail for " + mediaFile.getId(), e);
            } else {
                log.warn("ERROR loading thumbnail for " + mediaFile.getId());
            }
        }
    }

    if (resourceStream == null) {
        response.setContentType(mediaFile.getContentType());
        resourceStream = mediaFile.getInputStream();
    }

    OutputStream out = null;
    try {
        // ok, lets serve up the file
        byte[] buf = new byte[8192];
        int length = 0;
        out = response.getOutputStream();
        while ((length = resourceStream.read(buf)) > 0) {
            out.write(buf, 0, length);
        }

        // close output stream
        out.close();

    } catch (Throwable ex) {
        log.error("ERROR", ex);
        if (!response.isCommitted()) {
            response.reset();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } finally {
        // make sure stream to resource file is closed
        resourceStream.close();
    }

}

From source file:com.alfaariss.oa.profile.saml2.profile.artifactresolution.ArtifactResolutionService.java

/**
 * @see ISAML2Profile#process(javax.servlet.http.HttpServletRequest, 
 *  javax.servlet.http.HttpServletResponse)
 *///from w w  w .  j a  v  a 2 s.  co m
public void process(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException {
    SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context = null;
    try {
        //Decode SOAP message
        AbstractDecodingFactory decFactory = AbstractDecodingFactory.createInstance(servletRequest,
                servletResponse, SAMLConstants.SAML2_SOAP11_BINDING_URI, null);

        SAMLMessageDecoder decoder = decFactory.getDecoder();
        context = decFactory.getContext();
        context.setLocalEntityId(_sEntityID);
        context.setLocalEntityMetadata(_entityDescriptor);

        //Decode request
        try {
            decoder.decode(context);
        } catch (SecurityException e) {
            _logger.debug("Could not decode inbound message due to security exception", e);
            throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
        }

        //verify saml message in request
        SignableSAMLObject requestMessage = context.getInboundSAMLMessage();

        if (_logger.isDebugEnabled()) {
            if (requestMessage != null)
                logXML(requestMessage);
        }

        //Validate requestor and signature
        validateRequest(context, SPSSODescriptor.DEFAULT_ELEMENT_NAME);

        _protocol.processProtocol(context);
        //DD TOKEN_DEREFERENCE events are used for artifact resolution
        _eventLogger.info(new RequestorEventLogItem(null, null, null,
                RequestorEvent.TOKEN_DEREFERENCE_SUCCESSFUL, null, servletRequest.getRemoteAddr(),
                context.getInboundMessageIssuer(), this, context.getOutboundSAMLMessageId()));

        sendResponse(context, servletRequest, servletResponse);
    } catch (StatusException e) //SAML processing error
    {
        _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null,
                servletRequest.getRemoteAddr(), e.getRequestorID(), this, e.getMessage()));

        sendResponse(context, servletRequest, servletResponse);
    } catch (MessageDecodingException e) //SOAP binding processing error  
    {
        _logger.debug("SOAP decoding error", e);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.REQUEST_INVALID, null,
                servletRequest.getRemoteAddr(), null, this, "SOAP Fault"));
        SOAP11Utils.sendSOAPFault(context, RequestorEvent.REQUEST_INVALID);
    } catch (SAML2SecurityException e)
    //The message does not meet the required security constraints
    {
        //DD Security error -> Return a "403 Forbidden" response [saml-bindings-2.0-os r370]
        _logger.debug("Security error", e);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null,
                servletRequest.getRemoteAddr(), null, this, "Security Fault"));
        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e1) {
            _logger.warn("Could not send response", e1);
        }
    } catch (OAException e) //Internal error
    {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not process SAML request message", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:opendap.threddsHandler.StaticCatalogDispatch.java

private void browseRemoteCatalog(Request oRequest, HttpServletResponse response, String query)
        throws IOException, SaxonApiException {

    String http = "http://";

    // Sanitize the incoming query.
    query = query.substring("browseCatalog=".length(), query.length());
    String remoteCatalog = Scrub.completeURL(query);

    if (!remoteCatalog.startsWith(http)) {
        log.error("Catalog Must be remote: " + Scrub.completeURL(remoteCatalog));
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Catalog Must be remote: " + remoteCatalog);
        return;/*from w  w  w .  jav a  2  s  . c  o m*/
    }

    // Build URL for remote system:

    String remoteHost = remoteCatalog.substring(0, remoteCatalog.indexOf('/', http.length()) + 1);
    String remoteRelativeURL = remoteCatalog.substring(0, remoteCatalog.lastIndexOf('/') + 1);

    log.debug("Remote Catalog: " + remoteCatalog);
    log.debug("Remote Catalog Host: " + remoteHost);
    log.debug("Remote Catalog RelativeURL: " + remoteRelativeURL);

    // Go get the target catalog:
    HttpClient httpClient = new HttpClient();
    GetMethod request = new GetMethod(remoteCatalog);
    int statusCode = httpClient.executeMethod(request);

    if (statusCode != HttpStatus.SC_OK) {
        log.error("Can't find catalog: " + remoteCatalog);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Can't find catalog: " + remoteCatalog);
        return;
    }
    InputStream catDocIs = null;

    try {
        catDocIs = request.getResponseBodyAsStream();
        catalogToHtmlTransformLock.lock();
        catalogToHtmlTransform.reloadTransformIfRequired();

        // Build the catalog document as an XdmNode.
        XdmNode catDoc = catalogToHtmlTransform.build(new StreamSource(catDocIs));

        catalogToHtmlTransform.setParameter("dapService", oRequest.getDapServiceLocalID());
        catalogToHtmlTransform.setParameter("docsService", oRequest.getDocsServiceLocalID());

        catalogToHtmlTransform.setParameter("remoteHost", remoteHost);
        catalogToHtmlTransform.setParameter("remoteRelativeURL", remoteRelativeURL);
        catalogToHtmlTransform.setParameter("remoteCatalog", remoteCatalog);

        // Set up the Http headers.
        response.setContentType("text/html");
        response.setHeader("Content-Description", "thredds_catalog");
        response.setStatus(HttpServletResponse.SC_OK);

        // Send the transformed documet.
        catalogToHtmlTransform.transform(catDoc, response.getOutputStream());

        log.debug("Used saxon to send THREDDS catalog (XML->XSLT(saxon)->HTML).");

    } catch (SaxonApiException sapie) {
        if (response.isCommitted()) {
            return;
        }
        // Set up the Http headers.
        response.setContentType("text/html");
        response.setHeader("Content-Description", "ERROR");
        response.setStatus(HttpServletResponse.SC_BAD_GATEWAY);

        // Responed with error.
        response.sendError(HttpServletResponse.SC_BAD_GATEWAY,
                "Remote resource does not appear to reference a THREDDS Catalog.");
    } finally {
        // Clean up the transform before releasing it.
        catalogToHtmlTransform.clearAllParameters();

        if (catDocIs != null) {
            try {
                catDocIs.close();
            } catch (IOException e) {
                log.error("Failed to close InputStream for " + remoteCatalog + " Error Message: "
                        + e.getMessage());
            }
        }
        catalogToHtmlTransformLock.unlock();
    }

}

From source file:com.liferay.portal.servlet.ImageServlet.java

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    String path = req.getPathInfo();

    // The image id may be passed in as image_id, img_id, or i_id

    String imageId = ParamUtil.getString(req, "image_id");

    if (Validator.isNull(imageId)) {
        imageId = ParamUtil.getString(req, "img_id");

        if (Validator.isNull(imageId)) {
            imageId = ParamUtil.getString(req, "i_id");
        }//ww  w.j ava  2  s.  c  o  m
    }

    // Company Logo

    if (path.startsWith("/company_logo")) {
        if (ParamUtil.get(req, "png", false)) {
            imageId += ".png";

            res.setContentType("image/png");
        } else if (ParamUtil.get(req, "wbmp", false)) {
            imageId += ".wbmp";

            res.setContentType("image/vnd.wap.wbmp");
        }
    }

    // Image Gallery

    if (path.startsWith("/image_gallery")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".image_gallery.")) {

            imageId = _companyId + ".image_gallery." + imageId;

            if (ParamUtil.get(req, "small", false)) {
                imageId += ".small";
            } else {
                imageId += ".large";
            }
        }
    }

    // Journal Article

    if (path.startsWith("/journal/article")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".journal.article.")) {

            imageId = _companyId + ".journal.article." + imageId;

            String version = req.getParameter("version");

            if (Validator.isNotNull(version)) {
                imageId += "." + version;
            }
        }
    }

    // Journal Template

    if (path.startsWith("/journal/template")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".journal.template.")) {

            imageId = _companyId + ".journal.template." + imageId;
            imageId += ".small";
        }
    }

    // Shopping Item

    else if (path.startsWith("/shopping/item")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".shopping.item.")) {

            imageId = _companyId + ".shopping.item." + imageId;

            if (ParamUtil.get(req, "small", false)) {
                imageId += ".small";
            } else if (ParamUtil.get(req, "medium", false)) {
                imageId += ".medium";
            } else {
                imageId += ".large";
            }
        }
    }

    Image image = ImageLocalUtil.get(imageId);

    if (Validator.isNull(imageId)) {
        _log.error("Image id should never be null or empty, path is " + req.getPathInfo());
    }

    if (image == null) {
        _log.error("Image should never be null");
    } else {
        if (Validator.isNotNull(image.getType())) {
            res.setContentType("image/" + image.getType());
        }

        /*res.setHeader(
           "Cache-control", "max-age=" + Long.toString(Time.WEEK));*/

        try {
            if (!res.isCommitted()) {
                ServletOutputStream out = res.getOutputStream();

                out.write(image.getTextObj());
                out.flush();
            }
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }
    }
}