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:org.codehaus.wadi.web.TestHttpSession.java

public void testGetAttributeNames(Manager manager) {
    HttpSession session = ((WADIHttpSession) manager.create(null)).getWrapper();
    assertTrue(enumerationLength(session.getAttributeNames()) == 0);
    session.setAttribute("foo", "bar");
    assertTrue(enumerationLength(session.getAttributeNames()) == 1);
    session.setAttribute("bar", "baz");
    assertTrue(enumerationLength(session.getAttributeNames()) == 2);
    session.setAttribute("baz", "foo");
    assertTrue(enumerationLength(session.getAttributeNames()) == 3);
    session.setAttribute("baz", null);
    assertTrue(enumerationLength(session.getAttributeNames()) == 2);
    session.setAttribute("bar", null);
    assertTrue(enumerationLength(session.getAttributeNames()) == 1);
    session.setAttribute("foo", null);
    assertTrue(enumerationLength(session.getAttributeNames()) == 0);
}

From source file:elw.web.ErrController.java

@RequestMapping(value = "*")
public ModelAndView do_handle(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    final String url = (String) req.getAttribute("javax.servlet.error.request_uri");
    final Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status_code");

    if (statusCode != null && 404 == statusCode && ignoredUris.contains(url)) {
        resp.sendError(410, "ignored");
        return null;
    }/*w ww.j  a  va 2 s . c  om*/

    try {
        final String message = (String) req.getAttribute("javax.servlet.error.message");
        final Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
        final String eventId = Long.toString(System.currentTimeMillis(), 36);

        final StringWriter logDest = new StringWriter();
        final PrintWriter logOut = new PrintWriter(logDest);
        final HttpSession session = req.getSession(false);

        logOut.println(
                "web error: eventId=" + eventId + " status=" + statusCode + " message='" + message + "'");
        logOut.println("url: " + url);
        logOut.print("attributes: ");
        final Enumeration reqAttrNames = req.getAttributeNames();
        while (reqAttrNames.hasMoreElements()) {
            final String aName = (String) reqAttrNames.nextElement();
            if (!aName.startsWith("javax.servlet") && !aName.startsWith("org.springframework")) {
                logOut.print(aName + "=" + String.valueOf(req.getAttribute(aName)) + " ");
            }
        }
        logOut.println();

        if (session != null) {
            logOut.println("session id: " + session.getId());
            logOut.print("session: ");
            final Enumeration sessAttrNames = session.getAttributeNames();
            while (sessAttrNames.hasMoreElements()) {
                final String aName = (String) sessAttrNames.nextElement();
                if (!aName.startsWith("javax.servlet") && !aName.startsWith("org.springframework")) {
                    logOut.print(aName + "=" + String.valueOf(session.getAttribute(aName)) + " ");
                }
            }
            logOut.println();
        }

        log.error(logDest.toString(), throwable);

        final PrintWriter out = resp.getWriter();

        out.print("<html><title>HTTP status " + statusCode + " : " + message + "</title>"
                + "<body><h3>HTTP status " + statusCode + " : " + message + "</h3>"
                + "Sorry for inconvenience and thanks for finding just another bug out there.<br/>"
                + "For the time being, you may log out, log in and then try the operation once again.<br/><br/>"
                + "Event reference id: <b>" + eventId + "</b>." + "</body></html>");
    } catch (Throwable t) {
        log.error("failed on reporting error", t);
    }

    return null;
}

From source file:org.sakaiproject.tool.impl.RebuildBreakdownServiceImpl.java

/**
 * storeSessionAttributes() puts all of the attributes that are available from session.getAttribute()
 * into the sessionMap which will be stored in the cluster
 * @param s Session that is being stored
 * @param sessionMap the Map that will contain the attributes that will eventually stored in the cluster
 *//*from w w  w. j  av  a2s.  c om*/
private void storeSessionAttributes(HttpSession s, Map<String, Serializable> sessionMap) {
    @SuppressWarnings("unchecked")
    Enumeration<String> keys = s.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = keys.nextElement();
        if (sessionAttributeBlacklist.contains(key)) {
            // skip processing on this key
            continue;
        }
        if (log.isDebugEnabled())
            log.debug("attempting to store session attribute key [" + key + "] in cache");
        Object object = s.getAttribute(key);
        Serializable toStore = serializeSessionAttribute(object);
        // now store it if we were successful
        if (toStore != null) {
            sessionMap.put(key, toStore);
            if (log.isDebugEnabled())
                log.debug("RebuildBreakdownServiceImpl.storeSession, putting key [" + key + "], class: ["
                        + object.getClass().getName() + "], value: [" + object + "]");
        }
    }
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.SessionDump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    Page page = new Page();

    HttpSession session = request.getSession(getURI(request).indexOf("new") > 0);

    page.title("Session Dump Servlet: ");

    TableForm tf = new TableForm(response.encodeURL(getURI(request)));
    tf.method("POST");

    if (session == null) {
        page.add("<H1>No Session</H1>");
        tf.addButton("Action", "New Session");
    } else {//from   ww w  .j av  a  2  s  .c  o  m
        try {
            tf.addText("ID", session.getId());
            tf.addText("State", session.isNew() ? "NEW" : "Valid");
            tf.addText("Creation", new Date(session.getCreationTime()).toString());
            tf.addText("Last Access", new Date(session.getLastAccessedTime()).toString());
            tf.addText("Max Inactive", "" + session.getMaxInactiveInterval());

            tf.addText("Context", "" + session.getServletContext());

            Enumeration keys = session.getAttributeNames();
            while (keys.hasMoreElements()) {
                String name = (String) keys.nextElement();
                String value = session.getAttribute(name).toString();
                tf.addText(name, value);
            }

            tf.addTextField("Name", "Property Name", 20, "name");
            tf.addTextField("Value", "Property Value", 20, "value");
            tf.addTextField("MaxAge", "MaxAge(s)", 5, "");
            tf.addButtonArea();
            tf.addButton("Action", "Set");
            tf.addButton("Action", "Remove");
            tf.addButton("Action", "Invalidate");

            page.add(tf);
            tf = null;
            if (request.isRequestedSessionIdFromCookie())
                page.add("<P>Turn off cookies in your browser to try url encoding<BR>");

            if (request.isRequestedSessionIdFromURL())
                page.add("<P>Turn on cookies in your browser to try cookie encoding<BR>");

        } catch (IllegalStateException e) {
            log.debug(LogSupport.EXCEPTION, e);
            page.add("<H1>INVALID Session</H1>");
            tf = new TableForm(getURI(request));
            tf.addButton("Action", "New Session");
        }
    }

    if (tf != null)
        page.add(tf);

    Writer writer = response.getWriter();
    page.write(writer);
    writer.flush();
}

From source file:org.eiichiro.bootleg.AbstractRequest.java

/**
 * Returns the Web endpoint method parameter from HTTP session.
 * /* www .j a  v a 2  s  . c  o  m*/
 * @param type The parameter type.
 * @param name The parameter name.
 * @return The Web endpoint method parameter from HTTP session.
 */
protected Object session(Type type, String name) {
    return parameter(type, name, new Function<String, Object>() {

        public Object apply(String name) {
            return context.session().getAttribute(name);
        }

    }, new Function<String, Collection<Object>>() {

        @SuppressWarnings("unchecked")
        public Collection<Object> apply(String name) {
            HttpSession session = context.session();
            Object attribute = session.getAttribute(name);

            if (attribute instanceof Collection<?>) {
                return (Collection<Object>) attribute;
            }

            Map<String, Object> map = new TreeMap<String, Object>();

            for (Object object : Collections.list(session.getAttributeNames())) {
                String key = (String) object;

                if (key.startsWith(name + "[")) {
                    map.put(key, session.getAttribute(key));
                }
            }

            return (map.isEmpty()) ? null : map.values();
        }

    });
}

From source file:nl.armatiek.xslweb.serializer.RequestSerializer.java

@SuppressWarnings("rawtypes")
private void serializeSession() throws Exception {
    HttpSession session = req.getSession();
    if (session == null) {
        return;//from   ww  w . j  a  v  a  2s.  c o  m
    }
    xsw.writeStartElement(URI, "session");
    dataElement(xsw, URI, "creation-time", getXsDateTimeString(new Date(session.getCreationTime())));
    dataElement(xsw, URI, "id", session.getId());
    dataElement(xsw, URI, "last-accessed-time", getXsDateTimeString(new Date(session.getLastAccessedTime())));
    dataElement(xsw, URI, "max-inactive-interval", Integer.toString(session.getMaxInactiveInterval()));
    dataElement(xsw, URI, "is-new", Boolean.toString(session.isNew()));
    Enumeration attrNames = session.getAttributeNames();
    if (attrNames.hasMoreElements()) {
        xsw.writeStartElement(URI, "attributes");
        while (attrNames.hasMoreElements()) {
            String attrName = (String) attrNames.nextElement();
            xsw.writeStartElement(URI, "attribute");
            xsw.writeAttribute("name", attrName);
            Object attr = session.getAttribute(attrName);
            if (attr instanceof Collection) {
                @SuppressWarnings("unchecked")
                Collection<Attribute> attrs = (Collection<Attribute>) attr;
                for (Attribute a : attrs) {
                    xsw.writeStartElement(URI, "item");
                    if (a.isSerialized()) {
                        xsw.writeAttribute("type", a.getType());
                        getFilteredXMLReader().parse(new InputSource(new StringReader(a.getSerializedValue())));
                    } else {
                        xsw.writeAttribute("type", a.getType());
                        xsw.writeCharacters(a.getValue().toString());
                    }
                    xsw.writeEndElement();
                }
            } else {
                xsw.writeCharacters(attr.toString());
            }
            xsw.writeEndElement();
        }
        xsw.writeEndElement();
    }
    xsw.writeEndElement();
}

From source file:at.gv.egovernment.moa.id.configuration.struts.action.IndexAction.java

private HttpSession generateNewJSession(HttpServletRequest request) {
    HttpSession session = request.getSession(false);

    if (session != null) {

        HashMap<String, Object> attributes = new HashMap<String, Object>();

        Enumeration<String> enames = session.getAttributeNames();
        while (enames.hasMoreElements()) {
            String name = enames.nextElement();
            if (!name.equals("JSESSIONID"))
                attributes.put(name, session.getAttribute(name));
        }//from  www. j  a  v  a 2  s.  co m
        session.invalidate();

        session = request.getSession(true);
        for (Entry<String, Object> et : attributes.entrySet())
            session.setAttribute(et.getKey(), et.getValue());

    } else
        session = request.getSession(true);

    return session;
}

From source file:com.konakart.actions.BaseAction.java

/**
 * Creates a new session when we switch to SSL to avoid hackers using the current session id
 * (which may have been visible on the URL) to log into the application
 * /*ww w  .  ja  v  a2  s . com*/
 * @param request
 *            HttpServletRequest
 */

private void changeSession(HttpServletRequest request) {
    /* Used to temporarily store objects from current session */
    HashMap<String, Object> currentSessionMap = new HashMap<String, Object>();

    /* Loop through all objects saved in the current session and place them in the hash map */
    HttpSession currentSession = request.getSession();

    Enumeration<String> atrNameEnum = currentSession.getAttributeNames();
    while (atrNameEnum.hasMoreElements()) {
        String attrName = atrNameEnum.nextElement();
        currentSessionMap.put(attrName, currentSession.getAttribute(attrName));
    }

    /* Invalidate the current session */
    currentSession.invalidate();
    currentSession = null;

    /* Create a new session */
    HttpSession newSession = request.getSession(true);

    /* Load the new session with objects saved in the hash map */
    Set<String> atrNameSet = currentSessionMap.keySet();
    for (String attrName : atrNameSet) {
        newSession.setAttribute(attrName, currentSessionMap.get(attrName));
    }

    return;
}

From source file:com.cws.us.pws.controllers.CommonController.java

@RequestMapping(value = "/sitemap", method = RequestMethod.GET)
public final ModelAndView showSiteMap() {
    final String methodName = CommonController.CNAME + "#showSiteMap()";

    if (DEBUG) {//from   w  w  w. j  a v a 2s . c om
        DEBUGGER.debug(methodName);
    }

    ModelAndView mView = new ModelAndView();

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpServletRequest hRequest = requestAttributes.getRequest();
    final HttpSession hSession = hRequest.getSession();

    if (DEBUG) {
        DEBUGGER.debug("ServletRequestAttributes: {}", requestAttributes);
        DEBUGGER.debug("HttpServletRequest: {}", hRequest);
        DEBUGGER.debug("HttpSession: {}", hSession);

        DEBUGGER.debug("Dumping session content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> sessionEnumeration = hSession.getAttributeNames();

        while (sessionEnumeration.hasMoreElements()) {
            String sessionElement = sessionEnumeration.nextElement();
            Object sessionValue = hSession.getAttribute(sessionElement);

            DEBUGGER.debug("Attribute: " + sessionElement + "; Value: " + sessionValue);
        }

        DEBUGGER.debug("Dumping request content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> requestEnumeration = hRequest.getAttributeNames();

        while (requestEnumeration.hasMoreElements()) {
            String requestElement = requestEnumeration.nextElement();
            Object requestValue = hRequest.getAttribute(requestElement);

            DEBUGGER.debug("Attribute: " + requestElement + "; Value: " + requestValue);
        }

        DEBUGGER.debug("Dumping request parameters:");
        @SuppressWarnings("unchecked")
        Enumeration<String> paramsEnumeration = hRequest.getParameterNames();

        while (paramsEnumeration.hasMoreElements()) {
            String requestElement = paramsEnumeration.nextElement();
            Object requestValue = hRequest.getParameter(requestElement);

            DEBUGGER.debug("Parameter: " + requestElement + "; Value: " + requestValue);
        }
    }

    mView.setViewName(this.appConfig.getSiteMap());

    if (DEBUG) {
        DEBUGGER.debug("ModelAndView: {}", mView);
    }

    return mView;
}