Example usage for javax.servlet.http HttpSession getAttributeNames

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

Introduction

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

Prototype

public Enumeration<String> getAttributeNames();

Source Link

Document

Returns an Enumeration of String objects containing the names of all the objects bound to this session.

Usage

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

/**
 * //from   w w w .  j ava  2s  . co m
 * Calculate an <b>approximation</b> of the memory consumed by the objects
 * stored under each attribute of a user's {@link HttpSession}. The estimate
 * will often be greater than the actual value because of "double counting"
 * objects that appear multiple times in the attribute value's object graph.
 * 
 * @param session
 *            An HttpSession object from any web application.
 * @return An <b>approximation</b> of the memory consumed for each attribute
 *         <b>name</b> in the session.
 */
public static Map<String, Integer> getSessionAttributeNameToApproxSizeInBytesMap(HttpSession session) {

    // Use an IdentityHashMap because we don't want to miss distinct objects
    // that are equivalent according to equals(..) method.
    Map<String, Integer> sessionAttributeNameToApproxSizeInBytesMap = new IdentityHashMap<String, Integer>();

    Enumeration<?> enumeration = session.getAttributeNames();
    while (enumeration.hasMoreElements()) {
        String attributeName = (String) enumeration.nextElement();
        session.getAttribute(attributeName);

        try {
            sessionAttributeNameToApproxSizeInBytesMap.put(attributeName,
                    new Integer(approximateObjectSize(attributeName)));
        } catch (IOException ioe) {
            logger.error("Failed to approximate size of session attribute name: "
                    + attributeName.getClass().getName(), ioe);
            sessionAttributeNameToApproxSizeInBytesMap.put(attributeName, new Integer(0));
        }

    }

    return sessionAttributeNameToApproxSizeInBytesMap;

}

From source file:org.craftercms.commons.http.HttpUtils.java

/**
 * Creates a map from the session attributes in the specified request.
 *
 * @param request the request//w w w .  jav  a  2  s. c o  m
 */
public static Map<String, Object> createSessionMap(HttpServletRequest request) {
    Map<String, Object> sessionMap = new HashMap<>();
    HttpSession session = request.getSession(false);

    if (session != null) {
        for (Enumeration attributeNameEnum = session.getAttributeNames(); attributeNameEnum
                .hasMoreElements();) {
            String attributeName = (String) attributeNameEnum.nextElement();
            sessionMap.put(attributeName, session.getAttribute(attributeName));
        }
    }

    return sessionMap;
}

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;//from   w  w w .  j  av a2 s .c o  m
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:com.googlecode.jtiger.modules.ecside.util.ExtremeUtils.java

public static int sessionSize(HttpSession session) {
    int total = 0;

    try {/*from   ww  w .  j  a v a 2s.com*/
        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
        java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos);
        Enumeration enumeration = session.getAttributeNames();

        while (enumeration.hasMoreElements()) {
            String name = (String) enumeration.nextElement();
            Object obj = session.getAttribute(name);
            oos.writeObject(obj);

            int size = baos.size();
            total += size;
            logger.debug("The session name: " + name + " and the size is: " + size);
        }

        logger.debug("Total session size is: " + total);
    } catch (Exception e) {
        logger.error("Could not get the session size - " + ExceptionUtils.formatStackTrace(e));
    }

    return total;
}

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));
        //}/*from w  w  w  .  j av  a 2s . co m*/
    }
    // 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:de.zib.gndms.kit.monitor.GroovyMoniServlet.java

/**
* Tries to destroy the current session and reclaim associated resources
*
* @param requestWrapper//from   www .  j  av  a 2 s  .  c  o  m
* @return true, if the session was destroyed. false, if there was none.
*/
@SuppressWarnings({ "unchecked" })
private static boolean didDestroySessionOnRequest(@NotNull HttpServletRequest requestWrapper) {
    if ("destroy".equalsIgnoreCase(requestWrapper.getParameter("m"))) {
        final HttpSession session = getSessionOrFail(requestWrapper);
        if (session != null) {
            synchronized (session) {
                final Enumeration<String> attrs = (Enumeration<String>) session.getAttributeNames();
                while (attrs.hasMoreElements())
                    session.removeAttribute(attrs.nextElement());
                session.invalidate();
            }
        }
        return true;
    } else
        return false;
}

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));
            }/* www.jav a 2 s  . c  o  m*/
        } else {
            LOGGER.debug("--- no keys present in session ---");
        }
    }
}

From source file:org.opencms.jsp.CmsJspTagUserTracking.java

/**
 * Removes all session attributes starting with the given prefixes.<p>
 * /*from w  w  w  .  jav  a 2s.c  om*/
 * @param prefixes the prefixes of the session attributes to remove
 * @param req the current request
 */
protected static void removeSessionAttributes(String[] prefixes, HttpServletRequest req) {

    HttpSession session = req.getSession(true);
    Enumeration<String> en = session.getAttributeNames();
    while (en.hasMoreElements()) {
        String attrKey = en.nextElement();
        for (int i = 0; i < prefixes.length; i++) {
            if (attrKey.startsWith(prefixes[i])) {
                session.removeAttribute(attrKey);
            }
        }
    }
}

From source file:org.jbpcc.admin.jsf.JsfUtil.java

@SuppressWarnings("unchecked")
public static void cleanHttpSession() {
    HttpSession session = (HttpSession) getCurrentFacesContext().getExternalContext().getSession(true);
    SessionObjectKey sessionObjKeyArray[] = SessionObjectKey.values();
    for (SessionObjectKey objectKey : sessionObjKeyArray) {
        session.removeAttribute(objectKey.getKey());
    }/*from  www.  j  ava 2s . c  o m*/

    java.util.Enumeration attrs = session.getAttributeNames();
    while (attrs.hasMoreElements()) {
        String attr = (String) attrs.nextElement();
        if (attr.endsWith("Bean")) {
            session.removeAttribute(attr);
        }
    }
}

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

public static ApplicationSession getApplicationSession(Session session, boolean calcSize,
        boolean addAttributes) {
    ApplicationSession sbean = null;//from 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;
}