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.owasp.webgoat.service.SessionService.java

/**
 * Returns hints for current lesson//  w w w.j  a v  a 2  s .c  o  m
 *
 * @param session a {@link javax.servlet.http.HttpSession} object.
 * @param request a {@link javax.servlet.http.HttpServletRequest} object.
 * @return a {@link java.lang.String} object.
 */
@RequestMapping(value = "/session.mvc", produces = "application/json")
public @ResponseBody String showSession(HttpServletRequest request, HttpSession session) {
    StringBuilder sb = new StringBuilder();
    sb.append("id").append(" = ").append(session.getId()).append("\n");
    sb.append("created").append(" = ").append(new Date(session.getCreationTime())).append("\n");
    sb.append("last access").append(" = ").append(new Date(session.getLastAccessedTime())).append("\n");
    sb.append("timeout (secs)").append(" = ").append(session.getMaxInactiveInterval()).append("\n");
    sb.append("session from cookie?").append(" = ").append(request.isRequestedSessionIdFromCookie())
            .append("\n");
    sb.append("session from url?").append(" = ").append(request.isRequestedSessionIdFromURL()).append("\n");
    sb.append("=====================================\n");
    // get attributes
    List<String> attributes = new ArrayList<String>();
    Enumeration keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String name = (String) keys.nextElement();
        attributes.add(name);
    }
    Collections.sort(attributes);
    for (String attribute : attributes) {
        String value = session.getAttribute(attribute) + "";
        sb.append(attribute).append(" = ").append(value).append("\n");
    }
    return sb.toString();
}

From source file:password.pwm.http.filter.RequestInitializationFilter.java

private void checkIfSessionRecycleNeeded(final PwmRequest pwmRequest) throws IOException, ServletException {
    if (!pwmRequest.getPwmSession().getSessionStateBean().isSessionIdRecycleNeeded()) {
        return;/*from www . j  a  v a 2  s.  com*/
    }

    final boolean recycleEnabled = Boolean
            .parseBoolean(pwmRequest.getConfig().readAppProperty(AppProperty.HTTP_SESSION_RECYCLE_AT_AUTH));

    if (!recycleEnabled) {
        return;
    }
    LOGGER.debug(pwmRequest, "forcing new http session due to authentication");

    final HttpServletRequest req = pwmRequest.getHttpServletRequest();

    // read the old session data
    final HttpSession oldSession = req.getSession(true);
    final int oldMaxInactiveInterval = oldSession.getMaxInactiveInterval();
    final Map<String, Object> sessionAttributes = new HashMap<>();
    final Enumeration oldSessionAttrNames = oldSession.getAttributeNames();
    while (oldSessionAttrNames.hasMoreElements()) {
        final String attrName = (String) oldSessionAttrNames.nextElement();
        sessionAttributes.put(attrName, oldSession.getAttribute(attrName));
    }

    for (final String attrName : sessionAttributes.keySet()) {
        oldSession.removeAttribute(attrName);
    }

    //invalidate the old session
    oldSession.invalidate();

    // make a new session
    final HttpSession newSession = req.getSession(true);

    // write back all the session data
    for (final String attrName : sessionAttributes.keySet()) {
        newSession.setAttribute(attrName, sessionAttributes.get(attrName));
    }

    newSession.setMaxInactiveInterval(oldMaxInactiveInterval);

    pwmRequest.getPwmSession().getSessionStateBean().setSessionIdRecycleNeeded(false);
}

From source file:net.shopxx.controller.shop.OAuthController.java

/**
 * ?session?//from  w w w .  j a  va2s .  c o m
 * @param session
 * @param request
 * @param response
 * @param member
 */
private void saveSession(HttpSession session, HttpServletRequest request, HttpServletResponse response,
        Member member) {
    Cart cart = cartService.getCurrent();
    if (cart != null) {
        if (cart.getMember() == null) {
            cartService.merge(member, cart);
            WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME);
            WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME);
        }
    }
    Map<String, Object> attributes = new HashMap<String, Object>();
    Enumeration<?> keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        attributes.put(key, session.getAttribute(key));
    }
    session.invalidate();
    session = request.getSession();
    for (Entry<String, Object> entry : attributes.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }
    session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), member.getUsername()));
    WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername());
}

From source file:org.kchine.r.server.http.frontend.CommandServlet.java

HashMap<String, Object> cloneAttributes(HttpSession session) {
    HashMap<String, Object> result = new HashMap<String, Object>();

    Enumeration<String> names = session.getAttributeNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        result.put(name, session.getAttribute(name));
    }/* w w  w .  j a v a 2s . co m*/

    return result;
}

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

@RequestMapping(value = "/search", method = RequestMethod.POST)
public final ModelAndView searchProducts(@ModelAttribute("request") final Product request,
        final BindingResult binding) {
    final String methodName = ProductController.CNAME
            + "#searchProducts(@ModelAttribute(\"request\") final Product request, final BindingResult binding)";

    if (DEBUG) {//from   w w w .j av a2  s  .c o  m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Product: {}", request);
    }

    // String viewName = null;
    ProductResponse productResponse = null;
    ModelAndView mView = new ModelAndView();

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpServletRequest hRequest = requestAttributes.getRequest();
    final HttpSession hSession = hRequest.getSession();
    final String lang = hRequest.getParameter(Constants.PARAMETER_LANG);

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

        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);
        }
    }

    try {
        ProductRequest productRequest = new ProductRequest();
        productRequest.setProduct(request);
        productRequest.setLang((StringUtils.isBlank(lang)) ? "en" : lang);

        if (DEBUG) {
            DEBUGGER.debug("ProductRequest: {}", productRequest);
        }

        productResponse = this.productRefSvc.getProductData(productRequest);

        if (DEBUG) {
            DEBUGGER.debug("ProductResponse: {}", productResponse);
        }

        if (productResponse.getRequestStatus() == CoreServicesStatus.FAILURE) {
            mView.setViewName(this.appConfig.getErrorResponsePage());
        }
    } catch (ProductRequestException prx) {
        ERROR_RECORDER.error(prx.getMessage(), prx);

        mView.setViewName(this.appConfig.getErrorResponsePage());
    }

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

    return mView;
}

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

@RequestMapping(value = "/default", method = RequestMethod.GET)
public final ModelAndView showDefaultPage() {
    final String methodName = ProductController.CNAME + "#showDefaultPage()";

    if (DEBUG) {/*from   w w w .j a  v  a2s.co  m*/
        DEBUGGER.debug(methodName);
    }

    ModelAndView mView = new ModelAndView();

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpServletRequest hRequest = requestAttributes.getRequest();
    final HttpSession hSession = hRequest.getSession();
    final String lang = hRequest.getParameter(Constants.PARAMETER_LANG);

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

        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);
        }
    }

    try {
        ProductRequest productRequest = new ProductRequest();
        productRequest.setIsFeatured(true);
        productRequest.setLang((StringUtils.isBlank(lang)) ? "en" : lang);

        if (DEBUG) {
            DEBUGGER.debug("ProductRequest: {}", productRequest);
        }

        ProductResponse productResponse = this.productRefSvc.getFeaturedProducts(productRequest);

        if (DEBUG) {
            DEBUGGER.debug("ProductResponse: {}", productResponse);
        }

        if (productResponse.getRequestStatus() == CoreServicesStatus.SUCCESS) {
            List<Product> featuredProducts = productResponse.getProductList();

            if (DEBUG) {
                DEBUGGER.debug("List<Product>: {}", featuredProducts);
            }

            mView.addObject("featuredProducts", featuredProducts);
        }

        mView.addObject("command", new Product());
        mView.setViewName(this.defaultPage);
    } catch (ProductRequestException prx) {
        ERROR_RECORDER.error(prx.getMessage(), prx);

        mView = new ModelAndView(new RedirectView());
        mView.setViewName(this.appConfig.getErrorResponsePage());
    }

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

    return mView;
}

From source file:org.codehaus.wadi.web.TestHttpSession.java

public void testCreateHttpSession(Manager manager) {
    events.clear();//from  w  w w. j av a  2s . c o  m

    // create a session
    HttpSession session = ((WADIHttpSession) manager.create(null)).getWrapper();
    assertTrue(!session.getAttributeNames().hasMoreElements());
    assertTrue(session.getValueNames().length == 0);
    Pair pair = (Pair) events.remove(0);
    assertTrue(pair != null);
    assertTrue(pair.getType().equals("sessionCreated"));
    assertTrue(pair.getEvent().getSession() == session);
    assertTrue(events.size() == 0);
}

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

@RequestMapping(value = "/product/{product}", method = RequestMethod.GET)
public final ModelAndView getProductInfo(@PathVariable("product") final String product) {
    final String methodName = ProductController.CNAME
            + "#getProductInfo(@PathVariable(\"product\") final String product)";

    if (DEBUG) {/*from  w w  w  . jav  a  2 s.  co  m*/
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Product: {}", product);
    }

    ModelAndView mView = new ModelAndView();

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpServletRequest hRequest = requestAttributes.getRequest();
    final HttpSession hSession = hRequest.getSession();
    final String lang = hRequest.getParameter(Constants.PARAMETER_LANG);

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

        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);
        }
    }

    try {
        Product reqProduct = new Product();
        reqProduct.setProductId(product);

        if (DEBUG) {
            DEBUGGER.debug("Product: {}", reqProduct);
        }

        ProductRequest productRequest = new ProductRequest();
        productRequest.setProduct(reqProduct);
        productRequest.setLang((StringUtils.isBlank(lang)) ? "en" : lang);

        if (DEBUG) {
            DEBUGGER.debug("ProductRequest: {}", productRequest);
        }

        ProductResponse productResponse = this.productRefSvc.getProductData(productRequest);

        if (DEBUG) {
            DEBUGGER.debug("ProductResponse: {}", productResponse);
        }

        if (productResponse.getRequestStatus() == CoreServicesStatus.SUCCESS) {
            Product resProduct = productResponse.getProduct();

            if (DEBUG) {
                DEBUGGER.debug("Product: {}", resProduct);
            }

            mView.addObject("product", resProduct);
            mView.setViewName(this.showProduct);
        } else {
            mView = new ModelAndView(new RedirectView());
            mView.addObject(Constants.ERROR_MESSAGE, productResponse.getResponse());
            mView.setViewName(this.defaultPage);
        }
    } catch (ProductRequestException prx) {
        ERROR_RECORDER.error(prx.getMessage(), prx);

        mView.setViewName(this.appConfig.getErrorResponsePage());
    }

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

    return mView;
}

From source file:org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter.java

/**
 * Removes all attributes stored in session
 * //from  ww  w  .j  a  v a  2 s. co  m
 * @param session Session
 */
@SuppressWarnings("unchecked")
private void clearSession(HttpSession session) {
    Enumeration<String> names = (Enumeration<String>) session.getAttributeNames();
    while (names.hasMoreElements()) {
        session.removeAttribute(names.nextElement());
    }
}

From source file:com.google.ratel.service.error.ErrorReport.java

/**
 * Return a error report HTML &lt;div&gt; element for the given error and page. The HTML &lt;div&gt; element 'id' and 'class' attribute
 * values are 'errorReport'./*from  ww  w  .  j  av  a  2s . c o m*/
 *
 * @return a error HTML display string
 */
@SuppressWarnings("unchecked")
public String toString() {

    if (getMode() == Mode.PRODUCTION) {
        Locale locale = request.getLocale();
        ResourceBundle bundle = RatelUtils.getBundle("ratel", locale);
        return bundle.getString("production-error-message");
    }

    HtmlStringBuffer buffer = new HtmlStringBuffer(10 * 1024);

    Throwable cause = getCause();

    buffer.append("<div id='errorReport' class='errorReport'>\n");

    // Exception table
    buffer.append("<table class=\"flat-table flat-table-1\"><tbody>");
    if (isParseError()) {
        buffer.append("<tr><th colspan='2' class='header'>Service Parsing Error</th></tr>");
        buffer.append("<tr><th width='12%'>Source</th><td>");
        buffer.append(getSourceName());
        buffer.append("</td></tr>");
    } else {
        buffer.append("<tr><th colspan='2' class='header'>Exception</th></tr>");
        buffer.append("<tr><th width='12%'>Class</th><td>");
        buffer.append(cause.getClass().getName());
        buffer.append("</td></tr>");
    }
    buffer.append("<tr><th valign='top' width='12%'>Message</th><td>");
    buffer.append(getMessage());
    buffer.append("</td></tr>");
    if (getSourceReader() != null) {
        buffer.append("<tr><td class='pre' valign='top' colspan='2'>\n");
        buffer.append(getRenderedSource());
        buffer.append("</td></tr>");
    }
    if (!isParseError()) {
        buffer.append("<tr><td valign='top' colspan='2' class='pre'>\n");
        buffer.append(getStackTrace());
        buffer.append("</td></tr>");
    }
    buffer.append("</tbody></table>");
    buffer.append("<br/>");

    // Service table
    buffer.append("<table class=\"flat-table flat-table-1\"><tbody>");
    buffer.append("<tr><th colspan='2' class='header'>Service</th></tr>");
    buffer.append("<tr><th width='12%'>Service</th><td>");

    if (serviceClass != null) {
        String location = RatelUtils.buildLocation(serviceClass, method);
        buffer.append(location);
    }
    buffer.append("</td></tr>");
    buffer.append("<tr><th width='12%'>Path</th><td>");
    buffer.append(RatelUtils.getResourcePath(request));
    buffer.append("</td></tr>");
    buffer.append("</tbody></table>");
    buffer.append("<br/>");

    // Request table
    buffer.append("<table class=\"flat-table flat-table-1\"><tbody>");
    buffer.append("<tr><th colspan='2' class='header'>Request</th></tr>");

    Map<String, Object> requestAttributes = new TreeMap<String, Object>();
    Enumeration attributeNames = request.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = attributeNames.nextElement().toString();
        requestAttributes.put(name, request.getAttribute(name));
    }
    buffer.append("<tr><th width='12%' valign='top'>Attributes</th><td>");
    writeMap(requestAttributes, buffer);
    buffer.append("</td></tr>");

    buffer.append("<tr><th width='12%'>Auth Type</th><td>");
    buffer.append(request.getAuthType());
    buffer.append("</td></tr>");

    buffer.append("<tr><th width='12%'>Context Path</th><td>");
    buffer.append("<a href='");
    buffer.append(request.getContextPath());
    buffer.append("'>");
    buffer.append(request.getContextPath());
    buffer.append("</a>");
    buffer.append("</td></tr>");

    Map<String, Object> requestHeaders = new TreeMap<String, Object>();
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement().toString();
        requestHeaders.put(name, request.getHeader(name));
    }
    buffer.append("<tr><th width='12%' valign='top'>Headers</th><td>");
    writeMap(requestHeaders, buffer);
    buffer.append("</td></tr>");

    buffer.append("<tr><th width='12%'>Query</th><td>");
    String escapedQueryString = RatelUtils.escape(request.getQueryString());
    buffer.append(escapedQueryString);
    buffer.append("</td></tr>");

    buffer.append("<tr><th width='12%'>Method</th><td>");
    buffer.append(request.getMethod());
    buffer.append("</td></tr>");

    String content = null;
    if (RatelUtils.isPost(request) && RatelUtils.isJsonContentType(request)) {
        try {
            content = RatelUtils.getContent(request, ratelConfig.getMaxRequestSize());
        } catch (Exception ignore) {
        }

        buffer.append("<tr><th width='12%' valign='top'>Json Request Content></th>");
        buffer.append("<td class='pre'>");
        if (StringUtils.isBlank(content)) {
            buffer.append(
                    "Could not retrieve HttpServletRequest content from Reader, most likely because the content was already read before the exception occurred.");
        } else {
            buffer.append("<pre class='prettyprint'>");

            String json = content;
            try {
                // Pretty format the json
                JsonService jsonService = ratelConfig.getJsonService();
                JsonElement node = jsonService.parseJson(content);
                if (node != null) {
                    json = jsonService.toJson(node);
                }

            } catch (Exception ignore) {
            }

            buffer.append(json);
            buffer.append("</pre>");
        }
        buffer.append("</td></tr>");

    } else {
        Map<String, Object> requestParams = new TreeMap<String, Object>();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String name = paramNames.nextElement().toString();
            requestParams.put(name, request.getParameter(name));
        }
        buffer.append("<tr><th width='12%' valign='top'>Parameters</th><td>");
        writeMap(requestParams, buffer);
        buffer.append("</td></tr>");
    }

    buffer.append("<tr><th width='12%'>Remote User</th><td>");
    buffer.append(request.getRemoteUser());
    buffer.append("</td></tr>");

    buffer.append("<tr><th width='12%' valign='top'URI</th><td>");
    buffer.append("<a href='");
    String requestURI = RatelUtils.getRequestURI(request);
    buffer.append(requestURI);
    buffer.append("'>");
    buffer.append(requestURI);
    buffer.append("</a>");
    buffer.append("</td></tr>");

    buffer.append("<tr><th width='12%'>URL</th><td>");
    buffer.append("<a href='");
    buffer.append(request.getRequestURL());
    buffer.append("'>");
    buffer.append(request.getRequestURL());
    buffer.append("</a>");
    buffer.append("</td></tr>");

    Map<String, Object> sessionAttributes = new TreeMap<String, Object>();
    if (request.getSession(false) != null) {
        HttpSession session = request.getSession();
        attributeNames = session.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String name = attributeNames.nextElement().toString();
            sessionAttributes.put(name, session.getAttribute(name));
        }
    }
    buffer.append("<tr><th width='12%' valign='top'>Session</th><td>");
    writeMap(sessionAttributes, buffer);
    buffer.append("</td></tr>");
    buffer.append("</tbody></table>\n");

    buffer.append("</div>\n");

    return buffer.toString();
}