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:org.apereo.portal.events.PortalEventFactoryImpl.java

/**
 * Get a session scoped mutex specific to this class
 *///from  w  w  w .j a va2s .  com
protected final Object getEventSessionMutex(HttpSession session) {
    synchronized (WebUtils.getSessionMutex(session)) {
        SerializableObject mutex = (SerializableObject) session.getAttribute(EVENT_SESSION_MUTEX);
        if (mutex == null) {
            mutex = new SerializableObject();
            session.setAttribute(EVENT_SESSION_MUTEX, mutex);
        }

        return mutex;
    }
}

From source file:org.apereo.portal.layout.StylesheetUserPreferencesServiceImpl.java

@Transactional
@Override/*from   w  w w. ja  v  a 2 s  .com*/
public String setLayoutAttribute(HttpServletRequest request, PreferencesScope prefScope, String nodeId,
        String name, String value) {
    final StylesheetPreferencesKey stylesheetPreferencesKey = this.getStylesheetPreferencesKey(request,
            prefScope);
    final IStylesheetDescriptor stylesheetDescriptor = stylesheetPreferencesKey.stylesheetDescriptor;
    final ILayoutAttributeDescriptor layoutAttributeDescriptor = stylesheetDescriptor
            .getLayoutAttributeDescriptor(name);
    if (layoutAttributeDescriptor == null) {
        logger.warn(
                "Attempted to set layout attribute {}={} on node with ID=\"{}\" but no such stylesheet parameter is defined in stylesheet descriptor {}. It will be ignored.",
                new Object[] { name, value, nodeId, stylesheetDescriptor.getName() });
        return null;
    }

    if (this.compareValues(value, layoutAttributeDescriptor.getDefaultValue())) {
        //Value matches the default value, remove the attribute
        return this.removeLayoutAttribute(request, prefScope, nodeId, name);
    }

    final IStylesheetUserPreferences distributedStylesheetUserPreferences = this
            .getDistributedStylesheetUserPreferences(request, prefScope);
    if (distributedStylesheetUserPreferences != null) {
        final String defaultValue = distributedStylesheetUserPreferences.getLayoutAttribute(nodeId, name);
        if (this.compareValues(value, defaultValue)) {
            //Value matches the DLM preferences value, remove the value
            return this.removeLayoutAttribute(request, prefScope, nodeId, name);
        }
    }

    final Scope scope = this.getWriteScope(request, prefScope, stylesheetPreferencesKey,
            layoutAttributeDescriptor);
    switch (scope) {
    case PERSISTENT: {
        IStylesheetUserPreferences stylesheetUserPreferences = this.getStylesheetUserPreferences(request,
                stylesheetPreferencesKey);
        if (stylesheetUserPreferences == null) {
            stylesheetUserPreferences = this.stylesheetUserPreferencesDao.createStylesheetUserPreferences(
                    stylesheetDescriptor, stylesheetPreferencesKey.person,
                    stylesheetPreferencesKey.userProfile);
            this.clearStylesheetUserPreferencesCache(request, stylesheetPreferencesKey);
        }

        final String oldValue = stylesheetUserPreferences.setLayoutAttribute(nodeId, name, value);
        this.stylesheetUserPreferencesDao.storeStylesheetUserPreferences(stylesheetUserPreferences);
        return oldValue;
    }
    default: {

        //Determine the mutex to use for accessing the nodeAttributes map
        final Object mutex;
        switch (scope) {
        case REQUEST: {
            mutex = PortalWebUtils.getRequestAttributeMutex(request);
            break;
        }
        case SESSION: {
            final HttpSession session = request.getSession();
            mutex = WebUtils.getSessionMutex(session);
            break;
        }
        default: {
            mutex = new Object();
            break;
        }
        }

        //Get/Create the nodeAttributes map
        Map<String, String> nodeAttributes;
        synchronized (mutex) {
            nodeAttributes = this.getDataValue(request, stylesheetPreferencesKey, scope, LAYOUT_ATTRIBUTES_KEY,
                    nodeId);
            if (nodeAttributes == null) {
                nodeAttributes = new ConcurrentHashMap<String, String>();
                this.putDataValue(request, stylesheetPreferencesKey, scope, LAYOUT_ATTRIBUTES_KEY, nodeId,
                        nodeAttributes);
            }
        }

        return nodeAttributes.put(name, value);
    }
    }
}

From source file:org.apereo.portal.portlet.registry.PortletEntityRegistryImpl.java

protected PortletEntityCache<PortletEntityData> getPortletEntityDataMap(HttpServletRequest request) {
    request = portalRequestUtils.getOriginalPortalRequest(request);
    final HttpSession session = request.getSession();
    final Object mutex = WebUtils.getSessionMutex(session);
    synchronized (mutex) {
        @SuppressWarnings("unchecked")
        PortletEntityCache<PortletEntityData> cache = (PortletEntityCache<PortletEntityData>) session
                .getAttribute(PORTLET_ENTITY_DATA_ATTRIBUTE);
        if (cache == null) {
            cache = new PortletEntityCache<PortletEntityData>();
            session.setAttribute(PORTLET_ENTITY_DATA_ATTRIBUTE, cache);
        }/*from  www  .  j av  a 2  s . c o  m*/
        return cache;
    }
}

From source file:org.apereo.portal.portlet.registry.PortletWindowRegistryImpl.java

@SuppressWarnings("unchecked")
protected PortletWindowCache<PortletWindowData> getPortletWindowDataMap(HttpServletRequest request,
        boolean create) {
    request = portalRequestUtils.getOriginalPortalRequest(request);
    final HttpSession session = request.getSession(create);
    if (!create && session == null) {
        return null;
    }// w w w.jav  a  2s  .co m

    PortletWindowCache<PortletWindowData> windowCache;

    final Object mutex = WebUtils.getSessionMutex(session);
    synchronized (mutex) {
        windowCache = (PortletWindowCache<PortletWindowData>) session
                .getAttribute(PORTLET_WINDOW_DATA_ATTRIBUTE);
        if (windowCache == null) {
            windowCache = new PortletWindowCache<PortletWindowData>();
            session.setAttribute(PORTLET_WINDOW_DATA_ATTRIBUTE, windowCache);
        }
    }

    return windowCache;
}

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

/**
 * Null safe means for retrieving the {@link Map} from the specified session
 * keyed by {@link #SESSION_ATTRIBUTE__PORTLET_FAILURE_CAUSE_MAP}.
 * //www .j a  v  a  2  s  . co m
 * @param request HttpServletRequest
 * @return a never null {@link Map} in the session for storing portlet failure causes.
 */
@SuppressWarnings("unchecked")
protected Map<IPortletWindowId, Exception> getPortletErrorMap(HttpServletRequest request) {
    final HttpSession session = request.getSession();
    synchronized (WebUtils.getSessionMutex(session)) {
        Map<IPortletWindowId, Exception> portletFailureMap = (Map<IPortletWindowId, Exception>) session
                .getAttribute(SESSION_ATTRIBUTE__PORTLET_FAILURE_CAUSE_MAP);
        if (portletFailureMap == null) {
            portletFailureMap = new ConcurrentHashMap<IPortletWindowId, Exception>();
            session.setAttribute(SESSION_ATTRIBUTE__PORTLET_FAILURE_CAUSE_MAP, portletFailureMap);
        }
        return portletFailureMap;
    }

}

From source file:org.apereo.portal.portlet.session.PortletSessionExpirationManager.java

@SuppressWarnings("unchecked")
public void onEnd(PortletInvocationEvent event) {
    final PortletRequest portletRequest = event.getPortletRequest();
    final PortletSession portletSession = portletRequest.getPortletSession(false);
    if (portletSession == null) {
        return;//from  w ww  .  java 2 s .c o  m
    }

    final HttpServletRequest portalRequest = this.portalRequestUtils.getPortletHttpRequest(portletRequest);
    final HttpSession portalSession = portalRequest.getSession();

    if (portalSession != null) {
        NonSerializableMapHolder<String, PortletSession> portletSessions;
        synchronized (WebUtils.getSessionMutex(portalSession)) {
            portletSessions = (NonSerializableMapHolder<String, PortletSession>) portalSession
                    .getAttribute(PORTLET_SESSIONS_MAP);
            if (portletSessions == null || !portletSessions.isValid()) {
                portletSessions = new NonSerializableMapHolder(new ConcurrentHashMap<String, PortletSession>());
                portalSession.setAttribute(PORTLET_SESSIONS_MAP, portletSessions);
            }
        }

        final String contextPath = portletRequest.getContextPath();
        portletSessions.put(contextPath, portletSession);
    }
}

From source file:org.apereo.portal.spring.web.context.support.PortalSessionScope.java

public Object get(String name, ObjectFactory<?> objectFactory) {
    final HttpSession session = this.getPortalSesion(true);

    final Object sessionMutex = WebUtils.getSessionMutex(session);
    synchronized (sessionMutex) {
        Object scopedObject = session.getAttribute(name);
        if (scopedObject == null) {
            scopedObject = objectFactory.getObject();
            session.setAttribute(name, scopedObject);
        }/*from  w  ww. j a v a 2 s  .com*/

        return scopedObject;
    }
}

From source file:org.apereo.portal.spring.web.context.support.PortalSessionScope.java

public Object remove(String name) {
    final HttpSession session = this.getPortalSesion(false);
    if (session == null) {
        return null;
    }/*  www .  j a v  a  2  s .co  m*/

    final Object sessionMutex = WebUtils.getSessionMutex(session);
    synchronized (sessionMutex) {
        final Object attribute = session.getAttribute(name);
        if (attribute != null) {
            session.removeAttribute(name);
        }

        return attribute;
    }
}

From source file:org.jtalks.jcommune.web.controller.PostController.java

/**
 * Performs vote with session locking to prevent handling of concurrent requests from same user
 *
 * @param postId id of a post to vote/*w  w  w.java2 s  .co  m*/
 * @param vote {@link PostVote} object
 * @param request HttpServletRequest
 *
 * @throws NotFoundException if post with specified id not found
 */
private void voteWithSessionLocking(Long postId, PostVote vote, HttpServletRequest request)
        throws NotFoundException {
    /**
     * We should not create session here to prevent possibility of creating multiplier sessions for same user in
     * concurrent requests
     */
    HttpSession session = request.getSession(false);
    if (session != null) {
        Object mutex = WebUtils.getSessionMutex(session);
        /**
         *  Next operations performed in synchronized block to prevent handling of concurrent requests from same
         *  user. We use session mutex as the lock object. In many cases, the HttpSession reference itself is a safe
         *  mutex as well, since it will always be the same object reference for the same active logical session.
         *  However, this is not guaranteed across different servlet containers; the only 100% safe way is a session
         *  mutex.
        */
        synchronized (mutex) {
            Post post = postService.get(postId);
            postService.vote(post, vote);
        }
    } else {
        /**
         * If <code>HttpSession</code> is <code>null</code> we have no mutex object, so we perform operations
         * without synchronization
         */
        Post post = postService.get(postId);
        postService.vote(post, vote);
    }
}

From source file:org.springframework.security.web.authentication.session.AbstractSessionFixationProtectionStrategy.java

/**
 * Called when a user is newly authenticated.
 * <p>/*w w w.j a v  a 2s.  c  om*/
 * If a session already exists, and matches the session Id from the client, a new
 * session will be created, and the session attributes copied to it (if
 * {@code migrateSessionAttributes} is set). If the client's requested session Id is
 * invalid, nothing will be done, since there is no need to change the session Id if
 * it doesn't match the current session.
 * <p>
 * If there is no session, no action is taken unless the {@code alwaysCreateSession}
 * property is set, in which case a session will be created if one doesn't already
 * exist.
 */
public void onAuthentication(Authentication authentication, HttpServletRequest request,
        HttpServletResponse response) {
    boolean hadSessionAlready = request.getSession(false) != null;

    if (!hadSessionAlready && !alwaysCreateSession) {
        // Session fixation isn't a problem if there's no session

        return;
    }

    // Create new session if necessary
    HttpSession session = request.getSession();

    if (hadSessionAlready && request.isRequestedSessionIdValid()) {

        String originalSessionId;
        String newSessionId;
        Object mutex = WebUtils.getSessionMutex(session);
        synchronized (mutex) {
            // We need to migrate to a new session
            originalSessionId = session.getId();

            session = applySessionFixation(request);
            newSessionId = session.getId();
        }

        if (originalSessionId.equals(newSessionId)) {
            logger.warn(
                    "Your servlet container did not change the session ID when a new session was created. You will"
                            + " not be adequately protected against session-fixation attacks");
        }

        onSessionChange(originalSessionId, session, authentication);
    }
}