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:org.jruby.rack.mock.WebUtils.java

/**
 * Get the specified session attribute, creating and setting a new attribute if
 * no existing found. The given class needs to have a public no-arg constructor.
 * Useful for on-demand state objects in a web tier, like shopping carts.
 * @param session current HTTP session/*from ww  w.  jav  a 2  s . com*/
 * @param name the name of the session attribute
 * @param clazz the class to instantiate for a new attribute
 * @return the value of the session attribute, newly created if not found
 * @throws IllegalArgumentException if the session attribute could not be instantiated
 */
public static Object getOrCreateSessionAttribute(HttpSession session, String name, Class<?> clazz)
        throws IllegalArgumentException {

    Assert.notNull(session, "Session must not be null");
    Object sessionObject = session.getAttribute(name);
    if (sessionObject == null) {
        try {
            sessionObject = clazz.newInstance();
        } catch (InstantiationException ex) {
            throw new IllegalArgumentException("Could not instantiate class [" + clazz.getName()
                    + "] for session attribute '" + name + "': " + ex.getMessage());
        } catch (IllegalAccessException ex) {
            throw new IllegalArgumentException("Could not access default constructor of class ["
                    + clazz.getName() + "] for session attribute '" + name + "': " + ex.getMessage());
        }
        session.setAttribute(name, sessionObject);
    }
    return sessionObject;
}

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

        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:ece356.UserDBAO.java

public static boolean isLoggedIn(HttpServletRequest request) {
    HttpSession session = request.getSession();
    UserData loggedInUser = (UserData) session.getAttribute("userData");
    return loggedInUser != null;
}

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

/**
 * Check if the request was triggered by an Ajax call.
 * @param request the request//from w  ww  . ja va2  s .  c  om
 * @return <code>true</code> if Ajax
 */
public static boolean isAjax(final HttpServletRequest request) {

    String ajaxHeaderName = (String) ReflectionUtils.getConfigProperty("ajaxHeader");

    // check the current request's headers
    if ("XMLHttpRequest".equals(request.getHeader(ajaxHeaderName))) {
        return true;
    }

    Object ajaxCheckClosure = ReflectionUtils.getConfigProperty("ajaxCheckClosure");
    if (ajaxCheckClosure instanceof Closure) {
        Object result = ((Closure<?>) ajaxCheckClosure).call(request);
        if (result instanceof Boolean && ((Boolean) result)) {
            return true;
        }
    }

    // look for an ajax=true parameter
    if ("true".equals(request.getParameter("ajax"))) {
        return true;
    }

    // process multipart requests
    MultipartHttpServletRequest multipart = ((MultipartHttpServletRequest) request
            .getAttribute("org.springframework.web.multipart.MultipartHttpServletRequest"));
    if (multipart != null && "true".equals(multipart.getParameter("ajax"))) {
        return true;
    }

    // check the SavedRequest's headers
    HttpSession httpSession = request.getSession(false);
    if (httpSession != null) {
        SavedRequest savedRequest = (SavedRequest) httpSession.getAttribute(SAVED_REQUEST);
        if (savedRequest != null) {
            return !savedRequest.getHeaderValues(ajaxHeaderName).isEmpty();
        }
    }

    return false;
}

From source file:com.exilant.exility.core.HttpRequestHandler.java

/**
 * populate data with global/session variables, if this is an authenticated
 * session. Caller can have the CommonFieldNames.CSRF_HEADER token either in
 * the header, or a field already extracted into inData
 * //from w  w w .ja  va  2s  .com
 * @param req
 * @param inData
 *            into which session fields need to be extracted
 * @return true if this is an authenticated session, false otherwise
 */
public static boolean extractSessionFields(HttpServletRequest req, ServiceData inData) {
    String token = req.getHeader(CommonFieldNames.CSRF_HEADER);
    if (token == null) {
        token = inData.getValue(CommonFieldNames.CSRF_HEADER);
    }

    if (token == null || token.length() == 0) {
        return false;
    }

    HttpSession session = req.getSession(false);
    if (session == null) {
        return false;
    }

    Object obj = session.getAttribute(token);
    if (obj == null) {
        return false;
    }

    if (obj instanceof SessionData == false) {
        return false;
    }
    ((SessionData) obj).extractAll(inData);
    return true;
}

From source file:grails.plugin.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. j a v  a 2  s .  c o m
 * @return the closure's return value
 */
public static Object doWithAuth(@SuppressWarnings("rawtypes") final Closure closure) {
    boolean set = false;
    if (SecurityContextHolder.getContext().getAuthentication() == null
            && SecurityRequestHolder.getRequest() != null) {
        HttpSession httpSession = SecurityRequestHolder.getRequest().getSession(false);
        SecurityContext securityContext = null;
        if (httpSession != null) {
            securityContext = (SecurityContext) httpSession
                    .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            if (securityContext != null) {
                SecurityContextHolder.setContext(securityContext);
                set = true;
            }
        }
    }

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

From source file:com.web.panacea.service.SessionServiceImpl.java

public String getRole(HttpSession session) {
    return session.getAttribute("role").toString();
}

From source file:com.jsmartframework.web.manager.WebContext.java

/**
 * Check if attribute is carried on {@link HttpServletRequest}, {@link HttpSession} or {@link ServletContext}
 * instances associated with current request being processed.
 *
 * @param name name of the attribute./*from   w ww .ja va 2s  . c  o m*/
 * @return true if the attribute is contained in one of the instances {@link HttpServletRequest},
 * {@link HttpSession} or {@link ServletContext}, false otherwise.
 */
public static boolean containsAttribute(String name) {
    if (name != null) {
        HttpServletRequest request = getRequest();
        if (request != null && request.getAttribute(name) != null) {
            return true;
        }

        HttpSession session = getSession();
        if (session != null) {
            synchronized (session) {
                if (session.getAttribute(name) != null) {
                    return true;
                }
            }
        }

        return getApplication().getAttribute(name) != null;
    }
    return false;
}

From source file:com.jsmartframework.web.manager.WebContext.java

/**
 * Returns the attribute carried on {@link HttpServletRequest}, {@link HttpSession} or {@link ServletContext}
 * instances associated with current request being processed.
 *
 * @param name name of the attribute./* w w w.ja v a  2s . c  om*/
 * @return the {@link Object} mapped by attribute name on the current request.
 */
public static Object getAttribute(String name) {
    if (name != null) {
        HttpServletRequest request = getRequest();
        if (request != null && request.getAttribute(name) != null) {
            return request.getAttribute(name);
        }

        HttpSession session = getSession();
        if (session != null) {
            synchronized (session) {
                if (session.getAttribute(name) != null) {
                    return session.getAttribute(name);
                }
            }
        }

        ServletContext application = getApplication();
        if (application.getAttribute(name) != null) {
            return application.getAttribute(name);
        }
    }
    return null;
}

From source file:controller.AcountController.java

@RequestMapping(method = RequestMethod.GET)
public String showAccount(HttpSession session) {
    if (session.getAttribute("username") != null) {
        return "account";
    }//  w  w  w.j a  v  a2  s.c  om
    return "redirect:user/login";
}