Example usage for javax.servlet.http HttpSession invalidate

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

Introduction

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

Prototype

public void invalidate();

Source Link

Document

Invalidates this session then unbinds any objects bound to it.

Usage

From source file:org.qualipso.factory.ui.core.login.server.LoginServletImpl.java

/**
 * Try to log in the factory using the given username and password.
 * /*from  w ww . j  av a 2  s  .c  o  m*/
 * @see org.qualipso.factory.ui.core.login.client.LoginServlet#login(java.lang.String, java.lang.String)
 * 
 * @param username
 *            the username
 * @param password
 *            the password
 * @return true if the user information allow him to log in, false otherwise
 */
public Boolean login(String username, String password) {
    logger.info("User " + username + " trying to log on the factory...");

    // clean old login session if necessary
    HttpSession session = getThreadLocalRequest().getSession(false);
    if (session != null) {
        session.removeAttribute(USERNAME_SESSION_ATTRIBUTE);
        session.removeAttribute(PASSWORD_SESSION_ATTRIBUTE);
        session.invalidate();
    }

    // get the naming context for lookup factory services
    final Context namingContext;
    try {
        final Properties properties = new Properties();
        properties.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
        properties.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
        properties.put("java.naming.provider.url", "localhost:1099");
        namingContext = new InitialContext(properties);
    } catch (NamingException ne) {
        logger.error("Cannot manage to access Factory through naming. Caused by: ", ne);
        return false;
    }

    // check the application context to see if the bootstrap has already been done
    // thanks to Jerome for this piece of code
    String bootstrapped = (String) getThreadLocalRequest().getSession().getServletContext()
            .getAttribute(BOOTSTRAPPED_FLAG);
    if (bootstrapped == null) {
        logger.info("No bootstrap flag found in the application context.");
        logger.info("Bootstrap of the factory is needed, in progress....");
        try {
            BootstrapService bootstrap = (BootstrapService) namingContext
                    .lookup(FactoryNamingConvention.getJNDINameForService(BootstrapService.SERVICE_NAME));
            bootstrap.bootstrap();
            getThreadLocalRequest().getSession().getServletContext().setAttribute(BOOTSTRAPPED_FLAG,
                    BOOTSTRAPPED_FLAG);
            logger.info("Bootstrap of the factory done.");
        } catch (NamingException ne) {
            logger.error("Cannot manage to access Factory bootstrap service. Caused by: ", ne);
            return false;
        } catch (BootstrapServiceException bse) {
            logger.error("Cannot manage to call Factory bootstrap service. Caused by: ", bse);
            return false;
        }
    } else {
        logger.info("Bootstrap flag found in the application context, no need to bootstrap.");
    }

    // get the membership service
    final MembershipService membership;
    try {
        membership = (MembershipService) namingContext
                .lookup(FactoryNamingConvention.getJNDINameForService(MembershipService.SERVICE_NAME));
    } catch (NamingException ne) {
        logger.error("Cannot manage to access Factory membership service. Caused by: ", ne);
        return false;
    }

    // create a login context
    LoginContext loginContext;
    try {
        loginContext = new LoginContext("qualipso", new UsernamePasswordHandler(username, password));
        loginContext.login();
    } catch (LoginException le) {
        logger.error("Cannot manage to use the login context. Caused by: ", le);
        return false;
    }

    // test if the login context is valid by trying to call the membership service
    final String profilePath;
    try {
        profilePath = membership.getProfilePathForConnectedIdentifier();
        logger.info("Profile path for user " + username + ": " + profilePath);
    } catch (EJBAccessException no) {
        // login is invalid
        logger.info("Login failed for user " + username);
        return false;
    }

    // if we're here, the login is valid. Put it in the session.
    session = getThreadLocalRequest().getSession();
    session.setAttribute(USERNAME_SESSION_ATTRIBUTE, username);
    session.setAttribute(PASSWORD_SESSION_ATTRIBUTE, password);
    logger.info("User " + username + " logged in, with profile path " + profilePath);

    // log out
    try {
        loginContext.logout();
    } catch (LoginException le) {
        // just log, don't do anything else
        logger.error("Problem logging out after testing correct login. Caused by: ", le);
    }

    return true;
}

From source file:eu.eidas.node.service.IdPResponseServlet.java

/**
 * Executes the method {@link eu.eidas.node.auth.service.AUSERVICE#processIdpResponse} (of the ProxyService) and
 * then sets the internal variables used by the redirection JSP or the consent-value jsp, accordingly to {@link
 * EidasParameterKeys#NO_CONSENT_VALUE} or {@link EidasParameterKeys#CONSENT_VALUE} respectively.
 *
 * @param request//from w  w  w.j av a 2s. c o  m
 * @param response
 * @return {@link EidasParameterKeys#CONSENT_VALUE} if the consent-value form is to be displayed, {@link
 * EidasParameterKeys#NO_CONSENT_VALUE} otherwise.
 * @see EidasParameterKeys#NO_CONSENT_VALUE
 * @see EidasParameterKeys#CONSENT_VALUE
 */

private void execute(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {

        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher(handleExecute(request, response));
        dispatcher.forward(request, response);
        HttpSession session = request.getSession(false);
        if (null != session
                && session.getAttribute(EidasParameterKeys.EIDAS_CONNECTOR_SESSION.toString()) == null) {
            session.invalidate();
        }
    } catch (ServletException e) {
        getLogger().info("ERROR : ServletException {}", e.getMessage());
        getLogger().debug("ERROR : ServletException {}", e);
        throw e;
    } catch (IOException e) {
        getLogger().info("IOException {}", e.getMessage());
        getLogger().debug("IOException {}", e);
        throw e;
    }

}

From source file:pt.ist.bennu.core.presentationTier.servlets.filters.FunctionalityFilter.java

private void redirectByTampering(HttpServletRequest request, final HttpServletResponse response)
        throws IOException {
    final HttpSession httpSession = request.getSession(false);
    if (httpSession != null) {
        httpSession.invalidate();
    }/*from  w  ww.j a v a  2  s .  c  om*/
    // TODO not working!
    response.sendRedirect(FenixWebFramework.getConfig().getTamperingRedirect());
}

From source file:com.liferay.portlet.admin.action.KillSessionAction.java

private void _killSession(ActionRequest req, ActionResponse res) throws Exception {

    String sessionId = ParamUtil.getString(req, "session_id");

    HttpSession userSession = PortalSessionContext.get(sessionId);

    if (userSession != null) {
        try {/*from   w  ww .j av  a  2  s. c o m*/
            String companyId = PortalUtil.getCompanyId(req);
            String sesCompanyId = (String) userSession.getAttribute(WebKeys.COMPANY_ID);

            if ((!req.getPortletSession().getId().equals(sessionId)) && (companyId.equals(sesCompanyId))) {

                userSession.invalidate();
            }
        } catch (Exception e) {
            _log.error(StringUtil.stackTrace(e));
        }
    }

    // Send redirect

    res.sendRedirect(ParamUtil.getString(req, "redirect"));
}

From source file:com.impetus.kundera.datakeeper.beans.LoginBean.java

public String deleteAccount() {
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    DataKeeperService service = DataKeeperUtils.getService();
    Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);

    service.removeEmployee(employee);//from  ww  w  . jav  a  2s.c o m

    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Account successfully deleted"));
    session.invalidate();
    return "Account successfully deleted";
}

From source file:org.apache.geode.modules.session.TestSessionsBase.java

@Test
public void testCommitSessionValveInvalidSession() throws Exception {
    Callback c = new Callback() {
        @Override/*from   www . j a  v a 2  s . c o  m*/
        public void call(HttpServletRequest request, HttpServletResponse response) throws IOException {
            HttpSession session = request.getSession();
            session.invalidate();
            response.getWriter().write("done");
        }
    };
    servlet.getServletContext().setAttribute("callback", c);

    WebConversation wc = new WebConversation();
    WebRequest req = new GetMethodWebRequest(String.format("http://localhost:%d/test", port));

    // Execute the callback
    req.setParameter("cmd", QueryCommand.CALLBACK.name());
    req.setParameter("param", "callback");
    WebResponse response = wc.getResponse(req);

    assertEquals("done", response.getText());
}

From source file:com.poscoict.license.web.controller.BoardController.java

@RequestMapping(value = { "logout" }, method = { RequestMethod.POST, RequestMethod.GET })
public String logout(HttpSession session) {
    System.out.println("logout_____________________________________________index");
    session.invalidate();
    return "redirect:/index";
}

From source file:pl.umk.mat.zawodyweb.www.SessionBean.java

@HttpAction(name = "logout", pattern = "logout")
public String logOut() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
    session.invalidate();

    currentUser = new Users();
    loggedIn = false;//from  w w w  . ja  v  a  2  s.co m

    return "start";
}

From source file:org.structr.rest.auth.RestAuthenticator.java

@Override
public void doLogout(final HttpServletRequest request) {

    try {//  ww  w . java  2s.  c o m
        final Principal user = getUser(request, false);
        if (user != null) {

            AuthHelper.doLogout(request, user);
        }

        final HttpSession session = request.getSession(false);
        if (session != null) {

            session.invalidate();
        }

    } catch (IllegalStateException | FrameworkException ex) {

        logger.log(Level.WARNING, "Error while logging out user", ex);
    }
}

From source file:net.riezebos.thoth.servlets.ThothServlet.java

public void setCurrentUser(HttpServletRequest request, User user) {
    // Invalidate any current session before we start a fresh one with a logged in user
    HttpSession session = request.getSession(false);
    if (session != null)
        session.invalidate();
    session = request.getSession(true);//from   w  ww  .j  a  va  2  s .  c  om
    session.setAttribute(SESSION_USER_KEY, user);
}