Example usage for javax.servlet.http HttpSession removeAttribute

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

Introduction

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

Prototype

public void removeAttribute(String name);

Source Link

Document

Removes the object bound with the specified name from this session.

Usage

From source file:csns.web.controller.ForumController.java

@RequestMapping("/department/{dept}/forum/list")
public String list(@PathVariable String dept, @RequestParam(required = false) Boolean showAll,
        HttpSession session, ModelMap models) {
    Department department = departmentDao.getDepartment(dept);
    models.put("department", department);
    models.put("systemForums", forumDao.getSystemForums());

    User user = SecurityUtils.getUser();
    List<Forum> departmentForums = new ArrayList<Forum>();
    for (Forum departmentForum : department.getForums())
        if (!departmentForum.isMembersOnly() || departmentForum.isMember(user))
            departmentForums.add(departmentForum);
    models.put("departmentForums", departmentForums);

    if (showAll != null) {
        if (showAll)
            session.setAttribute("showAll", true);
        else/*from w w  w.  j a  va 2s .co  m*/
            session.removeAttribute("showAll");
    }

    List<Forum> courseForums = new ArrayList<Forum>();
    if (SecurityUtils.isAnonymous() || session.getAttribute("showAll") != null) {
        courseForums = forumDao.getCourseForums(department);
    } else {
        List<Subscription> subscriptions = subscriptionDao.getSubscriptions(SecurityUtils.getUser(),
                Forum.class);
        for (Subscription subscription : subscriptions) {
            Forum forum = (Forum) subscription.getSubscribable();
            if (forum.getCourse() != null)
                courseForums.add(forum);
        }
    }
    models.put("courseForums", courseForums);

    return "forum/list";
}

From source file:com.pararede.alfresco.security.AlfrescoContainerSecurityFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession httpSession = httpRequest.getSession();

    String userName = httpRequest.getUserPrincipal().getName();
    User userAuth = AuthenticationHelper.getUser(httpRequest, httpResponse);
    if ((userAuth == null) || !userName.equals(userAuth.getUserName())) {
        try {/*from  w  w  w  .  j a v a  2  s .c o m*/
            TransactionService transactionService = this.registry.getTransactionService();
            UserTransaction tx = transactionService.getUserTransaction();
            try {
                tx.begin();

                // remove the session invalidated flag (used to remove last username cookie by
                // AuthenticationFilter)
                httpSession.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED);

                if (logger.isDebugEnabled()) {
                    logger.debug("Authenticating user " + userName);
                }
                AuthenticationService authenticationService = getAuthenticationService();
                authenticationService.authenticate(userName, null);

                PersonService personService = this.registry.getPersonService();
                userAuth = new User(userName, authenticationService.getCurrentTicket(),
                        personService.getPerson(userName));

                NodeService nodeService = this.registry.getNodeService();
                NodeRef homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName),
                        ContentModel.PROP_HOMEFOLDER);
                if (!nodeService.exists(homeSpaceRef)) {
                    throw new InvalidNodeRefException(homeSpaceRef);
                }
                userAuth.setHomeSpaceId(homeSpaceRef.getId());

                httpSession.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, userAuth);
                httpSession.setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, true);

                tx.commit();
            } catch (Throwable e) {
                tx.rollback();
                throw new ServletException(e);
            }
        } catch (SystemException e) {
            throw new ServletException(e);
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("User " + userName + " already authenticated");
        }

        AuthenticationStatus status = AuthenticationHelper.authenticate(httpSession.getServletContext(),
                httpRequest, httpResponse, false);
        if (status != AuthenticationStatus.Success) {
            throw new ServletException("User not correctly autheticated");
        }
    }

    chain.doFilter(request, response);
}

From source file:net.naijatek.myalumni.framework.struts.MyAlumniDispatchAction.java

/**
 * Remove a session object based on the request and the attribute label.
 * //from  w ww  .  j a  va2 s. co  m
 * @param req
 *            HttpServletRequest
 * @param attrName
 *            String
 */
protected void removeSessionObject(HttpServletRequest req, String attrName) {
    HttpSession session = req.getSession(false);
    if (session != null) {
        session.removeAttribute(attrName);
    }
}

From source file:com.adito.core.CoreUtil.java

/**
 * Remove a page intercept listener from the provided session. This listener
 * will no longer be messaged upon every required
 * //from   www. j a  v a 2s.co m
 * @param servletSession session to remove listener from
 * @param listener listener to remove
 */
@SuppressWarnings("unchecked")
public static void removePageInterceptListener(HttpSession servletSession, PageInterceptListener listener) {
    synchronized (servletSession) {
        List<PageInterceptListener> pagetInterceptListeners = (List<PageInterceptListener>) servletSession
                .getAttribute(Constants.PAGE_INTERCEPT_LISTENERS);
        if (pagetInterceptListeners != null) {
            pagetInterceptListeners.remove(listener);
            if (pagetInterceptListeners.size() == 0) {
                servletSession.removeAttribute(Constants.PAGE_INTERCEPT_LISTENERS);
            }
            PageInterceptListener pil = (PageInterceptListener) servletSession
                    .getAttribute(Constants.PAGE_INTERCEPTED);
            if (pil == listener) {
                servletSession.removeAttribute(Constants.PAGE_INTERCEPTED);
            }
        }
    }
}

From source file:mitm.djigzo.web.services.security.ClearSavedRequestAuthenticationProcessingFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request) throws AuthenticationException {
    Authentication authentication = super.attemptAuthentication(request);

    HttpSession session = request.getSession(false);

    if (session != null) {
        SavedRequest savedRequest = (SavedRequest) session
                .getAttribute(AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY);

        if (savedRequest != null) {
            String[] savedEmails = savedRequest.getParameterValues(usernameRequestParameter);

            if (!ArrayUtils.isEmpty(savedEmails)) {
                String email = EmailAddressUtils.canonicalize(obtainUsername(request));

                for (String savedEmail : savedEmails) {
                    savedEmail = EmailAddressUtils.canonicalize(savedEmail);

                    if (!StringUtils.equals(email, savedEmail)) {
                        session.removeAttribute(AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY);

                        break;
                    }/*from  w  ww  . j av a 2s  .  c  o  m*/
                }
            }
        }
    }

    return authentication;
}

From source file:nl.b3p.commons.security.aselect.ASelectAuthorizationFilter.java

/**
 * Deze methode retourneert <code>true</code> indien de gebruiker is geautoriseerd. Indien
 * de gebruiker voor het eerst bij de webapplicatie komt wordt deze doorgestuurd
 * naar de A-Select server met response.sendRedirect() en wordt <code>false</code>
 * geretourneerd, wat betekent dat verder niks met de response moet worden gedaan/niet
 * chain.doFilter() moet worden aangeroepen. Er kan ook false worden teruggegeven indien
 * met response.sendRedirect() is geredirect naar de originele app URL indien deze was
 * omgeschreven bij de optie "avoid_url_params_in_redirect".
 * <p>//  w  w  w .  j  a  va  2s  .  com
 * Indien een fout optreedt wordt een exception gethrowed en moet geen toegang
 * worden verleend tot de applicatie.
 */
private boolean checkAuthorization(HttpServletRequest request, HttpServletResponse response)
        throws ASelectAuthorizationException, ServletException, IOException {

    if (api == ASELECT_API_WEBSERVERFILTER) {
        return verifyWebFilterCookies(request);
    }

    /* Deze twee request parameters worden door de A-Select server meegestuurd
     * nadat de gebruiker zich heeft geauthoriseerd bij de A-Select server.
     */
    String asRid = request.getParameter("rid");
    String asCredentials = request.getParameter("aselect_credentials");

    if ((asRid != null) && (asCredentials != null)) {
        if (log.isInfoEnabled()) {
            log.info("verifying credentials");
        }
        if (!verifyCredentials(request, asRid, asCredentials)) {
            /* FIXME redirect naar foutpagina */
            throw new ServletException("Credentials could not be verified");
        } else {
            /* credentials zijn ok, geef toegang tot app */

            if (avoidURLParamsInRedirect && "true".equals(request.getParameter(ASELECT_REDIRECT_BACK))) {
                HttpSession sess = request.getSession();
                String originalURL = (String) sess.getAttribute(ASELECT_ORIGINAL_APP_URL);
                if (originalURL == null) {
                    throw new ServletException("Invalid state: no original app URL in session to redirect to");
                }
                sess.removeAttribute(ASELECT_ORIGINAL_APP_URL);
                if (log.isInfoEnabled()) {
                    log.info("redirecting to original app URL: " + originalURL);
                }
                /* bijkomstige handigheid is dat de rid en aselect_credentials niet
                 * in de originalURL voorkomen en deze dus ook niet in de adresbalk
                 * van de browser blijven staan
                 */
                response.sendRedirect(originalURL);
                return false;
            }

            return true;
        }
    }

    ASelectTicket ticket = ASelectTicket.getFromSession(request.getSession());

    if (ticket != null) {

        /* deze methode throws een exception indien het ticket niet geldig
         * is of als het niet kon worden gecontroleerd
         */
        try {
            ticket.verify();
        } catch (IOException e) {
            throw new ServletException("Error verifying ticket", e);
        }

        org.apache.log4j.MDC.put("ASelectUid", ticket.getUid());
        org.apache.log4j.MDC.put("ASelectTicket", ticket.getTicketId());

        return true;
    }

    if (log.isInfoEnabled()) {
        log.info("redirecting to A-Select server");
    }
    redirectToASelect(request, response);
    return false;
}

From source file:com.oak_yoga_studio.controller.CustomerController.java

@RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public String add(@Valid Customer customer, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) {
    String view = "redirect:/";
    //System.out.println("customerController Add");

    if (!result.hasErrors()) {
        try {//from w w w .j  a v a2s.  c o m
            customer.setProfilePicture(file.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
        }
        customerService.addCustomer(customer);
        session.removeAttribute("credential");
        flashAttr.addFlashAttribute("successfulSignup",
                "Customer signed up succesfully. please  log in to proceed");

    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage());
        }
        view = "addCustomer";
    }
    return view;
}

From source file:com.oak_yoga_studio.controller.AdminController.java

@RequestMapping(value = "/addFaculty", method = RequestMethod.POST)
public String addFaculty(Faculty faculty, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) {
    String view = "redirect:/viewFaculties";

    if (!result.hasErrors()) {
        try {//from   w ww  .  j ava2  s  .  c  o m
            faculty.setProfilePicture(file.getBytes());
        } catch (IOException ex) {
            //Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
        }
        faculty.getCredential().setActive(false);
        faculty.setActive(false);
        facultyServcie.addFaculty(faculty);
        session.removeAttribute("credential");
        flashAttr.addFlashAttribute("successful registered",
                "Faculty signed up succesfully. please  log in to proceed"); //           Customer c=(Customer) session.getAttribute("loggedCustomer");

    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage());
        }
        view = "addFaculty";
    }
    return view;
}

From source file:mitm.djigzo.web.services.security.ClearSavedRequestAuthenticationProcessingFilter.java

@Override
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        Authentication authResult) throws IOException {
    super.onSuccessfulAuthentication(request, response, authResult);

    HttpSession session = request.getSession(false);

    /*//w  ww  . j  a  v  a 2 s . com
     * After successful authentication we will remove the saved request. This is required to support
     * the change of the Locale from the login page. The locale is stored in a (Tapestry) cookie.  If 
     * the saved request is not removed, the request after authentication will use the "old" Locale 
     * cookie and therefore the first request will use the old Locale instead of the new. I have not 
     * yet found a way to replace the locale cookie in the saved request with the new locale cookie.
     * 
     * Note: not sure what the impact might be of removing the saved request for post requests or 
     * for requests that require additional headers. 
     */
    if (session != null) {
        session.removeAttribute(AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY);
    }
}

From source file:org.openmrs.module.personalhr.web.controller.OptionsFormController.java

/**
 * Called prior to form display. Allows for data to be put in the request to be used in the view
 * /*from   w w  w.  j  a va2  s  .c  om*/
 * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
 */
protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {

    HttpSession httpSession = request.getSession();

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

    if (Context.isAuthenticated()) {

        LocationService ls = Context.getLocationService();

        // set location options
        map.put("locations", ls.getAllLocations());

        // set language/locale options
        map.put("languages", Context.getAdministrationService().getPresentationLocales());

        String resetPassword = (String) httpSession.getAttribute("resetPassword");
        if (resetPassword == null)
            resetPassword = "";
        else
            httpSession.removeAttribute("resetPassword");
        map.put("resetPassword", resetPassword);

    }

    return map;
}