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.cws.esolutions.security.filters.SessionAuthenticationFilter.java

public void doFilter(final ServletRequest sRequest, final ServletResponse sResponse,
        final FilterChain filterChain) throws IOException, ServletException {
    final String methodName = SessionAuthenticationFilter.CNAME
            + "#doFilter(final ServletRequest sRequest, final ServletResponse sResponse, final FilterChain filterChain) throws IOException, ServletException";

    if (DEBUG) {//ww  w  .ja  va 2  s.co m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServletRequest: {}", sRequest);
        DEBUGGER.debug("ServletResponse: {}", sResponse);
    }

    final HttpServletRequest hRequest = (HttpServletRequest) sRequest;
    final HttpServletResponse hResponse = (HttpServletResponse) sResponse;
    final HttpSession hSession = hRequest.getSession(false);
    final String requestURI = hRequest.getRequestURI();
    final String passwdPage = hRequest.getContextPath() + this.passwordURI;
    final StringBuilder redirectPath = new StringBuilder().append(hRequest.getContextPath() + this.loginURI)
            .append("?vpath=" + requestURI);

    if (DEBUG) {
        DEBUGGER.debug("HttpServletRequest: {}", hRequest);
        DEBUGGER.debug("HttpServletResponse: {}", hResponse);
        DEBUGGER.debug("HttpSession: {}", hSession);
        DEBUGGER.debug("RequestURI: {}", requestURI);
        DEBUGGER.debug("passwdPage: {}", passwdPage);
        DEBUGGER.debug("redirectPath: {}", redirectPath);

        DEBUGGER.debug("Dumping session content:");
        Enumeration<?> sessionEnumeration = hSession.getAttributeNames();

        while (sessionEnumeration.hasMoreElements()) {
            String element = (String) sessionEnumeration.nextElement();
            Object value = hSession.getAttribute(element);

            DEBUGGER.debug("Attribute: {}; Value: {}", element, value);
        }

        DEBUGGER.debug("Dumping request content:");
        Enumeration<?> requestEnumeration = hRequest.getAttributeNames();

        while (requestEnumeration.hasMoreElements()) {
            String element = (String) requestEnumeration.nextElement();
            Object value = hRequest.getAttribute(element);

            DEBUGGER.debug("Attribute: {}; Value: {}", element, value);
        }

        DEBUGGER.debug("Dumping request parameters:");
        Enumeration<?> paramsEnumeration = hRequest.getParameterNames();

        while (paramsEnumeration.hasMoreElements()) {
            String element = (String) paramsEnumeration.nextElement();
            Object value = hRequest.getParameter(element);

            DEBUGGER.debug("Parameter: {}; Value: {}", element, value);
        }
    }

    if (StringUtils.equals(this.loginURI, requestURI)) {
        if (DEBUG) {
            DEBUGGER.debug("Request authenticated. No action taken !");
        }

        filterChain.doFilter(sRequest, sResponse);

        return;
    }

    if ((this.ignoreURIs != null) && (this.ignoreURIs.length != 0)) {
        if (Arrays.asList(this.ignoreURIs).contains("ALL")) {
            if (DEBUG) {
                DEBUGGER.debug("ALL URIs are ignored. Breaking ...");
            }

            filterChain.doFilter(sRequest, sResponse);

            return;
        }

        // hostname isnt in ignore list
        for (String uri : this.ignoreURIs) {
            uri = hRequest.getContextPath().trim() + uri.trim();

            if (DEBUG) {
                DEBUGGER.debug(uri);
                DEBUGGER.debug(requestURI);
            }

            if (StringUtils.contains(requestURI, uri)) {
                // ignore
                if (DEBUG) {
                    DEBUGGER.debug("URI matched to ignore list - breaking out");
                }

                filterChain.doFilter(sRequest, sResponse);

                return;
            }
        }
    }

    if (hRequest.isRequestedSessionIdFromURL()) {
        ERROR_RECORDER.error("Session found is from URL. Redirecting request to " + hRequest.getContextPath()
                + this.loginURI);

        // invalidate the session
        hRequest.getSession(false).invalidate();
        hSession.removeAttribute(SessionAuthenticationFilter.USER_ACCOUNT);
        hSession.invalidate();

        hResponse.sendRedirect(hRequest.getContextPath() + this.loginURI);

        return;
    }

    Enumeration<?> sessionAttributes = hSession.getAttributeNames();

    if (DEBUG) {
        DEBUGGER.debug("Enumeration<String>: {}", sessionAttributes);
    }

    while (sessionAttributes.hasMoreElements()) {
        String element = (String) sessionAttributes.nextElement();

        if (DEBUG) {
            DEBUGGER.debug("element: {}", element);
        }

        Object value = hSession.getAttribute(element);

        if (DEBUG) {
            DEBUGGER.debug("sessionValue: {}", value);
        }

        if (value instanceof UserAccount) {
            UserAccount userAccount = (UserAccount) value;

            if (DEBUG) {
                DEBUGGER.debug("UserAccount: {}", userAccount);
            }

            if (userAccount.getStatus() != null) {
                switch (userAccount.getStatus()) {
                case EXPIRED:
                    if ((!(StringUtils.equals(requestURI, passwdPage)))) {
                        ERROR_RECORDER.error(
                                "Account is expired and this request is not for the password page. Redirecting !");

                        hResponse.sendRedirect(hRequest.getContextPath() + this.passwordURI);

                        return;
                    }

                    filterChain.doFilter(sRequest, sResponse);

                    return;
                case RESET:
                    if ((!(StringUtils.equals(requestURI, passwdPage)))) {
                        ERROR_RECORDER.error(
                                "Account has status RESET and this request is not for the password page. Redirecting !");

                        hResponse.sendRedirect(hRequest.getContextPath() + this.passwordURI);

                        return;
                    }

                    filterChain.doFilter(sRequest, sResponse);

                    return;
                case SUCCESS:
                    filterChain.doFilter(sRequest, sResponse);

                    return;
                default:
                    break;
                }
            }
        }
    }

    // no user account in the session
    ERROR_RECORDER.error("Session contains no existing user account. Redirecting request to "
            + hRequest.getContextPath() + this.loginURI);

    // invalidate the session
    hSession.removeAttribute(SessionAuthenticationFilter.USER_ACCOUNT);
    hSession.invalidate();

    if (StringUtils.isNotEmpty(hRequest.getQueryString())) {
        redirectPath.append("?" + hRequest.getQueryString());
    }

    if (DEBUG) {
        DEBUGGER.debug("redirectPath: {}", redirectPath.toString());
    }

    hResponse.sendRedirect(URLEncoder.encode(redirectPath.toString(), systemConfig.getEncoding()));

    return;
}

From source file:net.shopxx.controller.shop.LoginController.java

/**
 * ??//from   ww  w .j  a v a  2  s  . c  o  m
 */
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public @ResponseBody Message submit(String captchaId, String captcha, String username,
        HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    String password = rsaService.decryptParameter("enPassword", request);
    rsaService.removePrivateKey(request);

    if (!captchaService.isValid(CaptchaType.memberLogin, captchaId, captcha)) {
        return Message.error("shop.captcha.invalid");
    }
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        return Message.error("shop.common.invalid");
    }
    Member member;
    Setting setting = SettingUtils.get();
    if (setting.getIsEmailLogin() && username.contains("@")) {
        List<Member> members = memberService.findListByEmail(username);
        if (members.isEmpty()) {
            member = null;
        } else if (members.size() == 1) {
            member = members.get(0);
        } else {
            return Message.error("shop.login.unsupportedAccount");
        }
    } else {
        member = memberService.findByUsername(username);
    }
    if (member == null) {
        return Message.error("shop.login.unknownAccount");
    }
    if (!member.getIsEnabled()) {
        return Message.error("shop.login.disabledAccount");
    }
    if (member.getIsLocked()) {
        if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.member)) {
            int loginFailureLockTime = setting.getAccountLockTime();
            if (loginFailureLockTime == 0) {
                return Message.error("shop.login.lockedAccount");
            }
            Date lockedDate = member.getLockedDate();
            Date unlockDate = DateUtils.addMinutes(lockedDate, loginFailureLockTime);
            if (new Date().after(unlockDate)) {
                member.setLoginFailureCount(0);
                member.setIsLocked(false);
                member.setLockedDate(null);
                memberService.update(member);
            } else {
                return Message.error("shop.login.lockedAccount");
            }
        } else {
            member.setLoginFailureCount(0);
            member.setIsLocked(false);
            member.setLockedDate(null);
            memberService.update(member);
        }
    }
    if (member.getActivateEmail() == null || !member.getActivateEmail()) {
        return Message.error("??");
    }

    if (!DigestUtils.md5Hex(password).equals(member.getPassword())) {
        int loginFailureCount = member.getLoginFailureCount() + 1;
        if (loginFailureCount >= setting.getAccountLockCount()) {
            member.setIsLocked(true);
            member.setLockedDate(new Date());
        }
        member.setLoginFailureCount(loginFailureCount);
        memberService.update(member);
        if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.member)) {
            return Message.error("shop.login.accountLockCount", setting.getAccountLockCount());
        } else {
            return Message.error("shop.login.incorrectCredentials");
        }
    }
    member.setLoginIp(request.getRemoteAddr());
    member.setLoginDate(new Date());
    member.setLoginFailureCount(0);
    memberService.update(member);

    Cart cart = cartService.getCurrent();
    if (cart != null) {
        if (cart.getMember() == null) {
            cartService.merge(member, cart);
            WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME);
            WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME);
        }
    }

    Map<String, Object> attributes = new HashMap<String, Object>();
    Enumeration<?> keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        attributes.put(key, session.getAttribute(key));
    }
    session.invalidate();
    session = request.getSession();
    for (Entry<String, Object> entry : attributes.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }

    session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), username));
    WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername());

    return SUCCESS_MESSAGE;
}

From source file:egovframework.example.sample.web.EgovSampleController.java

@RequestMapping(value = "/logout.do", method = RequestMethod.GET)
public String logout(Model model, HttpServletRequest request) throws Exception {
    HttpSession hs = request.getSession();
    hs.invalidate();

    model.addAttribute("login", "login.jsp");
    //model.addAttribute("main", "defaultMain.jsp");
    return "forward:/home.do";
}

From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java

private void challengeOrPassThrough(FilterChain chain, HttpServletRequest req, HttpServletResponse res,
        HttpSession session) throws IOException, ServletException {
    try {//from   w  w w .  j av a2s .co  m
        // In this mode we can only use vaulted credentials. Do not proxy any request headers.
        String userId = AuthenticationUtil.getUserId(req);

        if (userId == null) {
            // If we are as yet unauthenticated but have external authentication, do a ping check as the external user.
            // This will either establish the session or throw us out to log in as someone else!
            userId = req.getRemoteUser();
            // Set the external auth flag so the UI knows we are using SSO etc.
            session.setAttribute(UserFactory.SESSION_ATTRIBUTE_EXTERNAL_AUTH, Boolean.TRUE);
            if (userId != null && logger.isDebugEnabled())
                logger.debug("Initial login from externally authenticated user " + userId);
            setExternalAuthSession(session);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Validating repository session for " + userId);
        }

        if (userId != null && !userId.equalsIgnoreCase(req.getRemoteUser())
                && session.getAttribute(NTLM_AUTH_DETAILS) == null
                && session.getAttribute(AUTH_BY_KERBEROS) == null) // Firefox & Chrome hack for MNT-15561
        {
            session.removeAttribute(UserFactory.SESSION_ATTRIBUTE_EXTERNAL_AUTH);
        }

        Connector conn = connectorService.getConnector(this.endpoint, userId, session);

        // ALF-10785: We must pass through the language header to set up the session in the correct locale
        ConnectorContext ctx;
        if (req.getHeader(HEADER_ACCEPT_LANGUAGE) != null) {
            if (logger.isDebugEnabled())
                logger.debug("Accept-Language header present: " + req.getHeader(HEADER_ACCEPT_LANGUAGE));
            ctx = new ConnectorContext(null,
                    Collections.singletonMap(HEADER_ACCEPT_LANGUAGE, req.getHeader(HEADER_ACCEPT_LANGUAGE)));
        } else {
            ctx = new ConnectorContext();
        }

        Response remoteRes = conn.call("/touch", ctx);
        if (Status.STATUS_UNAUTHORIZED == remoteRes.getStatus().getCode()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Repository session timed out - restarting auth process...");
            }

            String authHdr = remoteRes.getStatus().getHeaders().get(HEADER_WWWAUTHENTICATE);
            if (authHdr != null) {
                // restart SSO login as the repo has timed us out
                restartAuthProcess(session, req, res, authHdr);
            } else {
                // Don't invalidate the session if we've already got external authentication - it may result in us
                // having to reauthenticate externally too!
                if (req.getRemoteUser() == null) {
                    session.invalidate();
                }
                // restart manual login
                redirectToLoginPage(req, res);
            }
            return;
        } else {
            onSuccess(req, res, session, userId);

            // we have local auth in the session and the repo session is also valid
            // this means we do not need to perform any further auth handshake
            if (logger.isDebugEnabled()) {
                logger.debug("Authentication not required, chaining ...");
            }

            chain.doFilter(req, res);
            return;
        }
    } catch (ConnectorServiceException cse) {
        throw new PlatformRuntimeException("Incorrectly configured endpoint ID: " + this.endpoint);
    }
}

From source file:com.sundevils.web.controller.TopController.java

@RequestMapping(value = "/authorizationRequest**", method = { RequestMethod.POST, RequestMethod.GET })
public ModelAndView authRequest(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException, SQLException {
    String user = "";
    String role = "";
    String requestType = "";
    String[] authRequests = null;
    role = (String) session.getAttribute("Role");
    if (role == null) {
        ModelAndView model = new ModelAndView();
        model.setViewName("index");
        return model;
    } else if (role.equals("USER") || role.equals("ADMIN")) {
        ModelAndView model = new ModelAndView();
        model.setViewName("accessRequests");
        List<TransactionRequestDetails> transReqstdetails = new ArrayList<TransactionRequestDetails>();
        RequestAuthorize authorize = new RequestAuthorize();

        if (request.getParameter("submit") != null) {
            authRequests = request.getParameterValues("check");
            if (authRequests == null) {
                model.addObject("Select", "No user selected");
                if (role.equals("USER")) {
                    user = (String) session.getAttribute("USERNAME");
                } else if (role.equals("ADMIN")) {
                    user = (String) session.getAttribute("USERNAME");
                }//from   w w w  .j a va 2s . c  o m
                ResultSet rs = authorize.getRequestHandler(user);
                try {
                    while (rs.next()) {
                        TransactionRequestDetails view = new TransactionRequestDetails();
                        view.setRequstID(rs.getString("requestid"));
                        view.setRqstFrom(rs.getString("requestfrom"));
                        view.setRqstTime(rs.getString("requestdate"));
                        view.setRqstStatus(rs.getString("requeststatus"));
                        view.setRqstFor(rs.getString("requestfor"));
                        transReqstdetails.add(view);
                    }

                    model.addObject("requestApprove", transReqstdetails);
                } catch (Exception e) {
                    model = new ModelAndView();
                    LoginHandler handler_logout = new LoginHandler();
                    String userName = (String) session.getAttribute("USERNAME");
                    handler_logout.updateLoggedInFlag(userName, 0);
                    session.invalidate();
                    model.setViewName("index");
                    LOG.error("Issue while authorizing the account" + e.getMessage());
                }
                return model;
            }
            requestType = request.getParameter("Type");
            authorize.updateRequestStatus(requestType, authRequests);
        }
        if (role.equals("USER")) {
            user = (String) session.getAttribute("USERNAME");
        } else if (role.equals("ADMIN")) {
            user = (String) session.getAttribute("USERNAME");
        }
        ResultSet rs = authorize.getRequestHandler(user);
        try {
            while (rs.next()) {
                TransactionRequestDetails view = new TransactionRequestDetails();
                view.setRequstID(rs.getString("requestid"));
                view.setRqstFrom(rs.getString("requestfrom"));
                view.setRqstTime(rs.getString("requestdate"));
                view.setRqstStatus(rs.getString("requeststatus"));
                view.setRqstFor(rs.getString("requestfor"));
                transReqstdetails.add(view);
            }

            model.addObject("requestApprove", transReqstdetails);
        } catch (Exception e) {
            model = new ModelAndView();
            LoginHandler handler_logout = new LoginHandler();
            String userName = (String) session.getAttribute("USERNAME");
            handler_logout.updateLoggedInFlag(userName, 0);
            session.invalidate();
            model.setViewName("index");
            LOG.error("Issue while authorizing the account" + e.getMessage());
        }

        return model;
    } else {
        ModelAndView model = new ModelAndView();
        model.setViewName("login");
        return model;
    }
}

From source file:org.rhq.enterprise.gui.authentication.AuthenticateUserAction.java

/**
 * @see TilesAction#execute(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse)
 *//*from   www .  j a  v  a  2  s.c  om*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Log log = LogFactory.getLog(AuthenticateUserAction.class.getName());

    HttpSession session = request.getSession(true);
    LogonForm logonForm = (LogonForm) form;
    ServletContext ctx = getServlet().getServletContext();

    WebUser webUser = null;
    Map<String, Boolean> userGlobalPermissionsMap = new HashMap<String, Boolean>();
    boolean needsRegistration = false;

    try {
        // authenticate the credentials
        SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager();
        Subject subject = subjectManager.login(logonForm.getJ_username(), logonForm.getJ_password());
        Integer sessionId = subject.getSessionId(); // this is the RHQ session ID, not related to the HTTP session

        log.debug("Logged in as [" + logonForm.getJ_username() + "] with session id [" + sessionId + "]");

        boolean hasPrincipal = true;
        if (subject.getId() == 0) {
            // Subject with a ID of 0 means the subject wasn't in the database but the login succeeded.
            // This means the login method detected that LDAP authenticated the user and just gave us a dummy subject.
            // Set the needs-registration flag so we can eventually steer the user to the LDAP registration workflow.
            needsRegistration = true;
        }

        if (!needsRegistration) {
            subject = subjectManager.loadUserConfiguration(subject.getId());
            subject.setSessionId(sessionId); // put the transient data back into our new subject

            if (subject.getUserConfiguration() == null) {
                subject.setUserConfiguration((Configuration) ctx.getAttribute(Constants.DEF_USER_PREFS));
                subject = subjectManager.updateSubject(subject, subject);
                subject.setSessionId(sessionId); // put the transient data back into our new subject
            }

            // look up the user's permissions
            Set<Permission> all_permissions = LookupUtil.getAuthorizationManager()
                    .getExplicitGlobalPermissions(subject);

            for (Permission permission : all_permissions) {
                userGlobalPermissionsMap.put(permission.toString(), Boolean.TRUE);
            }
        }

        webUser = new WebUser(subject, hasPrincipal);
    } catch (Exception e) {
        String msg = e.getMessage().toLowerCase();
        if ((msg.indexOf("username") >= 0) || (msg.indexOf("password") >= 0)) {
            request.setAttribute(Constants.LOGON_STATUS, "login.info.bad");
        } else {
            log.error("Could not log into the web application", e);
            request.setAttribute(Constants.LOGON_STATUS, "login.bad.backend");
        }

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

    // compute the post-login destination
    ActionForward af;
    if (needsRegistration) {
        // Since we are authenticating the user with LDAP and the user has never logged in before,
        // that user has no subject record yet. We need to send him through the LDAP registration workflow.
        log.debug("LDAP registration required for user [" + logonForm.getJ_username() + "]");
        af = new ActionForward(URL_REGISTER);
    } else {
        // if the user's session timed out, we "bookmarked" the url that he was going to
        // so that we can send him there after login. otherwise, he gets the dashboard.
        String url = getBookmarkedUrl(session);
        if ((url == null) || url.equals("/Logout.do")) {
            url = URL_DASHBOARD;
        }
        if (url.toLowerCase().indexOf("ajax") != -1) {
            // we can't return to a URL that was a partial page request
            // because the view no longer exists, and will blow up.
            // instead, redirect back to the last saved URL
            url = webUser.getWebPreferences().getLastVisitedURL(2);
            log.info("Bypassing partial-page with " + url);
        }

        af = new ActionForward(url);
    }

    af.setRedirect(true);

    // now that we've constructed a forward to the bookmarked url,
    // if any, forget the old session and start a new one,
    // setting the web user to show that we're logged in
    session.invalidate();
    session = request.getSession(true);
    SessionUtils.setWebUser(session, webUser);
    session.setAttribute(Constants.USER_OPERATIONS_ATTR, userGlobalPermissionsMap);

    if (needsRegistration) {
        // will be cleaned out during registration
        session.setAttribute(Constants.PASSWORD_SES_ATTR, logonForm.getJ_password());
    }

    return af;
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/credential/logout")
@POST//from  ww w.  j  a va2  s.c  o  m
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public Response logout(@Context ServletConfig sc, @Context HttpServletRequest httpServletRequest) {
    HttpSession session = httpServletRequest.getSession(false);
    if (session != null)
        session.invalidate();
    return Response.ok("logout").build();
}

From source file:com.sundevils.web.controller.TopController.java

@RequestMapping(value = "/unlockaccount**", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView unlockAccount(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws SQLException {
    ModelAndView model = new ModelAndView();
    String userNameSession = (String) session.getAttribute("USERNAME");
    model.addObject("user", userNameSession);
    LoginHandler handler;//  w  w  w.  ja  v  a 2  s .  c om
    handler = new LoginHandler();
    String emailAddress = "";
    String user = "";
    String ssnNumber = "";
    String admin = "";
    String ssn = "";
    String email = "";
    ViewAccounts acc = new ViewAccounts();
    if (request.getParameter("submit") != null) {

        ssnNumber = request.getParameter("ssn");
        emailAddress = request.getParameter("email");
        if (ssnNumber.equals("") || emailAddress.equals("")) {
            model.addObject("emptyFields", "All fields are mandatory");
            model.setViewName("unlockaccount");
        } else {
            ResultSet rs = acc.requestPersonalDetailsHandler(userNameSession);
            ResultSet rs1 = handler.requestAdminHandler("ADMIN");
            ResultSet rs2 = handler.checkRequestExist(userNameSession, "unlock", "pending");
            if (rs.next() && rs1.next()) {
                if (!rs2.next()) {
                    user = rs.getString("username");
                    email = rs.getString("email");
                    ssn = rs.getString("ssn");
                    admin = rs1.getString("username");
                    if (email.equals(emailAddress) && ssn.equals(ssnNumber)) {
                        handler.insertUnlockRequests(user, "unlock", user, admin, "test", "pending", "test",
                                "test");
                        model.addObject("successunlock",
                                "Your request has been generated successfully. You will be notified via email when your account is ready for use. You will be automatically redirected to login page within few seconds.");
                        model.setViewName("success");
                    } else {
                        model.addObject("incorrectFields", "Either email address and/or ssn is incorrect");
                        model.setViewName("unlockaccount");
                    }
                } else {
                    model.addObject("alreadypresent",
                            "You have already submitted the request. Please bear with us.");
                    model.setViewName("unlockaccount");
                }
            } else {
                model.addObject("incorrectFields", "Either email address and/or ssn is incorrect");
                model.setViewName("unlockaccount");
            }
        }
    } else {
        handler.updateLoggedInFlag(userNameSession, 0);
        session.invalidate();
        model.setViewName("index");
    }
    return model;
}

From source file:org.n52.v3d.terrainserver.povraywts.WebTerrainServlet.java

private WTSSession setUpSession(WTSSession pWtsSession, boolean pCacheScene, HttpServletRequest pRequest,
        VgEnvelope pBBox, String pDrape, String pWmsLayers) {
    HttpSession lSession;
    TempFileHandler lRequTmpMngr;//  ww w. ja  v a2s .  co  m
    TempFileHandler lSessionTmpMngr = null;

    if (pCacheScene) {
        lSession = pRequest.getSession(true);
        if (lSession == null)
            throw new T3dException("Could not get session object...", 102);

        lRequTmpMngr = new TempFileHandler();

        if (lSession.isNew()) {
            lSession.setMaxInactiveInterval(mSessionMaxInactiveInterval);
            lSessionTmpMngr = new TempFileHandler();
            lSession.setAttribute("shndlr_" + lSession.getId(), lSessionTmpMngr);
        } else {
            lSessionTmpMngr = (TempFileHandler) lSession.getAttribute("shndlr_" + lSession.getId());
            if (lSessionTmpMngr == null) {
                // Session nicht neu, aber lTmpMngr nicht in Session, Fall tritt z. B. in JSP-Client auf.
                lSessionTmpMngr = new TempFileHandler();
                lSession.setAttribute("shndlr_" + lSession.getId(), lSessionTmpMngr);
            } else {
                // Parameterwerte der letzten Anfrage holen...
                VgEnvelope oldBBox = (VgEnvelope) lSession.getAttribute("rqBBOX_" + lSession.getId()); // BBOX
                String oldDrape = (String) lSession.getAttribute("rqDRAPE_" + lSession.getId()); // DRAPE
                String oldWmsLayers = (String) lSession.getAttribute("rqWMSLAYERS_" + lSession.getId()); // WMSLAYERS
                boolean changesBBox = false, changesDrp = false;
                // BBOX seit letzter Anfrage gendert?
                if (oldBBox != null && !oldBBox.isSpatiallyEquivalent(pBBox))
                    changesBBox = true;
                // DRAPE seit letzter Anfrage gendert?
                if (oldDrape != null && oldDrape.compareTo(pDrape) != 0)
                    changesDrp = true;
                // WMSLAYERS seit letzter Anfrage gendert?
                if (oldWmsLayers != null && oldWmsLayers.compareTo(pWmsLayers) != 0)
                    changesDrp = true;

                // ... und im Falle relevanter nderungen Cache-Inhalte leeren:
                if (changesBBox) {
                    lSession.removeAttribute("terrain_" + lSession.getId());
                    lSessionTmpMngr
                            .removeTempFile((String) lSession.getAttribute("demgif_" + lSession.getId()));
                    lSession.removeAttribute("demgif_" + lSession.getId());
                }
                if (changesDrp || changesBBox) {
                    lSessionTmpMngr.removeTempFile((String) lSession.getAttribute("drape_" + lSession.getId()));
                    lSession.removeAttribute("drape_" + lSession.getId());
                }
            }
            lSession.setAttribute("rqBBOX_" + lSession.getId(), pBBox); // BBOX in Session legen
            lSession.setAttribute("rqDRAPE_" + lSession.getId(), pDrape); // DRAPE in Session legen
            lSession.setAttribute("rqWMSLAYERS_" + lSession.getId(), pWmsLayers); // WMSLAYERS in Session legen
        }
    } else {
        // Fr CACHESCENE=false ggf. Objekte aus vorherigen Aufrufen mit CACHESCENE=true aus Session entfernen:
        lSession = pRequest.getSession(false);
        if (lSession != null) {
            lSession.removeAttribute("shndlr_" + lSession.getId());
            lSession.removeAttribute("terrain_" + lSession.getId());
            lSession.removeAttribute("drape_" + lSession.getId());
            lSession.removeAttribute("demgif_" + lSession.getId());
            lSession.invalidate();
        }
        lRequTmpMngr = new TempFileHandler();
    }
    pWtsSession.setHttpSession(lSession);
    pWtsSession.setRequTempFileHandler(lRequTmpMngr);
    pWtsSession.setSessionTempFileHandler(lSessionTmpMngr);
    return pWtsSession;
}

From source file:com.sundevils.web.controller.TopController.java

@RequestMapping(value = { "/transact" }, method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView transactPage(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException {
    String role = (String) session.getAttribute("Role");
    if (role == null) {
        ModelAndView model = new ModelAndView();
        model.setViewName("index");
        return model;
    } else if (role.equals("EMPLOYEE")) {
        ModelAndView model = new ModelAndView();
        CreateTransactionHandler handler = new CreateTransactionHandler();
        String userName = "";
        String transamount = "";
        String sourceacc = "";
        String destacc = "";
        String type = "";

        if (request.getParameter("submit") != null) {
            userName = request.getParameter("username");
            transamount = request.getParameter("transamount");
            sourceacc = request.getParameter("sourceacc");
            destacc = request.getParameter("destacc");

            if (userName.isEmpty() || transamount.isEmpty() || sourceacc.isEmpty() || destacc.isEmpty()) {
                model.addObject("success_msg", "Error: There are empty fields. Please rectify");
            } else if (!destacc.matches("[0-9]+$"))
                model.addObject("success_msg", "Enter account number in proper format");
            else if (sourceacc.equals(destacc))
                model.addObject("success_msg", "Source and destination account numbers can't be the same");
            else {
                CheckSourceAccountNumberHandler accounthandler = new CheckSourceAccountNumberHandler();
                String account_match_msg = (String) accounthandler.requestHandler(userName, sourceacc,
                        transamount);/*from   w w  w. ja  v a 2 s .c o m*/
                if (account_match_msg.equals("done"))
                    model.addObject("success_msg",
                            handler.transactionHandler(userName, transamount, sourceacc, destacc, type));
                else if (account_match_msg.equals("incorrect"))
                    model.addObject("success_msg", "Incorrect username or source account no.");
                else if (account_match_msg.equals("negative"))
                    model.addObject("success_msg", "Enter postive transaction amount");
                else if (account_match_msg.equals("NFE"))
                    model.addObject("success_msg", "Number format is wrong");
                else
                    model.addObject("success_msg", "Insufficient balance for the transaction");
            }

        }

        else {
            model.addObject("success_msg", "");
        }

        model.addObject("title", " Create Transaction");
        model.setViewName("create_transactions");
        return model;

    } else {
        ModelAndView model = new ModelAndView();
        LoginHandler handler = new LoginHandler();
        String userName = (String) session.getAttribute("USERNAME");
        handler.updateLoggedInFlag(userName, 0);
        session.invalidate();
        model.setViewName("index");
        return model;
    }
}