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:de.innovationgate.wgpublisher.WGPDispatcher.java

private void commitResponse(javax.servlet.http.HttpServletResponse response) {
    if (!response.isCommitted()) {
        try {//from  www  .j  a v  a  2 s .co  m
            response.flushBuffer();
        } catch (IOException e) {
        }
    }
}

From source file:org.josso.liferay6.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  ava2s . c o  m
    }

    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;
        }

        String nodeId = hreq.getParameter("josso_node");
        if (nodeId != null) {
            if (log.isDebugEnabled())
                log.debug("Storing JOSSO Node id : " + nodeId);
            _agent.setAttribute(hreq, hres, "JOSSO_NODE", nodeId);
        } else {
            nodeId = _agent.getAttribute(hreq, "JOSSO_NODE");
            if (log.isDebugEnabled())
                log.debug("Found JOSSO Node id : " + nodeId);
        }

        // ------------------------------------------------------------------
        // 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.hoteia.qalingo.core.web.mvc.interceptor.RefererOriginActionInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    try {/*w w w  .  j a  v a  2  s  .co  m*/
        String referer = request.getHeader(Constants.REFERER);
        if (StringUtils.isNotEmpty(referer) && !referer.startsWith("http:/.qalingo.com")
                && !referer.startsWith("http://www.qalingo.com")
                && !referer.startsWith("https://www.qalingo.com")) {

            logger.debug("Referer :" + referer);

            final String regexp = ".*\\.facebook\\..*|.*\\.twitter\\..*|.*\\.yahoo\\..*|.*\\.google\\..*|.*\\.bing\\..*";

            if (referer.matches(regexp)) {
                String targetUrl = request.getRequestURI().replace(request.getContextPath(), "");
                if (!targetUrl.contains("oauth") & !targetUrl.contains("openid")) {
                    final String remoteAddress = requestUtil.getRemoteAddr(request);
                    logger.debug("Referer matchs: '" + referer + "', remoteAddress:" + remoteAddress);

                    GeolocData geolocData = geolocService.getGeolocData(remoteAddress);
                    if (geolocData != null && geolocData.getCountry() != null) {
                        MarketArea marketAreaGeoloc = null;
                        List<MarketArea> marketAreas = marketService
                                .findMarketAreaOpenedByGeolocCountryCode(geolocData.getCountry().getIsoCode());
                        if (marketAreas != null) {
                            if (marketAreas.size() == 1) {
                                marketAreaGeoloc = marketAreas.get(0);
                            } else {
                                // WE HAVE MANY MARKET AREA FOR THE CURRENT COUNTRY CODE - WE SELECT THE DEFAULT MARKET PLACE ASSOCIATE
                                for (MarketArea marketAreaIt : marketAreas) {
                                    if (marketAreaIt.getMarket().getMarketPlace().isDefault()) {
                                        marketAreaGeoloc = marketAreaIt;
                                    }
                                }
                            }
                        }

                        if (marketAreaGeoloc != null) {
                            String context = "/" + marketAreaGeoloc.getCode() + "/"
                                    + marketAreaGeoloc.getDefaultLocalization().getCode() + "/";
                            String newSegmentl = urlService.getSeoSegmentMain(
                                    marketAreaGeoloc.getDefaultLocalization().getLocale(), true);
                            String[] splits = request.getRequestURI().split("/");
                            String target = "";
                            int count = 0;
                            for (String split : splits) {
                                if (count == (splits.length - 1)) {
                                    target = split;
                                }
                                count++;
                            }

                            final RequestData requestData = requestUtil.getRequestData(request);
                            String newUrl = context.toLowerCase() + newSegmentl + "/" + target;
                            String newAbsoluteUrl = urlService.buildAbsoluteUrl(requestData, newUrl);

                            if (!response.isCommitted() && !newAbsoluteUrl.contains(targetUrl)) {
                                response.sendRedirect(newAbsoluteUrl);
                            }
                            logger.debug("Redirect to:" + newAbsoluteUrl);
                        }

                    } else {
                        logger.debug("Can't redirect geoloc is empty, IP:" + remoteAddress);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error("Referer origin action failed", e);
    }
    return true;
}

From source file:opendap.threddsHandler.StaticCatalogDispatch.java

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

    String http = "http://";

    // Sanitize the incoming query.
    query = Scrub.completeURL(query);/*from w w  w. j  a va2  s  . c o  m*/
    log.debug("Processing query string: " + query);

    if (!query.startsWith("browseDataset=")) {
        log.error("Not a browseDataset request: " + Scrub.completeURL(query));
        throw new IOException("Not a browseDataset request!");
    }

    query = query.substring("browseDataset=".length(), query.length());

    String targetDataset = query.substring(0, query.indexOf('&'));

    String remoteCatalog = query.substring(query.indexOf('&') + 1, query.length());

    if (!remoteCatalog.startsWith(http)) {
        log.error("Catalog Must be remote: " + remoteCatalog);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Catalog Must be remote: " + remoteCatalog);
        return;
    }

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

    log.debug("targetDataset: " + targetDataset);
    log.debug("remoteCatalog: " + remoteCatalog);
    log.debug("remoteHost: " + remoteHost);

    // 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();
        datasetToHtmlTransformLock.lock();
        datasetToHtmlTransform.reloadTransformIfRequired();

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

        datasetToHtmlTransform.setParameter("docsService", oRequest.getDocsServiceLocalID());
        datasetToHtmlTransform.setParameter("targetDataset", targetDataset);
        datasetToHtmlTransform.setParameter("remoteCatalog", remoteCatalog);
        datasetToHtmlTransform.setParameter("remoteHost", remoteHost);

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

        // Send the transformed document.
        datasetToHtmlTransform.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 {
        datasetToHtmlTransform.clearAllParameters();

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

}

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

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

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

    WeblogResourceRequest resourceRequest = null;
    try {
        // parse the incoming request and extract the relevant data
        resourceRequest = new WeblogResourceRequest(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;
    }

    log.debug("Resource requested [" + resourceRequest.getResourcePath() + "]");

    long resourceLastMod = 0;
    InputStream resourceStream = null;

    // first see if resource comes from weblog's shared theme
    try {
        WeblogTheme weblogTheme = weblog.getTheme();
        if (weblogTheme != null) {
            ThemeResource resource = weblogTheme.getResource(resourceRequest.getResourcePath());
            if (resource != null) {
                resourceLastMod = resource.getLastModified();
                resourceStream = resource.getInputStream();
            }
        }
    } catch (Exception ex) {
        // hmmm, some kind of error getting theme.  that's an error.
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // if not from theme then see if resource is in weblog's upload dir
    if (resourceStream == null) {
        try {
            MediaFileManager mmgr = WebloggerFactory.getWeblogger().getMediaFileManager();
            MediaFile mf = mmgr.getMediaFileByOriginalPath(weblog, resourceRequest.getResourcePath());
            resourceLastMod = mf.getLastModified();
            resourceStream = mf.getInputStream();

        } 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
    response.setContentType(this.context.getMimeType(resourceRequest.getResourcePath()));

    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 (Exception 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:org.josso.gl2.agent.SSOAgentValve.java

/**
 * Perform single-sign-on support processing for this request.
 *
 * @param request  The servlet request we are processing
 * @param response The servlet response we are creating
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet error occurs
 *//*from  ww w  .  j  a  v a2  s .c  om*/
public int invoke(Request request, Response response) throws IOException, ServletException {

    // If this is not an HTTP request and response, just pass them on
    int ret = 0;
    if (!(request instanceof HttpRequest) || !(response instanceof HttpResponse)) {
        //context.invokeNext(request, response);
        ret = Valve.INVOKE_NEXT;
        return ret;
    }

    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    HttpServletResponse hres = (HttpServletResponse) response.getResponse();

    if (debug >= 1)
        log("***Processing : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "] path="
                + hreq.getPathInfo());
    try {
        container = (Container) request.getContext();
    } catch (Exception e) {
        log("Erreur sur cast container", e);
    }
    try {
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();
        _agent.setCatalinaContainer(container);

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";
        // T1 si l'appli n'est pas partenaire alors pas de SSO on continue
        if (!_agent.isPartnerApp(vhost, contextPath)) {
            if (debug >= 1)
                log("T1 Context is not a josso partner app : " + hreq.getContextPath());
            hres.sendError(hres.SC_UNAUTHORIZED, "vrifier config agent ajouter le contexte");
            ret = Valve.END_PIPELINE;
            return ret;
        } else {
            log("T1 Context IS a josso partner app =" + hreq.getContextPath());
        }

        // T2 ------------------------------------------------------------------
        // 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());
        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        //T9
        if (isResourceIgnored(cfg, request)) {
            log("T9 ressource non ssois (accs libre)");
            ret = Valve.INVOKE_NEXT;
            return ret;
        }

        // Get our session ...
        session = getSession(((HttpRequest) request), true);
        testCookieSession(hreq);

        //T3 on revient aprs authentification russie et pour finalisation
        if (_agent.isSSOIDloged(jossoSessionId)) {
            iBoucle++;
            log("T3 SSOAgentValve Info retour authentifi pour " + jossoSessionId + " faire retour vers "
                    + theOriginal);
            //**********************************************************************************************
            localSession = new CatalinaLocalSession(session);
            //T4 on revrifie ma prsence d'une entre SSOID
            SSOAgentRequest r = new CatalinaSSOAgentRequest(SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT,
                    jossoSessionId, localSession);
            SingleSignOnEntry entry = _agent.processRequest(r);

            if (debug == 1)
                log("T3 Executed agent acction ACTION_ESTABLISH_SECURITY_CONTEXT");
            // ------------------------------------------------------------------
            // Has a valid user already been authenticated?
            // ------------------------------------------------------------------
            //T3-1
            if (entry != null) {
                if (debug == 1)
                    log("T3-1 Principal '" + entry.principal + "' has already been authenticated");
                // TODO : Not supported
                // (request).setAuthType(entry.authType);
                // (request).setUserPrincipal(entry.principal);
                //T3-2
            } else {
                log("T3-2 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(), "-");
                    hres.addCookie(cookie);
                }
                //T3-2-1
                if (cookie != null
                        || (getSavedRequestURL(session) == null && _agent.isAutomaticLoginRequired(hreq))) {

                    if (debug == 1)
                        log("T3-2-1 SSO Session is not valid, attempting automatic login");

                    // Save current request, so we can co back to it later ...
                    log("T3-2-1 ***On sauve la requte 2 ***");
                    saveRequest((HttpRequest) request, session);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (debug == 1)
                        log("T3-2-1 Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    ret = Valve.INVOKE_NEXT;
                    return ret;
                } else {
                    if (debug == 1)
                        log("T3-2-1 SSO cookie is not present, but login optional process is not required");
                }

            }

            try {
                log("Avant sur webProgrammaticLogin -------------" + iBoucle);

                if (!WebProgrammaticLogin.login(jossoSessionId, assertionId, "jossoRealm", hreq, hres)) {
                    log("Erreur sur webProgrammaticLogin");
                } else {
                    log("Russite sur webProgrammaticLogin");
                }
                log("Aprs sur webProgrammaticLogin-------------" + iBoucle);
            } catch (Exception err) {
                log("SSOAgentValve Erreur2 finalisation contexte securit", err);
                throw err;
            }
            // 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);

            //hres.sendRedirect(theOriginal);
            System.out.println("**********************Termin**********************");
            ret = Valve.INVOKE_NEXT;
            return ret;
        } else {
            log("T3 SSOAgentValve Info retour pas authentifi pour " + jossoSessionId);
            iBoucle = 0;
        }
        String username = processAuthorizationToken(hreq);
        //TA2
        //equivalent  la page de login si pas autoris on passe par l'authent
        if (username == null && getSavedRequestURL(session) == null
                && !hreq.getRequestURI().endsWith(_agent.getJOSSOLoginUri())
                && !hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) {
            log("TA2 Il faut une authentification pralable (premire URL)! session=" + session.getId());
            //return sendAuthenticateChallenge(msgInfo);
            //return sendAuthenticateChallenge2(msgInfo);
            saveRequest((HttpRequest) request, session);
            theOriginal = getSavedRequestURL(session);
            hres.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            //response.setHeader("Location", jeVeux);
            hres.sendRedirect(hreq.getContextPath() + "/josso_login/");
            ret = Valve.END_PIPELINE;
            return ret;
        }
        //T4
        // ------------------------------------------------------------------
        // Check if the partner application required the login form
        // ------------------------------------------------------------------
        if (debug >= 1)
            log("T4 Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'");

        // /josso_login/ ou /josso_user_login/ c'est pas la page de login qui fait cela ?
        if (hreq.getRequestURI().endsWith(_agent.getJOSSOLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) {

            if (debug >= 1)
                log("T4 josso_login_request received for uri '" + 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, session, true);
            } else {
                saveLoginBackToURL(hreq, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (debug >= 1)
                log("T4 Redirecting to login url '" + loginUrl + "'");

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
            //question on termine ou on continue
            ret = Valve.END_PIPELINE;
            return ret;

        }
        //T5
        // ------------------------------------------------------------------
        // Check if the partner application required a logout
        // ------------------------------------------------------------------
        if (debug >= 1)
            log("T5 Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJOSSOLogoutUri())) {

            if (debug >= 1)
                log("T5 josso_logout request received for uri '" + hreq.getRequestURI() + "'");

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

            if (debug >= 1)
                log("T5 Redirecting to logout url '" + logoutUrl + "'");

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

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

            ret = Valve.END_PIPELINE;
            return ret;

        }
        //T6
        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        testCookieSession(hreq);
        if (debug >= 1)
            log("T6 Session is: " + session);
        //localSession = new CatalinaLocalSession(session);
        //T7
        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------
        // /josso_authentication/
        if (debug >= 1) {
            log("T7 Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJOSSOAuthenticationUri())) {

            if (debug >= 1)
                log("T7 josso_authentication received for uri '" + hreq.getRequestURI() + "'");

            HttpSSOAgentRequest customAuthRequest = new HttpSSOAgentRequest(
                    SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession);

            customAuthRequest.setRequest(hreq);
            customAuthRequest.setResponse(hres);
            customAuthRequest.setContext(request.getContext());

            _agent.processRequest(customAuthRequest);

            ret = Valve.INVOKE_NEXT;
            return ret;
        }
        //T8
        // si pas de cookie de session SSO
        if (cookie == null || cookie.getValue().equals("-")) {

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

            if (debug >= 1)
                log("T8 SSO cookie is not present, verifying optional login process ");
            //T8-1  /josso_security_check
            // 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 (debug >= 1)
                    log("T8-1 " + _agent.getJOSSOSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = this.getSavedRequestURL(session);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                ret = Valve.INVOKE_NEXT;
                return ret;

            }
            //T8-2
            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())) {

                // If saved request is NOT null, we're in the middle of another process ...
                if (!isResourceIgnored(cfg, request) && _agent.isAutomaticLoginRequired(hreq)) {

                    if (debug >= 1)
                        log("T8-2 SSO cookie is not present, attempting automatic login");

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

                    if (debug >= 1)
                        log("T8-2 Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    ret = Valve.END_PIPELINE;
                    return ret;
                } else {
                    if (debug >= 1)
                        log("T8-2 SSO cookie is not present, but login optional process is not required");
                }
            }
            //T8-3
            if (debug >= 1)
                log("T8-3 SSO cookie is not present, checking for outbound relaying");

            if (!(hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log("T8-3 SSO cookie not present and relaying was not requested, skipping");
                //context.invokeNext(request, response);
                ret = Valve.INVOKE_NEXT;
                return ret;
            }

        }

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

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

        _agent.setCatalinaContainer((Container) request.getContext());
        //T10  /josso_security_check
        // ------------------------------------------------------------------
        // Check if a user has been authenticated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (debug >= 1)
            log("T10 Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

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

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

            assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            HttpSSOAgentRequest relayRequest;

            relayRequest = new HttpSSOAgentRequest(SSOAgentRequest.ACTION_RELAY, null, localSession,
                    assertionId);
            if (debug >= 1)
                log("T10 Outbound relaying requested for assertion id=" + assertionId + " sessionID="
                        + relayRequest.getSessionId());

            relayRequest.setRequest(hreq);
            relayRequest.setResponse(hres);
            relayRequest.setContext(request.getContext());

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            //T10-1
            if (entry == null) {
                // This is wrong! We should have an entry here!
                if (debug >= 1)
                    log("T10-1 Outbound relaying failed for assertion id [" + assertionId
                            + "], no Principal found.");
                // Throw an exception, we will handle it below !
                throw new RuntimeException(
                        "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!");
            }
            //T10-2
            if (debug >= 1)
                log("T10-2 Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (debug >= 1)
                log("T10-2 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
            securityCheck(hreq, hres, entry, cfg, "T10");
            /*try {
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId);
            hres.addCookie(cookie);
            } catch (Exception e) {
            log("Pas de bras pas de chocolat !", e);
            }
            jossoSessionId = entry.ssoId;
            //T10-3
            //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise
            String requestURI = getSavedSplashResource(session.getSession());
            if(requestURI == null) {
            requestURI = getSavedRequestURL(session);
            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 (debug >= 1)
            log("T10-3 No saved request found, using : '" + requestURI + "'");
            }
            }
                    
            clearSavedRequestURLs(session);
            _agent.clearAutomaticLoginReferer(hreq);
            _agent.prepareNonCacheResponse(hres);
            //T10-4
            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
            String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
            if (debug >= 1)
            log("T10-4 Redirecting to post-auth-resource '" + postAuthURL  + "'");
            hres.sendRedirect(postAuthURL);
            } else {
            if (debug >= 1)
            log("T10-4 Redirecting to original '" + requestURI + "'");
            hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            //on garde des fois que ...
            theOriginal = hres.encodeRedirectURL(requestURI);
            }
            _agent.addEntrySSOIDsuccessed(entry.ssoId);
            log("T10 Fin josso_check jossoSessionId="+jossoSessionId);*/
            //c'est pas fini et pas en erreur pourtant ...
            ret = Valve.END_PIPELINE;
            return ret;
        }
        //T11
        // si on arrive la c'est une erreur!
        log("T11 Fin de la boucle validate donc tout va bien");
        ret = Valve.INVOKE_NEXT;
        return ret;
    } catch (Throwable t) {
        //  This is a 'hack' : Because this valve exectues before the ErrorReportingValve, we need to preapare
        // some stuff and invoke the next valve in the chain always ...

        // Store this error, it will be checked by the ErrorReportingValve
        hreq.setAttribute(Globals.EXCEPTION_ATTR, t);

        // Mark this response as error!
        response.setError();

        // Let the next valves work on this
        //context.invokeNext(request, response);
        ret = Valve.END_PIPELINE;

    } finally {
        if (debug >= 1)
            log("Processed : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "] ret=" + ret);
        //return ret;
    }
    log("retourne ret=" + ret);
    return ret;

}

From source file:org.hoteia.qalingo.core.web.mvc.controller.oauth.CallBackOAuthTwitterController.java

@RequestMapping("/callback-oauth-twitter.html*")
public ModelAndView callBackTwitter(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    final RequestData requestData = requestUtil.getRequestData(request);

    // SANITY CHECK
    if (!requestUtil.hasKnownCustomerLogged(request)) {
        try {/* w  w  w  .ja va2s  .c  o  m*/

            // CLIENT ID
            EngineSetting clientIdEngineSetting = engineSettingService.getSettingOAuthAppKeyOrId();
            EngineSettingValue clientIdEngineSettingValue = clientIdEngineSetting
                    .getEngineSettingValue(OAuthType.TWITTER.name());

            // CLIENT SECRET
            EngineSetting clientSecretEngineSetting = engineSettingService.getSettingOAuthAppSecret();
            EngineSettingValue clientSecretEngineSettingValue = clientSecretEngineSetting
                    .getEngineSettingValue(OAuthType.TWITTER.name());

            // CLIENT PERMISSIONS
            EngineSetting permissionsEngineSetting = engineSettingService.getSettingOAuthAppPermissions();
            EngineSettingValue permissionsEngineSettingValue = permissionsEngineSetting
                    .getEngineSettingValue(OAuthType.TWITTER.name());

            if (clientIdEngineSettingValue != null && clientSecretEngineSetting != null
                    && permissionsEngineSettingValue != null) {
                final String clientId = clientIdEngineSettingValue.getValue();
                final String clientSecret = clientSecretEngineSettingValue.getValue();

                final String twitterCallBackURL = urlService.buildAbsoluteUrl(requestData, urlService
                        .buildOAuthCallBackUrl(requestData, OAuthType.TWITTER.getPropertyKey().toLowerCase()));

                OAuthService service = new ServiceBuilder().provider(TwitterApi.class).apiKey(clientId)
                        .apiSecret(clientSecret).callback(twitterCallBackURL).build();

                final String code = request.getParameter(REQUEST_PARAM_OAUTH_VERIFIER);
                if (StringUtils.isNotEmpty(code)) {
                    Verifier verifier = new Verifier(code);
                    Token requestToken = (Token) request.getSession().getAttribute(TWITTER_OAUTH_REQUEST_TOKEN);

                    Token accessToken = service.getAccessToken(requestToken, verifier);
                    OAuthRequest oauthRequest = new OAuthRequest(Verb.GET, TWITTER_URL);
                    service.signRequest(accessToken, oauthRequest);
                    Response oauthResponse = oauthRequest.send();
                    int responseCode = oauthResponse.getCode();
                    String responseBody = oauthResponse.getBody();

                    if (responseCode == 200) {
                        handleAuthenticationData(request, response, requestData, OAuthType.TWITTER,
                                responseBody);
                    } else {
                        logger.error("Callback With " + OAuthType.TWITTER.name() + " failed!");
                    }
                } else {
                    logger.error("Callback With " + OAuthType.TWITTER.name() + " failed!");
                }

            }

        } catch (Exception e) {
            logger.error("Callback With " + OAuthType.TWITTER.name() + " failed!");
        }
    }

    // DEFAULT FALLBACK VALUE
    if (!response.isCommitted()) {
        response.sendRedirect(urlService.generateUrl(FoUrls.LOGIN, requestData));
    }

    return null;
}

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

@SuppressWarnings("rawtypes")
public ModelAndView handleURI(final String originalUri, GrailsWebRequest grailsWebRequest, Map params) {
    Assert.notNull(originalUri, "Controller URI [" + originalUri + "] cannot be null!");

    HttpServletRequest request = grailsWebRequest.getCurrentRequest();
    HttpServletResponse response = grailsWebRequest.getCurrentResponse();

    String uri = originalUri;//from  w ww  .ja v  a2  s. com
    if (uri.endsWith("/")) {
        uri = uri.substring(0, uri.length() - 1);
    }

    // Step 2: lookup the controller in the application.
    GrailsControllerClass controllerClass = null;
    if (!WebUtils.isIncludeRequest(request) && request.getAttribute(FORWARD_IN_PROGRESS) == null) {

        Object attribute = grailsWebRequest.getAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS,
                WebRequest.SCOPE_REQUEST);
        if (attribute instanceof GrailsControllerClass) {
            controllerClass = (GrailsControllerClass) attribute;
            Boolean canUse = (Boolean) grailsWebRequest.getAttribute(
                    GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS_AVAILABLE, WebRequest.SCOPE_REQUEST);
            if (canUse == null) {
                controllerClass = null;
            } else {
                grailsWebRequest.removeAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS_AVAILABLE,
                        WebRequest.SCOPE_REQUEST);
            }
        }
    }

    if (controllerClass == null) {
        controllerClass = getControllerClassByURI(uri);
    }

    if (controllerClass == null) {
        throw new UnknownControllerException("No controller found for URI [" + uri + "]!");
    }

    String actionName = controllerClass.getMethodActionName(uri);
    if (controllerClass.isFlowAction(actionName)) {
        // direct access to flow action not allowed
        return null;
    }
    grailsWebRequest.setActionName(actionName);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Processing request for controller action [" + actionName + "]");
    }
    // Step 3: load controller from application context.
    GroovyObject controller = getControllerInstance(controllerClass);

    if (!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) {
        try {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return null;
        } catch (IOException e) {
            throw new ControllerExecutionException("I/O error sending 403 error", e);
        }
    }

    request.setAttribute(GrailsApplicationAttributes.CONTROLLER, controller);

    // Step 4: Set grails attributes in request scope
    request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes);

    // Step 5: get the view name for this URI.
    String viewName = controllerClass.getViewByURI(uri);

    boolean executeAction = invokeBeforeInterceptor(controller, actionName, controllerClass);
    // if the interceptor returned false don't execute the action
    if (!executeAction) {
        return null;
    }

    ModelAndView mv = executeAction(controller, actionName, viewName, grailsWebRequest, params);

    boolean returnModelAndView = invokeAfterInterceptor(controllerClass, controller, actionName, mv)
            && !response.isCommitted();
    return returnModelAndView ? mv : null;
}

From source file:org.hoteia.qalingo.core.web.mvc.controller.oauth.CallBackGoogleAccountController.java

@RequestMapping("/callback-oauth-google-account.html*")
public ModelAndView callBackGoogleAccount(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    final RequestData requestData = requestUtil.getRequestData(request);

    // SANITY CHECK
    if (!requestUtil.hasKnownCustomerLogged(request)) {
        try {//  ww w  . j a v  a 2  s  .  c om

            // CLIENT ID
            EngineSetting clientIdEngineSetting = engineSettingService.getOAuthAppKeyOrId();
            EngineSettingValue clientIdEngineSettingValue = clientIdEngineSetting
                    .getEngineSettingValue(OAuthType.GOOGLE_ACCOUNT.name());

            // CLIENT SECRET
            EngineSetting clientSecretEngineSetting = engineSettingService.getOAuthAppSecret();
            EngineSettingValue clientSecretEngineSettingValue = clientSecretEngineSetting
                    .getEngineSettingValue(OAuthType.GOOGLE_ACCOUNT.name());

            // CLIENT PERMISSIONS
            EngineSetting permissionsEngineSetting = engineSettingService.getOAuthAppPermissions();
            EngineSettingValue permissionsEngineSettingValue = permissionsEngineSetting
                    .getEngineSettingValue(OAuthType.GOOGLE_ACCOUNT.name());

            if (clientIdEngineSettingValue != null && clientSecretEngineSetting != null
                    && permissionsEngineSettingValue != null) {
                final String clientId = clientIdEngineSettingValue.getValue();
                final String clientSecret = clientSecretEngineSettingValue.getValue();
                final String permissions = permissionsEngineSettingValue.getValue();

                final String googleAccountCallBackURL = urlService.buildAbsoluteUrl(requestData,
                        urlService.buildOAuthCallBackUrl(requestData,
                                OAuthType.GOOGLE_ACCOUNT.getPropertyKey().toLowerCase()));

                OAuthService service = new ServiceBuilder().provider(Google2Api.class).apiKey(clientId)
                        .apiSecret(clientSecret).scope(permissions).callback(googleAccountCallBackURL).build();

                final String code = request.getParameter("code");
                if (StringUtils.isNotEmpty(code)) {
                    Verifier verifier = new Verifier(code);
                    Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
                    OAuthRequest oauthRequest = new OAuthRequest(Verb.GET, GOOGLE_ME_URL);
                    service.signRequest(accessToken, oauthRequest);
                    Response oauthResponse = oauthRequest.send();
                    int responseCode = oauthResponse.getCode();
                    String responseBody = oauthResponse.getBody();

                    if (responseCode == 200) {
                        handleAuthenticationData(request, response, requestData, OAuthType.FACEBOOK,
                                responseBody);
                    } else {
                        logger.error("Callback With " + OAuthType.GOOGLE_ACCOUNT.name() + " failed!");
                    }
                } else {
                    logger.error("Callback With " + OAuthType.GOOGLE_ACCOUNT.name() + " failed!");
                }
            }

        } catch (Exception e) {
            logger.error("Callback With " + OAuthType.GOOGLE_ACCOUNT.name() + " failed!");
        }
    }

    // DEFAULT FALLBACK VALUE
    if (!response.isCommitted()) {
        response.sendRedirect(urlService.generateUrl(FoUrls.LOGIN, requestData));
    }

    return null;
}

From source file:com.bst.tags.TableTag.java

/**
 * Will write the export. The default behavior is to write directly to the response. If the ResponseOverrideFilter
 * is configured for this request, will instead write the exported content to a map in the Request object.
 * @param exportView export view//from ww w. j  a  v a 2 s.com
 * @throws JspException for problem in clearing the response or for invalid export views
 * @throws IOException exception thrown when writing content to the response
 */
protected void writeExport(ExportView exportView) throws IOException, JspException {
    String filename = properties.getExportFileName(this.currentMediaType);

    HttpServletResponse response = (HttpServletResponse) this.pageContext.getResponse();
    HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();

    Map bean = (Map) request.getAttribute(FILTER_CONTENT_OVERRIDE_BODY);
    boolean usingFilter = bean != null;

    String mimeType = exportView.getMimeType();
    // original encoding, be sure to add it back after reset()
    String characterEncoding = response.getCharacterEncoding();

    if (usingFilter) {
        if (!bean.containsKey(TableTagParameters.BEAN_BUFFER)) {
            // We are running under the export filter, call it
            log.debug("Exportfilter enabled in unbuffered mode, setting headers");
            response.addHeader(TableTagParameters.PARAMETER_EXPORTING, TagConstants.EMPTY_STRING);
        } else {
            // We are running under the export filter in buffered mode
            bean.put(TableTagParameters.BEAN_CONTENTTYPE, mimeType);
            bean.put(TableTagParameters.BEAN_FILENAME, filename);

            if (exportView instanceof TextExportView) {
                StringWriter writer = new StringWriter();
                ((TextExportView) exportView).doExport(writer);
                bean.put(TableTagParameters.BEAN_BODY, writer.toString());
            } else if (exportView instanceof BinaryExportView) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                ((BinaryExportView) exportView).doExport(stream);
                bean.put(TableTagParameters.BEAN_BODY, stream.toByteArray());

            } else {
                throw new JspTagException("Export view " + exportView.getClass().getName()
                        + " must implement TextExportView or BinaryExportView");
            }

            return;
        }
    } else {
        log.debug("Exportfilter NOT enabled");
        // response can't be already committed at this time
        if (response.isCommitted()) {
            throw new ExportException(getClass());
        }

        try {
            response.reset();
            pageContext.getOut().clearBuffer();
        } catch (Exception e) {
            throw new ExportException(getClass());
        }
    }

    if (!usingFilter && characterEncoding != null && mimeType.indexOf("charset") == -1) //$NON-NLS-1$
    {
        mimeType += "; charset=" + characterEncoding; //$NON-NLS-1$
    }

    response.setContentType(mimeType);

    if (StringUtils.isNotEmpty(filename)) {
        response.setHeader("Content-Disposition", //$NON-NLS-1$
                "attachment; filename=\"" + filename + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    }

    if (exportView instanceof TextExportView) {
        Writer writer;
        if (usingFilter) {
            writer = response.getWriter();
        } else {
            writer = pageContext.getOut();
        }

        ((TextExportView) exportView).doExport(writer);
    } else if (exportView instanceof BinaryExportView) {
        // dealing with binary content
        // note that this is not assured to work on any application server if the filter is not enabled. According
        // to the jsp specs response.getOutputStream() should no be called in jsps.
        ((BinaryExportView) exportView).doExport(response.getOutputStream());
    } else {
        throw new JspTagException("Export view " + exportView.getClass().getName()
                + " must implement TextExportView or BinaryExportView");
    }

    log.debug("Export completed");

}