Example usage for javax.servlet.http HttpSession getAttribute

List of usage examples for javax.servlet.http HttpSession getAttribute

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the object bound with the specified name in this session, or null if no object is bound under the name.

Usage

From source file:grails.plugin.springsecurity.SpringSecurityUtils.java

public static SecurityContext getSecurityContext(final HttpSession session) {
    Object securityContext = session
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    if (securityContext instanceof SecurityContext) {
        return (SecurityContext) securityContext;
    }/* www  .ja v a  2 s  .  c  o m*/
    return null;
}

From source file:grails.plugin.springsecurity.SpringSecurityUtils.java

/**
 * Get the last attempted username.//ww w  . j a  va  2s .c  o  m
 * @param session the session
 * @return the username
 */
public static String getLastUsername(final HttpSession session) {
    String username = (String) session.getAttribute(SPRING_SECURITY_LAST_USERNAME_KEY);
    if (username != null) {
        username = StringEscapeUtils.unescapeHtml(username);
    }
    return username;
}

From source file:psiprobe.tools.ApplicationUtils.java

/**
 * Gets the application session.//from  w ww .j  a v  a  2 s .co m
 *
 * @param session the session
 * @param calcSize the calc size
 * @param addAttributes the add attributes
 * @return the application session
 */
public static ApplicationSession getApplicationSession(Session session, boolean calcSize,
        boolean addAttributes) {

    ApplicationSession sbean = null;
    if (session != null && session.isValid()) {
        sbean = new ApplicationSession();

        sbean.setId(session.getId());
        sbean.setCreationTime(new Date(session.getCreationTime()));
        sbean.setLastAccessTime(new Date(session.getLastAccessedTime()));
        sbean.setMaxIdleTime(session.getMaxInactiveInterval() * 1000);
        sbean.setManagerType(session.getManager().getClass().getName());
        // sbean.setInfo(session.getInfo());
        // TODO:fixmee

        boolean sessionSerializable = true;
        int attributeCount = 0;
        long size = 0;

        HttpSession httpSession = session.getSession();
        Set<Object> processedObjects = new HashSet<>(1000);

        // Exclude references back to the session itself
        processedObjects.add(httpSession);
        try {
            for (String name : Collections.list(httpSession.getAttributeNames())) {
                Object obj = httpSession.getAttribute(name);
                sessionSerializable = sessionSerializable && obj instanceof Serializable;

                long objSize = 0;
                if (calcSize) {
                    try {
                        objSize += Instruments.sizeOf(name, processedObjects);
                        objSize += Instruments.sizeOf(obj, processedObjects);
                    } catch (Exception ex) {
                        logger.error("Cannot estimate size of attribute '{}'", name, ex);
                    }
                }

                if (addAttributes) {
                    Attribute saBean = new Attribute();
                    saBean.setName(name);
                    saBean.setType(ClassUtils.getQualifiedName(obj.getClass()));
                    saBean.setValue(obj);
                    saBean.setSize(objSize);
                    saBean.setSerializable(obj instanceof Serializable);
                    sbean.addAttribute(saBean);
                }
                attributeCount++;
                size += objSize;
            }
            String lastAccessedIp = (String) httpSession.getAttribute(ApplicationSession.LAST_ACCESSED_BY_IP);
            if (lastAccessedIp != null) {
                sbean.setLastAccessedIp(lastAccessedIp);
            }
            try {
                sbean.setLastAccessedIpLocale(
                        InetAddressLocator.getLocale(InetAddress.getByName(lastAccessedIp).getAddress()));
            } catch (Exception e) {
                logger.error("Cannot determine Locale of {}", lastAccessedIp);
                logger.trace("", e);
            }

        } catch (IllegalStateException e) {
            logger.info("Session appears to be invalidated, ignore");
            logger.trace("", e);
        }

        sbean.setObjectCount(attributeCount);
        sbean.setSize(size);
        sbean.setSerializable(sessionSerializable);
    }

    return sbean;
}

From source file:net.big_oh.common.web.WebUtil.java

/**
 * Calculate an <b>approximation</b> of the memory consumed by all objects
 * stored in the {@link HttpSession}. The estimate will often be greater
 * than the actual value because of "double counting" objects that appear in
 * the object graphs of multiple session attributes.
 * //from ww w. j av a 2 s .  c om
 * @param session
 *            An HttpSession object from any web application.
 * @return An <b>approximation</b> of the memory consumed by objects stored
 *         in the HttpSession object.
 */
public static long approximateSessionSizeInBytes(HttpSession session) {
    // Strategy used here is to sum memory consumed by all key/value pairs
    // stored in the session

    long sizeInBytes = 0;

    Map<String, Integer> attributeNameMap = getSessionAttributeNameToApproxSizeInBytesMap(session);
    for (String attributeName : attributeNameMap.keySet()) {
        sizeInBytes += attributeNameMap.get(attributeName);
    }

    // Map<String, Integer> attributeMap =
    // getSessionAttributeNameToApproxSizeInBytesMap(session);
    for (String attributeName : attributeNameMap.keySet()) {
        try {
            sizeInBytes += approximateObjectSize(session.getAttribute(attributeName));
        } catch (IOException ioe) {
            logger.error("Failed to approximate size of value associated with session attribute name: "
                    + attributeName.getClass().getName(), ioe);
        }
    }

    return sizeInBytes;

}

From source file:de.betterform.agent.web.WebUtil.java

public static void printSessionKeys(HttpSession session) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("--------------- http session dump ---------------");
        Enumeration keys = session.getAttributeNames();
        if (keys.hasMoreElements()) {
            while (keys.hasMoreElements()) {
                String s = (String) keys.nextElement();
                LOGGER.debug("sessionkey: " + s + ":" + session.getAttribute(s));
            }//from  ww w . j  av  a 2s  . c  o  m
        } else {
            LOGGER.debug("--- no keys present in session ---");
        }
    }
}

From source file:org.toobsframework.pres.util.ParameterUtil.java

public static Map buildParameterMap(HttpServletRequest request, boolean compCall) {
    Map params = new HashMap();
    HttpSession session = request.getSession();
    Enumeration attributes = session.getAttributeNames();
    // Session has lowest priority
    while (attributes.hasMoreElements()) {
        String thisAttribute = (String) attributes.nextElement();
        //if (session.getAttribute(thisAttribute) instanceof String) {
        params.put(thisAttribute, session.getAttribute(thisAttribute));
        //}//  w w  w  .j  ava2 s .com
    }
    // Parameters next highest
    params.putAll(request.getParameterMap());

    // Attributes rule all
    attributes = request.getAttributeNames();
    while (attributes.hasMoreElements()) {
        String thisAttribute = (String) attributes.nextElement();
        if (!excludedParameters.contains(thisAttribute)) {
            if (log.isDebugEnabled()) {
                log.debug("Putting " + thisAttribute + " As " + request.getAttribute(thisAttribute));
            }
            params.put(thisAttribute, request.getAttribute(thisAttribute));
        }
    }
    params.put("httpQueryString", request.getQueryString());
    if (compCall && request.getMethod().equals("POST")) {
        StringBuffer qs = new StringBuffer();
        Iterator iter = request.getParameterMap().entrySet().iterator();
        int i = 0;
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            String[] value = (String[]) entry.getValue();
            for (int j = 0; j < value.length; j++) {
                if (i > 0)
                    qs.append("&");
                qs.append(key).append("=").append(value[j]);
                i++;
            }
        }
        params.put("httpQueryString", qs.toString());
    }
    return params;
}

From source file:com.googlecode.psiprobe.tools.ApplicationUtils.java

public static ApplicationSession getApplicationSession(Session session, boolean calcSize,
        boolean addAttributes) {
    ApplicationSession sbean = null;/*w ww .ja v a 2  s  . c o m*/
    if (session != null && session.isValid()) {
        sbean = new ApplicationSession();

        sbean.setId(session.getId());
        sbean.setCreationTime(new Date(session.getCreationTime()));
        sbean.setLastAccessTime(new Date(session.getLastAccessedTime()));
        sbean.setMaxIdleTime(session.getMaxInactiveInterval() * 1000);
        sbean.setManagerType(session.getManager().getClass().getName());
        //sbean.setInfo(session.getInfo());
        //TODO:fixmee

        boolean sessionSerializable = true;
        int attributeCount = 0;
        long size = 0;

        HttpSession httpSession = session.getSession();
        Set processedObjects = new HashSet(1000);

        //Exclude references back to the session itself
        processedObjects.add(httpSession);
        try {
            for (Enumeration e = httpSession.getAttributeNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                Object o = httpSession.getAttribute(name);
                sessionSerializable = sessionSerializable && o instanceof Serializable;

                long oSize = 0;
                if (calcSize) {
                    try {
                        oSize += Instruments.sizeOf(name, processedObjects);
                        oSize += Instruments.sizeOf(o, processedObjects);
                    } catch (Throwable th) {
                        logger.error("Cannot estimate size of attribute \"" + name + "\"", th);
                        //
                        // make sure we always re-throw ThreadDeath
                        //
                        if (e instanceof ThreadDeath) {
                            throw (ThreadDeath) e;
                        }
                    }
                }

                if (addAttributes) {
                    Attribute saBean = new Attribute();
                    saBean.setName(name);
                    saBean.setType(ClassUtils.getQualifiedName(o.getClass()));
                    saBean.setValue(o);
                    saBean.setSize(oSize);
                    saBean.setSerializable(o instanceof Serializable);
                    sbean.addAttribute(saBean);
                }
                attributeCount++;
                size += oSize;
            }
            String lastAccessedIP = (String) httpSession.getAttribute(ApplicationSession.LAST_ACCESSED_BY_IP);
            if (lastAccessedIP != null) {
                sbean.setLastAccessedIP(lastAccessedIP);
            }
            try {
                sbean.setLastAccessedIPLocale(
                        InetAddressLocator.getLocale(InetAddress.getByName(lastAccessedIP).getAddress()));
            } catch (Throwable e) {
                logger.error("Cannot determine Locale of " + lastAccessedIP);
                //
                // make sure we always re-throw ThreadDeath
                //
                if (e instanceof ThreadDeath) {
                    throw (ThreadDeath) e;
                }
            }

        } catch (IllegalStateException e) {
            logger.info("Session appears to be invalidated, ignore");
        }

        sbean.setObjectCount(attributeCount);
        sbean.setSize(size);
        sbean.setSerializable(sessionSerializable);
    }

    return sbean;
}

From source file:com.tremolosecurity.unison.proxy.auth.twitter.TwitterAuth.java

public static void loadUnlinkedUser(HttpSession session, String noMatchOU, String uidAttr, AuthChainType act,
        Map jwtNVP) {//from   ww w  .  ja  v  a 2s  . co  m
    String uid = (String) jwtNVP.get(uidAttr);
    StringBuffer dn = new StringBuffer();
    dn.append(uidAttr).append('=').append(uid).append(",ou=").append(noMatchOU).append(",o=Tremolo");

    AuthInfo authInfo = new AuthInfo(dn.toString(),
            (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), act.getName(), act.getLevel());
    ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo);

    for (Object o : jwtNVP.keySet()) {
        String s = (String) o;
        if (jwtNVP.get(s) != null) {
            Attribute attr = new Attribute(s, jwtNVP.get(s).toString());
            authInfo.getAttribs().put(attr.getName(), attr);
        }

    }
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils.java

/**
 * Execute a closure with the current authentication. Assumes that there's an authentication in the
 * http session and that the closure is running in a separate thread from the web request, so the
 * context and authentication aren't available to the standard ThreadLocal.
 *
 * @param closure the code to run/* ww w  . ja va2  s .c  om*/
 * @return the closure's return value
 */
public static Object doWithAuth(@SuppressWarnings("rawtypes") final Closure closure) {
    boolean set = false;
    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        HttpSession httpSession = SecurityRequestHolder.getRequest().getSession(false);
        SecurityContext context = null;
        if (httpSession != null) {
            context = (SecurityContext) httpSession
                    .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            if (context != null) {
                SecurityContextHolder.setContext(context);
                set = true;
            }
        }
    }

    try {
        return closure.call();
    } finally {
        if (set) {
            SecurityContextHolder.clearContext();
        }
    }
}

From source file:com.tremolosecurity.unison.proxy.auth.openidconnect.OpenIDConnectAuthMech.java

public static void loadUnlinkedUser(HttpSession session, String noMatchOU, String uidAttr, AuthChainType act,
        Map jwtNVP, String defaultObjectClass) {
    String uid = (String) jwtNVP.get(uidAttr);
    StringBuffer dn = new StringBuffer();
    dn.append(uidAttr).append('=').append(uid).append(",ou=").append(noMatchOU).append(",")
            .append(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot());

    AuthInfo authInfo = new AuthInfo(dn.toString(),
            (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), act.getName(), act.getLevel());
    ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo);

    for (Object o : jwtNVP.keySet()) {
        String s = (String) o;
        Attribute attr = new Attribute(s, jwtNVP.get(s).toString());
        authInfo.getAttribs().put(attr.getName(), attr);

    }/*ww  w.ja  v  a2s  .  co  m*/

    authInfo.getAttribs().put("objectClass", new Attribute("objectClass", defaultObjectClass));
}