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:com.intelligentz.appointmentz.controllers.authenticate.java

private void authenticate(String userName, String password, HttpServletRequest req, HttpServletResponse res) {
    boolean status = false;
    HttpSession session = req.getSession();
    try {/*from w  ww. j  ava 2s .  c  o  m*/
        connection = DBConnection.getDBConnection().getConnection();
        String SQL1 = "select * from hospital WHERE hospital_id = ? and password = ?";

        preparedStatement = connection.prepareStatement(SQL1);
        preparedStatement.setString(1, userName);
        preparedStatement.setString(2, password);
        resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            String db_username = resultSet.getString("hospital_id");
            String db_hospital_name = resultSet.getString("hospital_name");

            session.setAttribute("hospital_id", db_username);
            session.setAttribute("hospital_name", db_hospital_name);

            res.sendRedirect("./home");
        } else {

            session.invalidate();
            res.sendRedirect("./index.jsp?auth=Authentication Failed");

        }

    } catch (SQLException | IOException | PropertyVetoException ex) {
        LOGGER.log(Level.SEVERE, ex.toString(), ex);
    } finally {
        try {
            DbUtils.closeQuietly(resultSet);
            DbUtils.closeQuietly(preparedStatement);
            DbUtils.close(connection);
        } catch (SQLException ex) {
            Logger.getLogger(authenticate.class.getName()).log(Level.SEVERE, ex.toString(), ex);
        }
    }
}

From source file:es.sm2.openppm.front.servlets.AbstractGenericServlet.java

/**
 * Prepare for choose or select role//from   w  w w. j ava  2  s .  c om
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
protected void setRolSession(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        ContactLogic contactLogic = new ContactLogic();

        Contact contact = contactLogic.findByUser(request.getRemoteUser());

        if (contact != null) {

            if (request.getSession().getAttribute("plugins") == null) {

                PluginLogic pluginLogic = new PluginLogic();
                request.getSession().setAttribute("plugins", pluginLogic.getPlugins(contact));
            }

            EmployeeLogic employeeLogic = new EmployeeLogic();
            List<Employee> employees = employeeLogic.consEmployeesByUser(contact);

            if (employees.isEmpty()) { // Any user match
                request.setAttribute("error",
                        getResourceBundle(request).getString("msg.error.without_permission"));
                request.setAttribute("notLogin", true);

                HttpSession session = request.getSession();
                if (session != null) {
                    session.invalidate();
                }

                setForward(true);
                forward("/login.jsp", request, response);
            } else if (employees.size() == 1) { // One user match
                Employee user = employeeLogic.consEmployee(employees.get(0).getIdEmployee());
                request.getSession().setAttribute("user", user);
                request.getSession().setAttribute("rolPrincipal", user.getResourceprofiles().getIdProfile());
            } else if (employees.size() > 1) { // More than one user found
                PerformingOrgLogic performingOrgLogic = new PerformingOrgLogic();

                List<Performingorg> orgs = performingOrgLogic.consByContact(contact);

                Employee user = new Employee();
                user.setContact(contact);
                request.getSession().setAttribute("user", user);

                request.setAttribute("employees", employees);
                request.setAttribute("organizactions", orgs);

                // Configurations
                ConfigurationLogic configurationLogic = new ConfigurationLogic();
                request.setAttribute("configurations",
                        configurationLogic.findByTypes(user, Configurations.TYPE_CHOOSE_ROLE));

                setForward(true);
                forward("/select_rol.jsp", request, response);
            }
        } else { // Contact not exists
            request.setAttribute("error", getResourceBundle(request).getString("msg.error_login.message"));
            setForward(true);
            forward("/index.jsp", request, response);
        }
    } catch (Exception e) {
        ExceptionUtil.evalueException(request, getResourceBundle(request), LOGGER, e);
        setForward(true);
        forward("/index.jsp", request, response);
    }
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTests.java

@Test
public void buildRequestSessionInvalidate() throws Exception {
    String sessionId = "session-id";
    webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);

    MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
    HttpSession sessionToRemove = actualRequest.getSession();
    sessionToRemove.invalidate();/*from w ww .ja va  2  s .co m*/

    assertThat(sessions.containsKey(sessionToRemove.getId()), equalTo(false));
    assertSingleSessionCookie("JSESSIONID=" + sessionToRemove.getId()
            + "; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/test; Domain=example.com");

    webRequest.removeAdditionalHeader("Cookie");
    requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);

    actualRequest = requestBuilder.buildRequest(servletContext);

    assertThat(actualRequest.getSession().isNew(), equalTo(true));
    assertThat(sessions.containsKey(sessionToRemove.getId()), equalTo(false));
}

From source file:org.uberfire.ext.security.server.BasicAuthSecurityFilter.java

@Override
public void doFilter(final ServletRequest _request, final ServletResponse _response, final FilterChain chain)
        throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) _request;
    final HttpServletResponse response = (HttpServletResponse) _response;

    HttpSession session = request.getSession(false);
    final User user = authenticationService.getUser();
    try {//  www .  j  a  va  2  s .  co  m
        if (user == null) {
            if (authenticate(request)) {
                chain.doFilter(request, response);
                if (response.isCommitted()) {
                    authenticationService.logout();
                }
            } else {
                challengeClient(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    } finally {
        // invalidate session only when it did not exists before this request
        // and was created as part of this request
        if (session == null) {
            session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
    }
}

From source file:com.onehippo.gogreen.login.HstConcurrentLoginFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req; // NOSONAR: req can always be cast to an HTTP servlet request
    HttpSession session = request.getSession(false);

    if (session != null) {
        String username = (request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : null);

        if (!StringUtils.isBlank(username)) {
            String usernameInSession = (String) session.getAttribute(USERNAME_ATTR);

            if (!username.equals(usernameInSession)) {
                registerUserSession(request, username);
            } else if (!isMySessionStillValid(session, username)) {
                log.debug(/*from ww w  .ja v a2 s  .c  o m*/
                        "HstConcurrentLoginFilter found another session had been logged in by {}. This session is to be invalidated.",
                        username);
                session.invalidate();
            }
        }
    }

    chain.doFilter(req, res);
}

From source file:it.scoppelletti.programmerpower.web.security.CasClient.java

/**
 * Rimuove una sessione autenticata./*from  w  w  w.ja v a  2s . c o  m*/
 * 
 * @param serviceTicket Ticket di servizio.
 */
public void removeAuthenticatedSession(String serviceTicket) {
    HttpSession session;

    if (Strings.isNullOrEmpty(serviceTicket)) {
        throw new ArgumentNullException("serviceTicket");
    }
    if (mySessionStorage == null) {
        throw new PropertyNotSetException(toString(), "sessionMappingStorage");
    }

    myLogger.debug("Removing service ticket {}.", serviceTicket);
    session = mySessionStorage.removeSessionByMappingId(serviceTicket);
    if (session == null) {
        return;
    }

    myLogger.debug("Invalidating session {}.", session.getId());
    try {
        session.invalidate();
    } catch (Exception ex) {
        myLogger.error("Failed to invalidate session.", ex);
    }
}

From source file:com.redsqirl.auth.UserInfoBean.java

private void invalidateSession(HttpSession sessionOtherMachine) {
    logger.warn("before invalidating session");
    try {/*from   ww w  .ja v  a2  s  . c o  m*/
        sessionOtherMachine.invalidate();
    } catch (Exception e) {
        logger.warn("Fail invalidate session: assume none created");
    }

    logger.warn("after invalidating session");
}

From source file:org.wso2.carbon.apimgt.authenticator.oidc.OIDCAuthenticator.java

public void logout() {
    String loggedInUser;/*w  w  w .j a v a 2s .  com*/
    String delegatedBy;
    Date currentTime = Calendar.getInstance().getTime();
    SimpleDateFormat date = new SimpleDateFormat("'['yyyy-MM-dd HH:mm:ss,SSSS']'");
    HttpSession session = getHttpSession();

    if (session != null) {
        loggedInUser = (String) session.getAttribute(ServerConstants.USER_LOGGED_IN);
        delegatedBy = (String) session.getAttribute("DELEGATED_BY");
        if (delegatedBy == null) {
            log.info("'" + loggedInUser + "' logged out at " + date.format(currentTime));
        } else {
            log.info("'" + loggedInUser + "' logged out at " + date.format(currentTime) + " delegated by "
                    + delegatedBy);
        }
        session.invalidate();
    }
}

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

public void testInvalidate(Manager manager) {
    HttpSession session = ((WADIHttpSession) manager.create(null)).getWrapper();
    session.invalidate();
    // TODO - what should we test here ?
}

From source file:org.fao.geonet.api.AllRequestsInterceptor.java

/**
 * Create the {@link UserSession} and add it to the HttpSession.
 *
 * If a crawler, check that session is null and if not, invalidate it.
 */// w w  w .j  av a2  s  .  co  m
private void createSessionForAllButNotCrawlers(HttpServletRequest request) {
    String userAgent = request.getHeader("user-agent");

    if (!isCrawler(userAgent)) {
        final HttpSession httpSession = request.getSession(true);
        UserSession session = (UserSession) httpSession.getAttribute(Jeeves.Elem.SESSION);
        if (session == null) {
            session = new UserSession();

            httpSession.setAttribute(Jeeves.Elem.SESSION, session);
            session.setsHttpSession(httpSession);

            if (Log.isDebugEnabled(Log.REQUEST)) {
                Log.debug(Log.REQUEST, "Session created for client : " + request.getRemoteAddr());
            }
        }
    } else {
        HttpSession httpSession = request.getSession(false);
        if (Log.isDebugEnabled(Log.REQUEST)) {
            Log.debug(Log.REQUEST, String.format("Crawler '%s' detected. Session MUST be null: %s", userAgent,
                    request.getSession(false) == null));
        }
        if (httpSession != null) {
            httpSession.invalidate();
        }
    }
}