Example usage for org.springframework.web.util WebUtils getSessionMutex

List of usage examples for org.springframework.web.util WebUtils getSessionMutex

Introduction

In this page you can find the example usage for org.springframework.web.util WebUtils getSessionMutex.

Prototype

public static Object getSessionMutex(HttpSession session) 

Source Link

Document

Return the best available mutex for the given session: that is, an object to synchronize on for the given session.

Usage

From source file:ch.ralscha.extdirectspring.controller.RouterController.java

@RequestMapping(value = "/poll/{beanName}/{method}/{event}")
public void poll(@PathVariable("beanName") String beanName, @PathVariable("method") String method,
        @PathVariable("event") String event, HttpServletRequest request, HttpServletResponse response,
        Locale locale) throws Exception {

    ExtDirectPollResponse directPollResponse = new ExtDirectPollResponse();
    directPollResponse.setName(event);//from  ww  w  .ja  va 2  s.com

    MethodInfo methodInfo = this.methodInfoCache.get(beanName, method);
    boolean streamResponse;
    Class<?> jsonView = null;

    if (methodInfo != null) {

        streamResponse = this.configurationService.getConfiguration().isStreamResponse()
                || methodInfo.isStreamResponse();

        try {

            Object[] parameters = this.configurationService.getParametersResolver().prepareParameters(request,
                    response, locale, methodInfo);

            if (this.configurationService.getConfiguration().isSynchronizeOnSession()
                    || methodInfo.isSynchronizeOnSession()) {
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Object mutex = WebUtils.getSessionMutex(session);
                    synchronized (mutex) {
                        Object result = ExtDirectSpringUtil.invoke(
                                this.configurationService.getApplicationContext(), beanName, methodInfo,
                                parameters);

                        if (result instanceof ModelAndJsonView) {
                            ModelAndJsonView modelAndJsonView = (ModelAndJsonView) result;
                            directPollResponse.setData(modelAndJsonView.getModel());
                            jsonView = getJsonView(modelAndJsonView, methodInfo.getJsonView());
                        } else {
                            directPollResponse.setData(result);
                            jsonView = getJsonView(result, methodInfo.getJsonView());
                        }
                    }
                } else {
                    Object result = ExtDirectSpringUtil.invoke(
                            this.configurationService.getApplicationContext(), beanName, methodInfo,
                            parameters);
                    if (result instanceof ModelAndJsonView) {
                        ModelAndJsonView modelAndJsonView = (ModelAndJsonView) result;
                        directPollResponse.setData(modelAndJsonView.getModel());
                        jsonView = getJsonView(modelAndJsonView, methodInfo.getJsonView());
                    } else {
                        directPollResponse.setData(result);
                        jsonView = getJsonView(result, methodInfo.getJsonView());
                    }
                }
            } else {
                Object result = ExtDirectSpringUtil.invoke(this.configurationService.getApplicationContext(),
                        beanName, methodInfo, parameters);
                if (result instanceof ModelAndJsonView) {
                    ModelAndJsonView modelAndJsonView = (ModelAndJsonView) result;
                    directPollResponse.setData(modelAndJsonView.getModel());
                    jsonView = getJsonView(modelAndJsonView, methodInfo.getJsonView());
                } else {
                    directPollResponse.setData(result);
                    jsonView = getJsonView(result, methodInfo.getJsonView());
                }
            }

        } catch (Exception e) {
            log.error("Error polling method '" + beanName + "." + method + "'",
                    e.getCause() != null ? e.getCause() : e);
            directPollResponse.setData(handleException(methodInfo, directPollResponse, e, request));
        }
    } else {
        log.error("Error invoking method '" + beanName + "." + method + "'. Method or Bean not found");
        handleMethodNotFoundError(directPollResponse, beanName, method);
        streamResponse = this.configurationService.getConfiguration().isStreamResponse();
    }

    writeJsonResponse(response, directPollResponse, jsonView, streamResponse);
}

From source file:ch.ralscha.extdirectspring.controller.RouterController.java

@RequestMapping(value = "/router", method = RequestMethod.POST, params = "extAction")
public String router(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("extAction") String extAction, @RequestParam("extMethod") String extMethod)
        throws IOException {

    ExtDirectResponse directResponse = new ExtDirectResponse(request);
    MethodInfo methodInfo = this.methodInfoCache.get(extAction, extMethod);

    boolean streamResponse;

    if (methodInfo != null && methodInfo.getForwardPath() != null) {
        return methodInfo.getForwardPath();
    } else if (methodInfo != null && methodInfo.getHandlerMethod() != null) {
        streamResponse = this.configurationService.getConfiguration().isStreamResponse()
                || methodInfo.isStreamResponse();

        HandlerMethod handlerMethod = methodInfo.getHandlerMethod();
        try {//w  w  w.  j  av a2 s . c o  m

            ModelAndView modelAndView;

            if (this.configurationService.getConfiguration().isSynchronizeOnSession()
                    || methodInfo.isSynchronizeOnSession()) {
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Object mutex = WebUtils.getSessionMutex(session);
                    synchronized (mutex) {
                        modelAndView = this.handlerAdapter.handle(request, response, handlerMethod);
                    }
                } else {
                    modelAndView = this.handlerAdapter.handle(request, response, handlerMethod);
                }
            } else {
                modelAndView = this.handlerAdapter.handle(request, response, handlerMethod);
            }

            Map<String, Object> model = modelAndView.getModel();
            if (model.containsKey("extDirectFormPostResult")) {
                ExtDirectFormPostResult formPostResult = (ExtDirectFormPostResult) model
                        .get("extDirectFormPostResult");
                directResponse.setResult(formPostResult.getResult());
                directResponse.setJsonView(getJsonView(formPostResult, methodInfo.getJsonView()));
            } else if (model.containsKey("edFormPostResult")) {
                EdFormPostResult formPostResult = (EdFormPostResult) model.get("edFormPostResult");
                directResponse.setResult(formPostResult.result());
                directResponse.setJsonView(getJsonView(formPostResult, methodInfo.getJsonView()));
            }

        } catch (Exception e) {
            log.error("Error calling method: " + extMethod, e.getCause() != null ? e.getCause() : e);
            directResponse.setResult(handleException(methodInfo, directResponse, e, request));
        }
    } else {
        streamResponse = this.configurationService.getConfiguration().isStreamResponse();
        log.error("Error invoking method '" + extAction + "." + extMethod + "'. Method  or Bean not found");
        handleMethodNotFoundError(directResponse, extAction, extMethod);
    }
    writeJsonResponse(response, directResponse, null, streamResponse, ExtDirectSpringUtil.isMultipart(request));

    return null;
}

From source file:org.kmnet.com.fw.web.token.transaction.HttpSessionTransactionTokenStore.java

/**
 * Returns mutex from the given session<br>
 * @param session
 * @return mutex object
 */
Object getMutex(HttpSession session) {
    return WebUtils.getSessionMutex(session);
}

From source file:org.kmnet.com.fw.web.token.transaction.TransactionTokenInterceptor.java

/**
 * Creates a new <code>TransactionToken</code> <br>
 * <p>//from w w  w.j  a  v  a 2 s  .c om
 * Generated <code>TransactionToken</code> instance is stored in <code>TransactionTokenStore</code> and also set to request
 * attribute <code>TransactionTokenInterceptor.NEXT_TOKEN</code>.
 * <p>
 * @param request
 * @param session
 * @param tokenInfo TransactionTokenInfo
 * @param generator TokenStringGenerator
 * @param tokenStore TransactionTokenStore
 */
void createToken(HttpServletRequest request, HttpSession session, TransactionTokenInfo tokenInfo,
        TokenStringGenerator generator, TransactionTokenStore tokenStore) {
    TransactionToken nextToken;
    synchronized (WebUtils.getSessionMutex(session)) {
        String tokenKey = tokenStore.createAndReserveTokenKey(tokenInfo.getTokenName());
        nextToken = new TransactionToken(tokenInfo.getTokenName(), tokenKey,
                generator.generate(session.getId()));
        tokenStore.store(nextToken);
    }
    request.setAttribute(NEXT_TOKEN_REQUEST_ATTRIBUTE_NAME, nextToken);
}

From source file:morph.plugin.views.annotation.AnnotationMethodHandlerAdapter.java

public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    if (AnnotationUtils.findAnnotation(handler.getClass(), SessionAttributes.class) != null) {
        // Always prevent caching in case of session attribute management.
        checkAndPrepare(request, response, this.cacheSecondsForSessionAttributeHandlers, true);
        // Prepare cached set of session attributes names.
    } else {/*from w w w .j  av  a 2s .  c  o  m*/
        // Uses configured default cacheSeconds setting.
        checkAndPrepare(request, response, true);
    }

    // Execute invokeHandlerMethod in synchronized block if required.
    if (this.synchronizeOnSession) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object mutex = WebUtils.getSessionMutex(session);
            synchronized (mutex) {
                return invokeHandlerMethod(request, response, handler);
            }
        }
    }

    return invokeHandlerMethod(request, response, handler);
}

From source file:ch.ralscha.extdirectspring.controller.RouterController.java

private Object processRemotingRequest(HttpServletRequest request, HttpServletResponse response, Locale locale,
        ExtDirectRequest directRequest, MethodInfo methodInfo) throws Exception {

    Object[] parameters = this.configurationService.getParametersResolver().resolveParameters(request, response,
            locale, directRequest, methodInfo);

    if (this.configurationService.getConfiguration().isSynchronizeOnSession()
            || methodInfo.isSynchronizeOnSession()) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object mutex = WebUtils.getSessionMutex(session);
            synchronized (mutex) {
                return ExtDirectSpringUtil.invoke(this.configurationService.getApplicationContext(),
                        directRequest.getAction(), methodInfo, parameters);
            }//from   w  w w.j  a  v a 2  s  . c om
        }
    }

    return ExtDirectSpringUtil.invoke(this.configurationService.getApplicationContext(),
            directRequest.getAction(), methodInfo, parameters);
}

From source file:co.paralleluniverse.springframework.web.servlet.mvc.method.annotation.FiberRequestMappingHandlerAdapter.java

@Override
protected final ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response,
        HandlerMethod handlerMethod) throws Exception {

    if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
        // Always prevent caching in case of session attribute management.
        checkAndPrepare(request, response, this.cacheSecondsForSessionAttributeHandlers, true);
    } else {/* w w w .j a v  a  2s .c o m*/
        // Uses configured default cacheSeconds setting.
        checkAndPrepare(request, response, true);
    }

    // Execute invokeHandlerMethod in synchronized block if required.
    if (this.synchronizeOnSession) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object mutex = WebUtils.getSessionMutex(session);
            synchronized (mutex) {
                return invokeHandleMethod(request, response, handlerMethod);
            }
        }
    }

    return invokeHandleMethod(request, response, handlerMethod);
}

From source file:org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter.java

public boolean authenticateRequest(ServletContext context, HttpServletRequest sreq, HttpServletResponse sresp)
        throws IOException, ServletException {
    // Check if there is an authorization header with an NTLM security blob
    String authHdr = sreq.getHeader(AUTHORIZATION);
    boolean reqAuth = false;

    // Check if an NTLM authorization header was received

    if (authHdr != null) {
        // Check for an NTLM authorization header

        if (authHdr.startsWith(AUTH_NTLM))
            reqAuth = true;/*from   www  .ja va2s. c  o m*/
        else if (authHdr.startsWith("Negotiate")) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Received 'Negotiate' from client, may be SPNEGO/Kerberos logon");

            // Restart the authentication

            restartLoginChallenge(context, sreq, sresp);
            return false;
        } else if (isFallbackEnabled()) {
            return performFallbackAuthentication(context, sreq, sresp);
        }
    }

    // Check if the user is already authenticated
    SessionUser user = getSessionUser(context, sreq, sresp, true);

    // If the user has been validated and we do not require re-authentication then continue to
    // the next filter
    if (user != null && reqAuth == false) {
        // Filter validate hook
        onValidate(context, sreq, sresp, new TicketCredentials(user.getTicket()));

        if (getLogger().isDebugEnabled())
            getLogger().debug("Authentication not required (user), chaining ...");

        // Chain to the next filter
        return true;
    }

    // Check if the login page is being accessed, do not intercept the login page
    if (hasLoginPage() && sreq.getRequestURI().endsWith(getLoginPage()) == true) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Login page requested, chaining ...");

        // Chain to the next filter
        return true;
    }

    // Check if the browser is Opera, if so then display the login page as Opera does not
    // support NTLM and displays an error page if a request to use NTLM is sent to it
    String userAgent = sreq.getHeader("user-agent");
    if (userAgent != null && userAgent.indexOf("Opera ") != -1) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Opera detected, redirecting to login page");

        // If there is no login page configured (WebDAV) then just keep requesting the user details from the client

        if (hasLoginPage())
            redirectToLoginPage(sreq, sresp);
        else
            restartLoginChallenge(context, sreq, sresp);
        return false;
    }

    // Check the authorization header
    if (authHdr == null) {
        // Check for a ticket based logon, if enabled

        if (allowsTicketLogons()) {
            // Check if the request includes an authentication ticket

            if (checkForTicketParameter(context, sreq, sresp)) {

                // Authentication was bypassed using a ticket parameter
                return true;
            }
        }

        // DEBUG

        if (getLogger().isDebugEnabled())
            getLogger().debug("New NTLM auth request from " + sreq.getRemoteHost() + " (" + sreq.getRemoteAddr()
                    + ":" + sreq.getRemotePort() + ") SID:" + sreq.getSession().getId());

        // Send back a request for NTLM authentication
        restartLoginChallenge(context, sreq, sresp);
        return false;
    } else {
        HttpSession session = sreq.getSession();
        Object sessionMutex = WebUtils.getSessionMutex(session);
        // Decode the received NTLM blob and validate
        final byte[] ntlmByts = Base64.decodeBase64(authHdr.substring(5).getBytes());
        int ntlmTyp = NTLMMessage.isNTLMType(ntlmByts);
        if (ntlmTyp == NTLM.Type1) {
            // Process the type 1 NTLM message
            Type1NTLMMessage type1Msg = new Type1NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType1(type1Msg, sreq, sresp);
            }
            return false;
        } else if (ntlmTyp == NTLM.Type3) {
            // Process the type 3 NTLM message
            Type3NTLMMessage type3Msg = new Type3NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                return processType3(type3Msg, context, sreq, sresp);
            }
        } else {
            if (getLogger().isDebugEnabled())
                getLogger().debug("NTLM blob not handled, redirecting to login page.");

            if (hasLoginPage())
                redirectToLoginPage(sreq, sresp);
            else
                restartLoginChallenge(context, sreq, sresp);
            return false;
        }
    }
}

From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java

/**
 * Run the filter//  w  ww.j  a  v  a  2  s  . c o  m
 * 
 * @param sreq ServletRequest
 * @param sresp ServletResponse
 * @param chain FilterChain
 * 
 * @exception IOException
 * @exception ServletException
 */
public void doFilter(ServletRequest sreq, ServletResponse sresp, FilterChain chain)
        throws IOException, ServletException {
    NDC.remove();
    NDC.push(Thread.currentThread().getName());
    final boolean debug = logger.isDebugEnabled();

    // Wrap externally authenticated requests that provide the user in an HTTP header
    // with one that returns the correct name from getRemoteUser(). For use in our own
    // calls to this method and any chained filters.
    sreq = wrapHeaderAuthenticatedRequest(sreq);

    // Bypass the filter if we don't have an endpoint with external auth enabled
    if (this.endpoint == null) {
        if (debug)
            logger.debug("There is no endpoint with external auth enabled.");
        chain.doFilter(sreq, sresp);
        return;
    }

    // Get the HTTP request/response/session
    HttpServletRequest req = (HttpServletRequest) sreq;
    HttpServletResponse res = (HttpServletResponse) sresp;
    HttpSession session = req.getSession();

    if (req.getServletPath() != null && req.getServletPath().startsWith(UNAUTHENTICATED_ACCESS_PROXY)) {
        if (debug)
            logger.debug("SSO is by-passed for unauthenticated access endpoint.");
        chain.doFilter(sreq, sresp);
        return;
    }

    // external invitation link should not trigger any SSO
    if (PAGE_SERVLET_PATH.equals(req.getServletPath()) && IGNORE_LINK.equals(req.getPathInfo())) {
        if (debug)
            logger.debug("SSO is by-passed for external invitation link.");
        chain.doFilter(sreq, sresp);
        return;
    }

    if (debug)
        logger.debug("Processing request " + req.getRequestURI() + " SID:" + session.getId());

    // Login page or login submission
    String pathInfo;
    if (PAGE_SERVLET_PATH.equals(req.getServletPath())
            && (LOGIN_PATH_INFORMATION.equals(pathInfo = req.getPathInfo())
                    || pathInfo == null && LOGIN_PARAMETER.equals(req.getParameter("pt")))) {
        if (debug)
            logger.debug("Login page requested, chaining ...");

        // Chain to the next filter
        chain.doFilter(sreq, sresp);
        return;
    }

    // initialize a new request context
    RequestContext context = null;
    try {
        // perform a "silent" init - i.e. no user creation or remote connections
        context = RequestContextUtil.initRequestContext(getApplicationContext(), req, true);
    } catch (Exception ex) {
        logger.error("Error calling initRequestContext", ex);
        throw new ServletException(ex);
    }

    // get the page from the model if any - it may not require authentication
    Page page = context.getPage();
    if (page != null && page.getAuthentication() == RequiredAuthentication.none) {
        if (logger.isDebugEnabled())
            logger.debug("Unauthenticated page requested - skipping auth filter...");
        chain.doFilter(sreq, sresp);
        return;
    }

    // If userHeader (X-Alfresco-Remote-User or similar) external auth - does not require a challenge/response
    if (this.userHeader != null) {
        String userId = AuthenticationUtil.getUserId(req);
        if (userId != null && req.getRemoteUser() != null) {
            if (logger.isDebugEnabled())
                logger.debug("userHeader external auth - skipping auth filter...");
            setExternalAuthSession(session);
            onSuccess(req, res, session, req.getRemoteUser());
            chain.doFilter(sreq, sresp);
            return;
        } else {
            // initial external user login requires a ping check to authenticate remote Session
            challengeOrPassThrough(chain, req, res, session);
            return;
        }
    }

    // Check if there is an authorization header with a challenge response
    String authHdr = req.getHeader(HEADER_AUTHORIZATION);

    // We are not passing on a challenge response and we have sufficient client session information
    if (authHdr == null && AuthenticationUtil.isAuthenticated(req)) {
        if (debug)
            logger.debug("Touching the repo to ensure we still have an authenticated session.");
        challengeOrPassThrough(chain, req, res, session);
        return;
    }

    // Check the authorization header
    if (authHdr == null) {
        if (debug)
            logger.debug("New auth request from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":"
                    + req.getRemotePort() + ")");
        challengeOrPassThrough(chain, req, res, session);
        return;
    }
    // SPNEGO / Kerberos authentication
    else if (authHdr.startsWith(AUTH_SPNEGO) && this.krbRealm != null) {
        if (debug)
            logger.debug("Processing SPNEGO / Kerberos authentication.");
        // Decode the received SPNEGO blob and validate

        final byte[] spnegoByts = Base64.decode(authHdr.substring(10).getBytes());

        // Check if the client sent an NTLMSSP blob

        if (isNTLMSSPBlob(spnegoByts, 0)) {
            if (logger.isDebugEnabled())
                logger.debug("Client sent an NTLMSSP security blob");

            // Restart the authentication

            restartAuthProcess(session, req, res, AUTH_SPNEGO);
            return;
        }

        //  Check the received SPNEGO token type

        int tokType = -1;

        try {
            tokType = SPNEGO.checkTokenType(spnegoByts, 0, spnegoByts.length);
        } catch (IOException ex) {
        }

        // Check for a NegTokenInit blob

        if (tokType == SPNEGO.NegTokenInit) {
            if (debug)
                logger.debug("Parsing the SPNEGO security blob to get the Kerberos ticket.");

            NegTokenInit negToken = new NegTokenInit();

            try {
                // Decode the security blob

                negToken.decode(spnegoByts, 0, spnegoByts.length);

                //  Determine the authentication mechanism the client is using and logon

                String oidStr = null;
                if (negToken.numberOfOids() > 0)
                    oidStr = negToken.getOidAt(0).toString();

                if (oidStr != null && (oidStr.equals(OID.ID_MSKERBEROS5) || oidStr.equals(OID.ID_KERBEROS5))) {
                    if (debug)
                        logger.debug("Kerberos logon.");
                    //  Kerberos logon

                    if (doKerberosLogon(negToken, req, res, session) != null) {
                        // Allow the user to access the requested page

                        chain.doFilter(req, res);
                        if (logger.isDebugEnabled())
                            logger.debug("Request processing ended");
                    } else {
                        // Send back a request for SPNEGO authentication

                        restartAuthProcess(session, req, res, AUTH_SPNEGO);
                    }
                } else {
                    //  Unsupported mechanism, e.g. NegoEx

                    if (logger.isDebugEnabled())
                        logger.debug("Unsupported SPNEGO mechanism " + oidStr);

                    // Try again!

                    restartAuthProcess(session, req, res, AUTH_SPNEGO);
                }
            } catch (IOException ex) {
                // Log the error

                if (logger.isDebugEnabled())
                    logger.debug(ex);
            }
        } else {
            //  Unknown SPNEGO token type

            if (logger.isDebugEnabled())
                logger.debug("Unknown SPNEGO token type");

            // Send back a request for SPNEGO authentication

            restartAuthProcess(session, req, res, AUTH_SPNEGO);
        }
    }
    // NTLM authentication
    else if (authHdr.startsWith(AUTH_NTLM)) {
        if (debug)
            logger.debug("Processing NTLM authentication.");
        // Decode the received NTLM blob and validate
        final byte[] authHdrByts = authHdr.substring(5).getBytes();
        final byte[] ntlmByts = Base64.decode(authHdrByts);
        int ntlmTyp = NTLMMessage.isNTLMType(ntlmByts);
        Object sessionMutex = WebUtils.getSessionMutex(session);

        if (ntlmTyp == NTLM.Type1) {
            if (debug)
                logger.debug("Process the type 1 NTLM message.");
            Type1NTLMMessage type1Msg = new Type1NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType1(type1Msg, req, res, session);
            }
        } else if (ntlmTyp == NTLM.Type3) {
            if (debug)
                logger.debug("Process the type 3 NTLM message.");
            Type3NTLMMessage type3Msg = new Type3NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType3(type3Msg, req, res, session, chain);
            }
        } else {
            if (debug)
                logger.debug("NTLM not handled, redirecting to login page");

            redirectToLoginPage(req, res);
        }
    }
    // Possibly basic auth - allow through
    else {
        if (debug)
            logger.debug("Processing Basic Authentication.");
        // ACE-3257 fix, it looks like basic auth header was sent.
        // However lets check for presence of remote_user CGI variable in AJP.
        // If remote user is not null then it most likely that apache proxy with mod_auth_basic module is used
        if (AuthenticationUtil.isAuthenticated(req) || req.getRemoteUser() != null) {
            if (debug)
                logger.debug("Ensuring the session is still valid.");
            challengeOrPassThrough(chain, req, res, session);
        } else {
            if (debug)
                logger.debug("Establish a new session or bring up the login page.");
            chain.doFilter(req, res);
        }
    }
}