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.testdriven.psiprobe.tools.ApplicationUtils.java

public static ApplicationSession getApplicationSession(Session session, boolean calcSize,
        boolean addAttributes) {
    ApplicationSession sbean = null;/*  w w w .j a  v a2  s.  co 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());

        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:psiprobe.tools.ApplicationUtils.java

/**
 * Gets the application session.//  w w w.  j  a v  a2 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:com.liferay.portal.action.LoginAction.java

public static HashMap getUserCarryAttributes(HttpSession ses) {

    HashMap result = new HashMap();

    Enumeration enu = ses.getAttributeNames();

    while (enu.hasMoreElements()) {
        String name = (String) enu.nextElement();

        if (name.startsWith("USER_CARRY")) {

            result.put(name, ses.getAttribute(name));

        }/*w w  w . j  a  v a 2 s .  com*/
    }

    return result;
}

From source file:org.hx.rainbow.common.web.session.RainbowSession.java

public static void web2Service(HttpServletRequest request) {
    if (request == null) {
        return;//from   w w  w  .jav a2s .c o m
    }
    setProperty(ThreadConstants.CONSTMER_IPADDRESS, request.getRemoteAddr());
    setProperty(ThreadConstants.CONSTMER_HOST, request.getRemoteHost());
    setProperty(ThreadConstants.CONSTMER_PORT, request.getRemotePort());
    setProperty(ThreadConstants.SERVICE_IPADDRESS, request.getLocalAddr());
    setProperty(ThreadConstants.SERVICE_HOST, request.getLocalName());
    setProperty(ThreadConstants.RAINBOW_REQUEST, request);

    HttpSession session = request.getSession();

    RainbowUser rainbowUser = (RainbowUser) session.getAttribute(ThreadConstants.RAINBOW_USER);
    if (rainbowUser != null) {
        setProperty(ThreadConstants.RAINBOW_SESSION, rainbowUser);
        setProperty(ThreadConstants.RAINBOW_LOGINID, rainbowUser.getUsername());
        setProperty(ThreadConstants.RAINBOW_USERNAME, rainbowUser.getSessionData().get("name"));

        String sessionKeys = (String) PropertiesUtil.getInstance().read(THREAD_LOACL_FILE)
                .get(ThreadConstants.SESSION_KEYS);
        if (sessionKeys != null) {
            if (sessionKeys.equals("*")) {
                Enumeration<String> attrNames = session.getAttributeNames();
                while (attrNames.hasMoreElements()) {
                    String attrName = (String) attrNames.nextElement();
                    if (SESSION_KEYS.contains(attrName)) {
                        continue;
                    }
                    if (attrName != null) {
                        Object session_attr = session.getAttribute(attrName);
                        if (session_attr != null) {
                            rainbowUser.getSessionData().put(attrName, session_attr);
                        }
                    }
                }
            } else {
                String[] s_sessionkey = StringUtils.split(sessionKeys, ",");
                for (int i = 0; i < s_sessionkey.length; i++) {
                    if (s_sessionkey[i] != null) {
                        Object session_attr = session.getAttribute(s_sessionkey[i]);
                        if (session_attr != null) {
                            rainbowUser.getSessionData().put(s_sessionkey[i], session_attr);
                        }
                    }
                }
            }
        }
    }
    //   
    //
    //
    //
    //      Map<String, Object> inCookie = new ConcurrentHashMap<String, Object>();
    //      String cookieKeys = (String)PropertiesUtil.get(ThreadConstants.resource_cookieKeys);
    //
    //      if (cookieKeys != null) {
    //         Cookie[] cookies = request.getCookies();
    //         if (cookies != null) {
    //            if (cookieKeys.equals("*")) {
    //               for (int i = 0; i < cookies.length; i++) {
    //                  Cookie cookie = cookies[i];
    //                  String cookieName = cookie.getName();
    //                  String cookieValue = cookie.getValue();
    //                  if(cookieName != null && cookieValue != null){
    //                     inCookie.put(cookieName, cookieValue);
    //                  }
    //               }
    //            } else {
    //               cookieKeys = cookieKeys + ",";
    //               for (int i = 0; i < cookies.length; i++) {
    //                  Cookie cookie = cookies[i];
    //                  String cookieName = cookie.getName();
    //                  if (cookieKeys.indexOf(cookieName + ",") > -1) {
    //                     String cookieValue = cookie.getValue();
    //                     if(cookieName != null && cookieValue != null){
    //                        inCookie.put(cookieName, cookieValue);
    //                     }
    //                  }
    //               }
    //            }
    //         }
    //         setProperty(ThreadConstants.IN_COOKIE, inCookie);
    //      }

}

From source file:org.jboss.dashboard.users.SessionClearerUserStatusListener.java

public void statusChanged(UserStatus us) {
    if (us.isAnonymous()) { // just logout
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpSession session = ctx.getRequest().getSessionObject();
        Enumeration en = session.getAttributeNames();
        Set attributesToDelete = new HashSet();
        while (en.hasMoreElements()) {
            String attrName = (String) en.nextElement();
            Object obj = session.getAttribute(attrName);
            if (obj == null || !(obj instanceof LogoutSurvivor)) {
                attributesToDelete.add(attrName);
            }//w w  w  .j  a  v  a2  s.  com
        }
        for (Iterator iterator = attributesToDelete.iterator(); iterator.hasNext();) {
            String attrName = (String) iterator.next();
            session.removeAttribute(attrName);
        }
        try {
            ctx.getRequest().getRequestObject().logout();
            ctx.getRequest().getRequestObject().getSession().invalidate();
        } catch (ServletException e) {
            log.error("Error logging out", e);
        }
    }
}

From source file:org.consultjr.mvc.core.components.ApplicationInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    String queryString = request.getQueryString();
    String uri = request.getRequestURI();
    StringBuffer url = request.getRequestURL();
    HttpSession session = this.getSession(request);
    Enumeration attributes = session.getAttributeNames();
    Map<String, Object> sessionAttributes = new HashMap<>();

    logger.debug("URL: {}", url);
    logger.debug("URI: {}", uri);
    logger.debug("QUERY STRING: {}", queryString);

    logger.debug("Handler Object: {}", handler);

    while (attributes.hasMoreElements()) {
        String name = (String) attributes.nextElement();

        sessionAttributes.put(name, session.getAttribute(name));
    }//  w  ww  .  j  av a2 s .com

    logger.debug("Session: {}", sessionAttributes);

    return true;
}

From source file:org.pentaho.test.platform.web.SessionIT.java

public void testPentahoHttpSession() {
    startTest();//w ww.  j  a va  2s  . c o  m
    // @TOTO Not sure how to test PentahoHttpSession. In a request object to be present
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpSession session = new MockHttpSession();
    request.setSession(session);
    request.setupAddParameter("solution", "samples"); //$NON-NLS-1$//$NON-NLS-2$
    request.setupAddParameter("path", "steel-wheels/reports"); //$NON-NLS-1$ //$NON-NLS-2$
    request.setupAddParameter("action", "Inventory List.xaction"); //$NON-NLS-1$ //$NON-NLS-2$
    request.setupAddParameter("details", "all"); //$NON-NLS-1$ //$NON-NLS-2$
    HttpSession httpSession = session;

    Enumeration attrNames = httpSession.getAttributeNames();
    while (attrNames.hasMoreElements()) {
        System.out.println("Attribute Name " + attrNames.nextElement()); //$NON-NLS-1$
    }
    httpSession.setAttribute("solution", "samples"); //$NON-NLS-1$ //$NON-NLS-2$
    httpSession.removeAttribute("solution"); //$NON-NLS-1$

    finishTest();
}

From source file:com.clican.pluto.cms.ui.servlet.VelocityResourceServlet.java

@SuppressWarnings("unchecked")
@Override/*  www  . ja va 2s .  c  o m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String prefix = request.getContextPath() + request.getServletPath();
    if (request.getRequestURI().startsWith(prefix)) {
        String path = request.getRequestURI().replaceFirst(prefix, "");
        if (path.startsWith("/")) {
            path = path.substring(1, path.indexOf(";"));
        }
        // request.getSession().setAttribute("propertyDescriptionList", new
        // ArrayList<PropertyDescription>());
        Writer w = new OutputStreamWriter(response.getOutputStream(), "utf-8");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
            byte[] data = new byte[is.available()];
            is.read(data);
            String content = new String(data, "utf-8");
            Template t = null;
            VelocityContext velocityContext = new VelocityContext();
            HttpSession session = request.getSession();
            Enumeration<String> en = session.getAttributeNames();
            while (en.hasMoreElements()) {
                String name = en.nextElement();
                velocityContext.put(name, session.getAttribute(name));
            }
            SimpleNode node = RuntimeSingleton.getRuntimeServices().parse(content, path);
            t = new Template();
            t.setName(path);
            t.setRuntimeServices(RuntimeSingleton.getRuntimeServices());
            t.setData(node);
            t.initDocument();
            Writer wr = new OutputStreamWriter(os);
            t.merge(velocityContext, wr);
            wr.flush();
            byte[] datas = os.toByteArray();
            String s = new String(datas);
            log.info(s);
        } catch (Exception e) {
            log.error("", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } finally {
            if (w != null) {
                w.close();
            }
            if (is != null) {
                is.close();
            }
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

}

From source file:com.liferay.samplestruts.struts.action.ViewChartAction.java

private Object _getAttribute(HttpServletRequest request, String attrName) {

    // Go through all the session attributes and use Sun's
    // PortletSessionUtil to match the correct attribute name

    HttpSession session = request.getSession();

    Enumeration<String> enu = session.getAttributeNames();

    while (enu.hasMoreElements()) {
        String encodedAttrName = enu.nextElement();

        String decodedAttrName = PortletSessionUtil.decodeAttributeName(encodedAttrName);

        if (decodedAttrName.equals(attrName)) {
            return session.getAttribute(encodedAttrName);
        }/*from  www  . j  a va2s . c o  m*/
    }

    return null;
}

From source file:org.exoplatform.frameworks.jcr.command.web.GenericWebAppContext.java

public GenericWebAppContext(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response, SessionProvider sessionProvider, ManageableRepository repository) {

    initialize(servletContext, request, response);

    this.sessionProvider = sessionProvider;
    this.repository = repository;

    // log.info("WEb context ---------------");
    // initialize context with all props
    Enumeration en = servletContext.getInitParameterNames();
    while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        put(name, servletContext.getInitParameter(name));
        LOG.debug("ServletContext init param: " + name + "=" + servletContext.getInitParameter(name));
    }//from   ww w .  ja v  a 2  s  .  co  m

    en = servletContext.getAttributeNames();
    while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        put(name, servletContext.getAttribute(name));
        LOG.debug("ServletContext: " + name + "=" + servletContext.getAttribute(name));
    }

    HttpSession session = request.getSession(false);
    if (session != null) {
        en = session.getAttributeNames();
        while (en.hasMoreElements()) {
            String name = (String) en.nextElement();
            put(name, session.getAttribute(name));
            LOG.debug("Session: " + name + "=" + session.getAttribute(name));
        }
    }

    en = request.getAttributeNames();
    while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        put(name, request.getAttribute(name));
    }

    en = request.getParameterNames();
    while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        put(name, request.getParameter(name));
        LOG.debug("Request: " + name + "=" + request.getParameter(name));
    }
}