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:org.javarebel.chart.ChartComponentListener.java

@Override
public void beforePhase(PhaseEvent arg0) {
    FacesContext context = arg0.getFacesContext();
    ExternalContext eCtx = context.getExternalContext();

    HttpServletRequest req = (HttpServletRequest) eCtx.getRequest();
    String data_KEY = req.getParameter("data_KEY");
    logger.info("Chart Data Key is " + data_KEY);

    HttpSession session = req.getSession();
    if (data_KEY != null) {
        Object chartData = session.getAttribute(data_KEY);

        if (chartData != null) {

            ChartData data = ChartData.class.cast(chartData);
            logger.info("Chart Type received is " + data.getType());
            IChartGenerator chartGen = ChartGeneratorFactory.getChartGenerator(data.getType());
            logger.info("ChartGenerator in use -> " + chartGen.getClass().getName());
            JFreeChart chart = chartGen.generateChart(data);

            BufferedImage img = chart.createBufferedImage(Integer.valueOf(data.getWidth()),
                    Integer.valueOf(data.getHeight()));
            try {
                HttpServletResponse response = (HttpServletResponse) eCtx.getResponse();
                response.setContentType("image/png");
                response.setHeader("Cache-Control", "no-store");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0L);

                ServletOutputStream output = response.getOutputStream();
                ImageIO.write(img, "png", output);

                session.removeAttribute(data_KEY);

                context.responseComplete();
            } catch (Exception e) {
                logger.log(Level.SEVERE, e.getMessage(), e);
                throw new IllegalStateException(e);
            }//from  ww  w .j a v a  2s.  com
        }
    }
}

From source file:com.anite.ocelot.MultipleRequestFilter.java

/**
 * tidys up the session/*w w  w.  ja v a 2 s  .  c  o  m*/
 * 
 * @param httpSession
 */
private void tidySession(HttpSession httpSession) {
    /*
     * final sync'd tidy up on things we hold in the session
     *  
     */
    synchronized (httpSession) {
        List list = (List) httpSession.getAttribute(SESSION_REQUESTSTACK);
        if (log.isInfoEnabled()) {
            log.info("Removing self from list");
        }
        /*
         * at this stage the current request should ALWAYS be at position
         * ZERO in the stack
         */
        list.remove(0);
        if (list.size() == 0) {
            /*
             * no more items in the stack, so remove everything we may have
             * left in here
             * 
             * (the stack and the page that was built on the first request)
             *  
             */
            if (log.isInfoEnabled()) {
                log.info("List now empty");
            }
            httpSession.removeAttribute(SESSION_REQUESTSTACK);
            httpSession.removeAttribute(SESSION_FIRSTRESPONSE);
        }
    }
}

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

/** Perform form authentication.
 * Called from SecurityHandler./* w ww . j ava  2  s.  co  m*/
 * @return UserPrincipal if authenticated else null.
 */
public Principal authenticate(UserRealm realm, String pathInContext, HttpRequest httpRequest,
        HttpResponse httpResponse) throws IOException {
    HttpServletRequest request = (ServletHttpRequest) httpRequest.getWrapper();
    HttpServletResponse response = httpResponse == null ? null
            : (HttpServletResponse) httpResponse.getWrapper();

    // Handle paths
    String uri = pathInContext;

    // Setup session 
    HttpSession session = request.getSession(response != null);
    if (session == null)
        return null;

    // Handle a request for authentication.
    if (uri.substring(uri.lastIndexOf("/") + 1).startsWith(__J_SECURITY_CHECK)) {
        // Check the session object for login info.
        FormCredential form_cred = new FormCredential();
        form_cred.authenticate(realm, request.getParameter(__J_USERNAME), request.getParameter(__J_PASSWORD),
                httpRequest);

        String nuri = (String) session.getAttribute(__J_URI);
        if (nuri == null || nuri.length() == 0) {
            nuri = request.getContextPath();
            if (nuri.length() == 0)
                nuri = "/";
        }

        if (form_cred._userPrincipal != null) {
            // Authenticated OK
            if (log.isDebugEnabled())
                log.debug("Form authentication OK for " + form_cred._jUserName);
            session.removeAttribute(__J_URI); // Remove popped return URI.
            httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
            httpRequest.setAuthUser(form_cred._jUserName);
            httpRequest.setUserPrincipal(form_cred._userPrincipal);
            session.setAttribute(__J_AUTHENTICATED, form_cred);

            // Sign-on to SSO mechanism
            if (realm instanceof SSORealm) {
                ((SSORealm) realm).setSingleSignOn(httpRequest, httpResponse, form_cred._userPrincipal,
                        new Password(form_cred._jPassword));
            }

            // Redirect to original request
            if (response != null) {
                response.setContentLength(0);
                response.sendRedirect(response.encodeRedirectURL(nuri));
            }
        } else if (response != null) {
            if (log.isDebugEnabled())
                log.debug("Form authentication FAILED for " + form_cred._jUserName);
            if (_formErrorPage != null) {
                response.setContentLength(0);
                response.sendRedirect(
                        response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formErrorPage)));
            } else {
                response.sendError(HttpResponse.__403_Forbidden);
            }
        }

        // Security check is always false, only true after final redirection.
        return null;
    }

    // Check if the session is already authenticated.
    FormCredential form_cred = (FormCredential) session.getAttribute(__J_AUTHENTICATED);

    if (form_cred != null) {
        // We have a form credential. Has it been distributed?
        if (form_cred._userPrincipal == null) {
            // This form_cred appears to have been distributed.  Need to reauth
            form_cred.authenticate(realm, httpRequest);

            // Sign-on to SSO mechanism
            if (form_cred._userPrincipal != null && realm instanceof SSORealm) {
                ((SSORealm) realm).setSingleSignOn(httpRequest, httpResponse, form_cred._userPrincipal,
                        new Password(form_cred._jPassword));
            }
        } else if (!realm.reauthenticate(form_cred._userPrincipal))
            // Else check that it is still authenticated.
            form_cred._userPrincipal = null;

        // If this credential is still authenticated
        if (form_cred._userPrincipal != null) {
            if (log.isDebugEnabled())
                log.debug("FORM Authenticated for " + form_cred._userPrincipal.getName());
            httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
            httpRequest.setAuthUser(form_cred._userPrincipal.getName());
            httpRequest.setUserPrincipal(form_cred._userPrincipal);
            return form_cred._userPrincipal;
        } else
            session.setAttribute(__J_AUTHENTICATED, null);
    } else if (realm instanceof SSORealm) {
        // Try a single sign on.
        Credential cred = ((SSORealm) realm).getSingleSignOn(httpRequest, httpResponse);

        if (httpRequest.hasUserPrincipal()) {
            form_cred = new FormCredential();
            form_cred._userPrincipal = request.getUserPrincipal();
            form_cred._jUserName = form_cred._userPrincipal.getName();
            if (cred != null)
                form_cred._jPassword = cred.toString();
            if (log.isDebugEnabled())
                log.debug("SSO for " + form_cred._userPrincipal);

            httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
            session.setAttribute(__J_AUTHENTICATED, form_cred);
            return form_cred._userPrincipal;
        }
    }

    // Don't authenticate authform or errorpage
    if (isLoginOrErrorPage(pathInContext))
        return SecurityConstraint.__NOBODY;

    // redirect to login page
    if (response != null) {
        if (httpRequest.getQuery() != null)
            uri += "?" + httpRequest.getQuery();
        session.setAttribute(__J_URI, request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + URI.addPaths(request.getContextPath(), uri));
        response.setContentLength(0);
        response.sendRedirect(
                response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formLoginPage)));
    }

    return null;
}

From source file:elw.web.ControllerElw.java

protected HashMap<String, Object> auth(final HttpServletRequest req, final HttpServletResponse resp,
        final boolean page, final boolean verified) throws IOException {
    final HttpSession session = req.getSession(true);
    final Auth auth = (Auth) session.getAttribute(SESSION_KEY);

    if (auth == null) {
        return noAuth(req, resp, page, "Auth required");
    }/*from www . j  a v a 2 s  .  c o m*/

    if (!W.resolveRemoteAddress(req).equals(auth.getSourceAddr())) {
        return noAuth(req, resp, page, "Source address changed");
    }

    auth.renew(core.getQueries());

    if (auth.isEmpty()) {
        return noAuth(req, resp, page, "Non-empty Auth required");
    }

    final String extraValidationMessage = extraAuthValidations(auth);

    if (!Strings.isNullOrEmpty(extraValidationMessage)) {
        return noAuth(req, resp, page, extraValidationMessage);
    }

    if (verified && !auth.isVerified()) {
        return noAuth(req, resp, page, "Verified Auth required");
    }

    session.removeAttribute(ControllerAuth.SESSION_SUCCESS_REDIRECT);

    return prepareDefaultModel(req, auth, null);
}

From source file:controllers.controller.java

private void clearNCloseSession(HttpSession session, HttpServletRequest request, HttpServletResponse response,
        QUID quid, PrintWriter out) throws Exception {
    String param = "";
    Enumeration enu = session.getAttributeNames();
    while (enu.hasMoreElements()) {
        param = enu.nextElement().toString();
        session.setAttribute(param, null);
        session.removeAttribute(param);
    }/*from ww w  . j a  v  a 2s.co m*/
    session.invalidate();
    session = null;
}

From source file:com.jaeksoft.searchlib.renderer.Renderer.java

public void configureAuthRequest(AbstractSearchRequest searchRequest, HttpServletRequest servletRequest)
        throws ParseException, IOException, SearchLibException {
    AuthPluginInterface authPlugin = getNewAuthPluginInterface();
    if (authPlugin == null)
        return;/*from w w  w  .  j  a  v a  2  s . co m*/
    HttpSession session = servletRequest.getSession();
    if (servletRequest.getParameter("logout") != null) {
        session.removeAttribute(RENDERER_SESSION_USER);
        throw new NoUserException("Logout");
    }
    AuthPluginInterface.User user = (User) session.getAttribute(RENDERER_SESSION_USER);
    if (user == null)
        user = authPlugin.getUser(this, servletRequest);
    if (user == null)
        throw new NoUserException("No user found");
    session.setAttribute(RENDERER_SESSION_USER, user);

    StringBuilder sbPositiveFilter = new StringBuilder();
    if (authUserAllowField != null && authUserAllowField.length() > 0) {
        if (sbPositiveFilter.length() > 0)
            sbPositiveFilter.append(" OR ");
        sbPositiveFilter.append(authUserAllowField);
        sbPositiveFilter.append(':');
        AuthPluginInterface.User.usernamesToFilterQuery(user, sbPositiveFilter);
    }
    if (authGroupAllowField != null && authGroupAllowField.length() > 0
            && !CollectionUtils.isEmpty(user.groups)) {
        if (sbPositiveFilter.length() > 0)
            sbPositiveFilter.append(" OR ");
        sbPositiveFilter.append(authGroupAllowField);
        sbPositiveFilter.append(":(");
        boolean bOr = false;
        for (String group : user.groups) {
            if (bOr)
                sbPositiveFilter.append(" OR ");
            else
                bOr = true;
            sbPositiveFilter.append('"');
            sbPositiveFilter.append(QueryUtils.escapeQuery(group));
            sbPositiveFilter.append('"');
        }
        sbPositiveFilter.append(')');
    }

    if (sbPositiveFilter.length() > 0)
        searchRequest.addFilter(sbPositiveFilter.toString(), false);

    if (authUserDenyField != null && authUserDenyField.length() > 0) {
        StringBuilder sbNegativeFilter = new StringBuilder();
        sbNegativeFilter.append(authUserDenyField);
        sbNegativeFilter.append(':');
        AuthPluginInterface.User.usernamesToFilterQuery(user, sbNegativeFilter);
        searchRequest.addFilter(sbNegativeFilter.toString(), true);
    }

    if (authGroupDenyField != null && authGroupDenyField.length() > 0
            && !CollectionUtils.isEmpty(user.groups)) {
        StringBuilder sbNegativeFilter = new StringBuilder();
        sbNegativeFilter.append(authGroupDenyField);
        sbNegativeFilter.append(":(");
        boolean bOr = false;
        for (String group : user.groups) {
            if (bOr)
                sbNegativeFilter.append(" OR ");
            else
                bOr = true;
            sbNegativeFilter.append('"');
            sbNegativeFilter.append(QueryUtils.escapeQuery(group));
            sbNegativeFilter.append('"');
        }
        sbNegativeFilter.append(')');
        searchRequest.addFilter(sbNegativeFilter.toString(), true);
    }

}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.actions.SaveSessionConfigAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.//www.  ja  va2  s.c o m
 *
 * @param mapping The ActionMapping used to select this instance
 * @param actionForm The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes and parameters we will need
    HttpSession session = request.getSession();

    DynaValidatorForm sessionForm = (DynaValidatorForm) form;

    // Validate the transactional control token
    ActionMessages errors = new ActionMessages();

    isTokenValid(request, log.isDebugEnabled());
    resetToken(request);

    if (!isExperimenter(session))
        return (mapping.findForward("login_fail"));

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        saveToken(request);
        return (mapping.getInputForward());
    }

    SessionBean sessionBean = createSessionBean(session, sessionForm);
    if (sessionBean == null) {
        ActionMessages aerrors = new ActionMessages();
        aerrors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.session.file"));
        saveErrors(request, aerrors);

        // Remove the obsolete form bean
        if (mapping.getAttribute() != null) {
            if ("request".equals(mapping.getScope()))
                request.removeAttribute(mapping.getAttribute());
            else
                session.removeAttribute(mapping.getAttribute());
        }

        return (mapping.findForward("failure"));
    }

    session.setAttribute("sessionBean", sessionBean);

    // Remove the obsolete form bean
    if (mapping.getAttribute() != null) {
        if ("request".equals(mapping.getScope()))
            request.removeAttribute(mapping.getAttribute());
        else
            session.removeAttribute(mapping.getAttribute());
    }

    return (mapping.findForward("success"));
}

From source file:org.openmrs.web.controller.user.ChangePasswordFormController.java

/**
 * Method to save changes of the new password for a user. The password will be validated against
 * the current rules and will display error messages in case the password is not strong enough.
 * /*  w  ww .  j  a  va  2s .c o m*/
 * @should display an error message when the password and confirm password entries are different
 * @should not display error message if password and confirm password are the same
 * @should display error message when the password is empty
 * @should display error message if password is weak
 * @should display error message when question is empty and answer is not empty
 * @should display error message when the answer and the confirm answer entered are not the same
 * @should display error message when the answer is empty and question is not empty
 * @should navigate to the home page if the authentication is successful
 * @should set the user property forcePassword to false after successful password change
 * @should not set the user property forcePassword to false after unsuccessful password change
 * @should remain on the changePasswordForm page if there are errors
 * @should set the secret question and answer of the user
 * @param password to be applied
 * @param confirmPassword confirmation for the password to be applied
 * @param question in case of a forgotten password
 * @param answer answer for the question
 * @param confirmAnswer confirmation of the answer for the question
 * @param errors while processing the form
 */
@RequestMapping(method = RequestMethod.POST)
public String handleSubmission(HttpSession httpSession,
        @RequestParam(required = true, value = "oldPassword") String oldPassword,
        @RequestParam(required = true, value = "password") String password,
        @RequestParam(required = true, value = "confirmPassword") String confirmPassword,
        @RequestParam(required = false, value = "question") String question,
        @RequestParam(required = false, value = "answer") String answer,
        @RequestParam(required = false, value = "confirmAnswer") String confirmAnswer,
        @ModelAttribute("user") User user, BindingResult errors) {

    NewPassword newPassword = new NewPassword(password, confirmPassword);
    NewQuestionAnswer newQuestionAnswer = new NewQuestionAnswer(question, answer, confirmAnswer);
    new NewPasswordValidator(user).validate(newPassword, errors);
    new NewQuestionAnswerValidator().validate(newQuestionAnswer, errors);

    if (errors.hasErrors()) {
        return showForm(httpSession);
    }

    changeUserPasswordAndQuestion(user, oldPassword, newPassword, newQuestionAnswer);
    httpSession.removeAttribute(WebConstants.OPENMRS_MSG_ATTR);
    return "redirect:/index.htm";

}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.actions.SaveClientLoginAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.// w  ww . ja  va  2 s .  co m
 *
 * @param mapping The ActionMapping used to select this instance
 * @param actionForm The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    HttpSession session = request.getSession();

    if ("request".equals(mapping.getScope())) {
        request.setAttribute(mapping.getAttribute(), form);
    } else {
        session.setAttribute(mapping.getAttribute(), form);
    }

    DynaValidatorForm loginForm = (DynaValidatorForm) form;

    String email = (String) loginForm.get("email");
    String password = (String) loginForm.get("password");

    log.info("Logging in client: " + email);
    int clientId = ControlServ.dbw.getClientIdByEmailAndPassword(email, password, JMConstants.USER_ROLE);
    log.info("Client logged in: " + email + " : " + clientId);
    if (clientId < 0) {
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.client.notRegistered"));
        saveErrors(request, errors);
        return (mapping.findForward("failure"));
    }

    loginClient(session, clientId);

    Boolean joiningExp = (Boolean) session.getAttribute("joiningExp");
    if (joiningExp == null || joiningExp == Boolean.FALSE) {
        ActionMessages msg = new ActionMessages();
        msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("client.login.success"));
        saveMessages(request, msg);

        session.removeAttribute("joiningExp");
        return (mapping.findForward("success"));
    } else { //directly join an experiment if the client was sent to login from the EditJoinExpAction
        session.removeAttribute("joiningExp");
        return (mapping.findForward("join"));
    }
}